text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->

<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
           id="cordova-plugin-globalization"
      version="1.0.2">
    <name>Globalization</name>
    <description>Cordova Globalization Plugin</description>
    <license>Apache 2.0</license>
    <keywords>cordova,globalization</keywords>
    <repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-globalization.git</repo>
    <issue>https://issues.apache.org/jira/browse/CB/component/12320649</issue>

    <js-module src="www/GlobalizationError.js" name="GlobalizationError">
        <clobbers target="window.GlobalizationError" />
    </js-module>

    <js-module src="www/globalization.js" name="globalization">
        <clobbers target="navigator.globalization" />
    </js-module>

    <!-- android -->
    <platform name="android">
        <config-file target="res/xml/config.xml" parent="/*">
            <feature name="Globalization">
                <param name="android-package" value="org.apache.cordova.globalization.Globalization" />
            </feature>
        </config-file>

        <source-file src="src/android/Globalization.java" target-dir="src/org/apache/cordova/globalization" />
        <source-file src="src/android/GlobalizationError.java" target-dir="src/org/apache/cordova/globalization" />
    </platform>

    <!-- amazon-fireos -->
    <platform name="amazon-fireos">
        <config-file target="res/xml/config.xml" parent="/*">
            <feature name="Globalization">
                <param name="android-package" value="org.apache.cordova.globalization.Globalization" />
            </feature>
        </config-file>

        <source-file src="src/android/Globalization.java" target-dir="src/org/apache/cordova/globalization" />
        <source-file src="src/android/GlobalizationError.java" target-dir="src/org/apache/cordova/globalization" />
    </platform>

   <!-- ubuntu -->
   <platform name="ubuntu">
       <header-file src="src/ubuntu/globalization.h" />
       <source-file src="src/ubuntu/globalization.cpp" />

       <js-module src="www/ubuntu/globalization.js" name="Globalization1">
           <merges target="navigator.globalization" />
       </js-module>
   </platform>

    <!-- firefoxos -->
    <platform name="firefoxos">
        <js-module src="src/firefoxos/GlobalizationProxy.js" name="GlobalizationProxy">
            <runs />
        </js-module>
		<asset src="www/firefoxos/locales" target="locales" />
		<asset src="www/firefoxos/l10n.js" target="js/l10n.js" />
		<asset src="www/firefoxos/l10n_date.js" target="js/l10n_date.js" />
    </platform>

   <!-- ios -->
   <platform name="ios">
        <config-file target="config.xml" parent="/*">
            <feature name="Globalization">
                <param name="ios-package" value="CDVGlobalization" />
            </feature>
        </config-file>
        <header-file src="src/ios/CDVGlobalization.h" />
        <source-file src="src/ios/CDVGlobalization.m" />
    </platform>

    <!-- wp7 -->
    <platform name="wp7">
        <config-file target="config.xml" parent="/*">
            <feature name="Globalization">
                <param name="wp-package" value="Globalization"/>
            </feature>
        </config-file>

        <source-file src="src/wp/Globalization.cs" />
    </platform>

    <!-- wp8 -->
    <platform name="wp8">
        <config-file target="config.xml" parent="/*">
            <feature name="Globalization">
                <param name="wp-package" value="Globalization"/>
            </feature>
        </config-file>

        <source-file src="src/wp/Globalization.cs" />
        <source-file src="src/windows/GlobalizationProxy/GlobalizationProxy/Globalization/GlobalizationApiTypes.cs" />
        <source-file src="src/windows/GlobalizationProxy/GlobalizationProxy/Globalization/GlobalizationImpl.cs" />
    </platform>

    <!-- windows8 -->
    <platform name="windows8">
        <js-module src="src/windows/GlobalizationProxy.js" name="GlobalizationProxy">
            <runs/>
        </js-module>
        <framework src="src/Windows/GlobalizationProxy.winmd" custom="true"/>
    </platform>

    <!-- windows -->
    <platform name="windows">
        <js-module src="src/windows/GlobalizationProxy.js" name="GlobalizationProxy">
            <runs/>
        </js-module>
        <framework src="src/Windows/GlobalizationProxy.winmd" custom="true"/>
    </platform>

    <!-- tizen -->
    <platform name="tizen">
        <js-module src="src/tizen/GlobalizationProxy.js" name="GlobalizationProxy">
            <runs/>
        </js-module>
    </platform>

    <!-- blackberry10 -->
    <platform name="blackberry10">
        <source-file src="src/blackberry10/index.js" target-dir="Globalization" />
        <lib-file src="src/blackberry10/native/device/libGlobalization.so" arch="device" />
        <lib-file src="src/blackberry10/native/simulator/libGlobalization.so" arch="simulator" />
    </platform>

    <!-- browser -->
    <platform name="browser">
        <js-module src="www/browser/moment.js" name="moment">
            <runs/>
        </js-module>
        <js-module src="src/browser/GlobalizationProxy.js" name="GlobalizationProxy">
            <runs/>
        </js-module>
    </platform>
</plugin>


text:
id: components-and-props
title: Components and Props
permalink: docs/components-and-props.html
redirect_from:
  - "docs/reusable-components.html"
  - "docs/transferring-props.html"
  - "tips/props-in-getInitialState-as-anti-pattern.html"
  - "tips/communicate-between-components.html"
prev: rendering-elements.html
next: state-and-lifecycle.html
---

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.

Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen.

## Functional and Class Components

The simplest way to define a component is to write a JavaScript function:

```js
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
```

This function is a valid React component because it accepts a single "props" object argument with data and returns a React element. We call such components "functional" because they are literally JavaScript functions.

You can also use an [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes) to define a component:

```js
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
```

The above two components are equivalent from React's point of view.

Classes have some additional features that we will discuss in the [next sections](/react/docs/state-and-lifecycle.html). Until then, we will use functional components for their conciseness.

## Rendering a Component

Previously, we only encountered React elements that represent DOM tags:

```js
const element = <div />;
```

However, elements can also represent user-defined components:

```js
const element = <Welcome name="Sara" />;
```

When React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object "props".

For example, this code renders "Hello, Sara" on the page:

```js{1,5}
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);
```

[Try it on CodePen.](http://codepen.io/gaearon/pen/YGYmEG?editors=0010)

Let's recap what happens in this example:

1. We call `ReactDOM.render()` with the `<Welcome name="Sara" />` element.
2. React calls the `Welcome` component with `{name: 'Sara'}` as the props.
3. Our `Welcome` component returns a `<h1>Hello, Sara</h1>` element as the result.
4. React DOM efficiently updates the DOM to match `<h1>Hello, Sara</h1>`.

>**Caveat:**
>
>Always start component names with a capital letter.
>
>For example, `<div />` represents a DOM tag, but `<Welcome />` represents a component and requires `Welcome` to be in scope.

## Composing Components

Components can refer to other components in their output. This lets us use the same component abstraction for any level of detail. A button, a form, a dialog, a screen: in React apps, all those are commonly expressed as components.

For example, we can create an `App` component that renders `Welcome` many times:

```js{8-10}
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
```

[Try it on CodePen.](http://codepen.io/gaearon/pen/KgQKPr?editors=0010)

Typically, new React apps have a single `App` component at the very top. However, if you integrate React into an existing app, you might start bottom-up with a small component like `Button` and gradually work your way to the top of the view hierarchy.

>**Caveat:**
>
>Components must return a single root element. This is why we added a `<div>` to contain all the `<Welcome />` elements.

## Extracting Components

Don't be afraid to split components into smaller components.

For example, consider this `Comment` component:

```js
function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <img className="Avatar"
          src={props.author.avatarUrl}
          alt={props.author.name}
        />
        <div className="UserInfo-name">
          {props.author.name}
        </div>
      </div>
      <div className="Comment-text">
        {props.text}
      </div>
      <div className="Comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}
```

[Try it on CodePen.](http://codepen.io/gaearon/pen/VKQwEo?editors=0010)

It accepts `author` (an object), `text` (a string), and `date` (a date) as props, and describes a comment on a social media website.

This component can be tricky to change because of all the nesting, and it is also hard to reuse individual parts of it. Let's extract a few components from it.

First, we will extract `Avatar`:

```js{3-6}
function Avatar(props) {
  return (
    <img className="Avatar"
      src={props.user.avatarUrl}
      alt={props.user.name}
    />
  );
}
```

The `Avatar` doesn't need to know that it is being rendered inside a `Comment`. This is why we have given its prop a more generic name: `user` rather than `author`.

We recommend naming props from the component's own point of view rather than the context in which it is being used.

We can now simplify `Comment` a tiny bit:

```js{5}
function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <Avatar user={props.author} />
        <div className="UserInfo-name">
          {props.author.name}
        </div>
      </div>
      <div className="Comment-text">
        {props.text}
      </div>
      <div className="Comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}
```

Next, we will extract a `UserInfo` component that renders an `Avatar` next to user's name:

```js{3-8}
function UserInfo(props) {
  return (
    <div className="UserInfo">
      <Avatar user={props.user} />
      <div className="UserInfo-name">
        {props.user.name}
      </div>
    </div>
  );
}
```

This lets us simplify `Comment` even further:

```js{4}
function Comment(props) {
  return (
    <div className="Comment">
      <UserInfo user={props.author} />
      <div className="Comment-text">
        {props.text}
      </div>
      <div className="Comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}
```

[Try it on CodePen.](http://codepen.io/gaearon/pen/rrJNJY?editors=0010)

Extracting components might seem like grunt work at first, but having a palette of reusable components pays off in larger apps. A good rule of thumb is that if a part of your UI is used several times (`Button`, `Panel`, `Avatar`), or is complex enough on its own (`App`, `FeedStory`, `Comment`), it is a good candidate to be a reusable component.

## Props are Read-Only

Whether you declare a component [as a function or a class](#functional-and-class-components), it must never modify its own props. Consider this `sum` function:

```js
function sum(a, b) {
  return a + b;
}
```

Such functions are called ["pure"](https://en.wikipedia.org/wiki/Pure_function) because they do not attempt to change their inputs, and always return the same result for the same inputs.

In contrast, this function is impure because it changes its own input:

```js
function withdraw(account, amount) {
  account.total -= amount;
}
```

React is pretty flexible but it has a single strict rule:

**All React components must act like pure functions with respect to their props.**

Of course, application UIs are dynamic and change over time. In the [next section](/react/docs/state-and-lifecycle.html), we will introduce a new concept of "state". State allows React components to change their output over time in response to user actions, network responses, and anything else, without violating this rule.

redpajama_set_name: RedPajamaGithub


text:
import sys
import os
from .sqlite import JsonSqliteDict
from subprocess import Popen, PIPE
from ConfigParser import NoSectionError
import json
from twisted.web import resource

from scrapyd.spiderqueue import SqliteSpiderQueue
from scrapy.utils.python import stringify_dict, unicode_to_str
from scrapyd.config import Config

class JsonResource(resource.Resource):

    json_encoder = json.JSONEncoder()

    def render(self, txrequest):
        r = resource.Resource.render(self, txrequest)
        return self.render_object(r, txrequest)

    def render_object(self, obj, txrequest):
        r = self.json_encoder.encode(obj) + "\n"
        txrequest.setHeader('Content-Type', 'application/json')
        txrequest.setHeader('Access-Control-Allow-Origin', '*')
        txrequest.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE')
        txrequest.setHeader('Access-Control-Allow-Headers',' X-Requested-With')
        txrequest.setHeader('Content-Length', len(r))
        return r

class UtilsCache:
    # array of project name that need to be invalided
    invalid_cached_projects = []

    def __init__(self):
        self.cache_manager = JsonSqliteDict(table="utils_cache_manager")

    # Invalid the spider's list's cache of a given project (by name)
    @staticmethod
    def invalid_cache(project):
        UtilsCache.invalid_cached_projects.append(project)

    def __getitem__(self, key):
        for p in UtilsCache.invalid_cached_projects:
            if p in self.cache_manager:
                del self.cache_manager[p]
        UtilsCache.invalid_cached_projects[:] = []
        return self.cache_manager[key]

    def __setitem__(self, key, value):
        self.cache_manager[key] = value

def get_spider_queues(config):
    """Return a dict of Spider Quees keyed by project name"""
    dbsdir = config.get('dbs_dir', 'dbs')
    if not os.path.exists(dbsdir):
        os.makedirs(dbsdir)
    d = {}
    for project in get_project_list(config):
        dbpath = os.path.join(dbsdir, '%s.db' % project)
        d[project] = SqliteSpiderQueue(dbpath)
    return d

def get_project_list(config):
    """Get list of projects by inspecting the eggs dir and the ones defined in
    the scrapyd.conf [settings] section
    """
    eggs_dir = config.get('eggs_dir', 'eggs')
    if os.path.exists(eggs_dir):
        projects = os.listdir(eggs_dir)
    else:
        projects = []
    try:
        projects += [x[0] for x in config.cp.items('settings')]
    except NoSectionError:
        pass
    return projects

def get_crawl_args(message):
    """Return the command-line arguments to use for the scrapy crawl process
    that will be started for this message
    """
    msg = message.copy()
    args = [unicode_to_str(msg['_spider'])]
    del msg['_project'], msg['_spider']
    settings = msg.pop('settings', {})
    for k, v in stringify_dict(msg, keys_only=False).items():
        args += ['-a']
        args += ['%s=%s' % (k, v)]
    for k, v in stringify_dict(settings, keys_only=False).items():
        args += ['-s']
        args += ['%s=%s' % (k, v)]
    return args

def get_spider_list(project, runner=None, pythonpath=None):
    """Return the spider list from the given project, using the given runner"""
    if "cache" not in get_spider_list.__dict__:
        get_spider_list.cache = UtilsCache()
    try:
        return get_spider_list.cache[project]
    except KeyError:
        pass
    if runner is None:
        runner = Config().get('runner')
    env = os.environ.copy()
    env['SCRAPY_PROJECT'] = project
    if pythonpath:
        env['PYTHONPATH'] = pythonpath
    pargs = [sys.executable, '-m', runner, 'list']
    proc = Popen(pargs, stdout=PIPE, stderr=PIPE, env=env)
    out, err = proc.communicate()
    if proc.returncode:
        msg = err or out or 'unknown error'
        raise RuntimeError(msg.splitlines()[-1])
    tmp = out.splitlines();
    get_spider_list.cache[project] = tmp
    return tmp


text:
<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE programlisting PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY PRODUCT "JSound - valid JSON data">
<!ENTITY BOOKID "JSound">
<!ENTITY YEAR "2013">
<!ENTITY HOLDER "| You need to change the HOLDER entity in the en-US/JSound.ent file |">
]>

<programlisting language="Java">package org.jboss.book.jca.ex1;

import javax.naming.InitialContext;

public class ExClient
{
   public static void main(String args[])
       throws Exception
   {
      InitialContext iniCtx = new InitialContext();
      Object         ref    = iniCtx.lookup("EchoBean");
      EchoHome       home   = (EchoHome) ref;
      Echo           echo   = home.create();

      System.out.println("Created Echo");

      System.out.println("Echo.echo('Hello') = " + echo.echo("Hello"));
   }
}</programlisting>


text:
Using Environment module
########################

Assuming that you have Client Factory instantiated (see :ref:`How to Instantiate Client Factory <client-factory>`) at **client** variable, in order to access methods relative to Environment module you need to call create_api_environment() at **client**.

Example:

.. code-block:: python

   env_module = client.create_api_environment()

For more information, please look GloboNetworkAPI documentation.

GET
***

The List of fields available at Environment module is:

    * id
    * name
    * grupo_l3
    * ambiente_logico
    * divisao_dc
    * filter
    * acl_path
    * ipv4_template
    * ipv6_template
    * link
    * min_num_vlan_1
    * max_num_vlan_1
    * min_num_vlan_2
    * max_num_vlan_2
    * vrf
    * default_vrf
    * father_environment
    * children
    * configs
    * routers
    * equipments
    * sdn_controllers

Obtain List of Environments through id's
========================================

Here you need to call get() method at env_module.

You can pass up to 5 parameters:
    * **ids**: List containing identifiers of environments.
    * **include**: Array containing fields to include on response.
    * **exclude**: Array containing fields to exclude on response.
    * **fields**: Array containing fields to override default fields.
    * **kind**: string where you can choose between "basic" or "details".

The response will be a dict with a list of Environments.

Examples:

.. code-block:: python

    envs = env_module.get(ids=[1, 2, 3])

.. code-block:: python

    envs = env_module.get(ids=[1, 2, 3],
                          include=['name', 'divisao_dc'],
                          exclude=['id'],
                          kind='details')

.. code-block:: python

    envs = env_module.get(ids=[1, 2, 3],
                          fields=['id', 'name', 'grupo_l3'])

Obtain List of Environments through extended search
===================================================

Here you need to call search() method at env_module.

You can pass up to 5 parameters:
    * **search**: Dict containing QuerySets to find environments.
    * **include**: Array containing fields to include on response.
    * **exclude**: Array containing fields to exclude on response.
    * **fields**: Array containing fields to override default fields.
    * **kind**: string where you can choose between "basic" or "details".

The response will be a dict with a list of Environments.

Example:

.. code-block:: python

    search = {
        'extends_search': [{
            'divisao_dc': 1,
            'ambiente_logico__nome': 'AmbLog'
        }],
        'start_record': 0,
        'custom_search': '',
        'end_record': 25,
        'asorting_cols': [],
        'searchable_columns': []}
    fields = ['id', 'name']

    envs = env_module.search(search=search, fields=fields)

POST
****

The List of fields available for create an Environment is:

    * grupo_l3 - **Mandatory**
    * ambiente_logico - **Mandatory**
    * divisao_dc - **Mandatory**
    * filter
    * min_num_vlan_1
    * max_num_vlan_1
    * min_num_vlan_2
    * max_num_vlan_2
    * ipv4_template
    * ipv6_template
    * link
    * acl_path
    * vrf
    * father_environment
    * default_vrf - **Mandatory**
    * configs
        * subnet
        * new_prefix
        * type
        * network_type

Create List of Environments
===========================

Here you need to call create() method at env_module.

You need to pass 1 parameter:
    * **environments**: List containing environments that you want to create.

Example:

.. code-block:: python

    envs_to_create = [
        {
            "grupo_l3": 1,
            "ambiente_logico": 2,
            "divisao_dc": 3,
            "filter": 1,
            "min_num_vlan_1": 1,
            "max_num_vlan_1": 500,
            "min_num_vlan_2": 1,
            "max_num_vlan_2": 500,
            "ipv4_template": "templatev4",
            "ipv6_template": "templatev6",
            "link": "http://environment",
            "acl_path": "path_to_acl",
            "vrf": "Test-Vrf",
            "father_environment": 1,
            "default_vrf": 1
        },
        {
            "grupo_l3": 1,
            "ambiente_logico": 2,
            "divisao_dc": 4,
            "default_vrf": 1,
            "configs": [
                {
                    'subnet': 'febe:bebe:bebe:8200:0:0:0:0/57',
                    'new_prefix': '64',
                    'type': 'v6',
                    'network_type': 8
                },
                {
                    'subnet': '10.10.0.0/16',
                    'new_prefix': '24',
                    'type': 'v4',
                    'network_type': 8
                }
            ]
        }
    ]

    env_module.create(environments=envs_to_create)

PUT
***

The List of fields available for update an Environment is:

    * id - **Mandatory**
    * grupo_l3 - **Mandatory**
    * ambiente_logico - **Mandatory**
    * divisao_dc - **Mandatory**
    * filter
    * min_num_vlan_1
    * max_num_vlan_1
    * min_num_vlan_2
    * max_num_vlan_2
    * ipv4_template
    * ipv6_template
    * link
    * acl_path
    * vrf
    * father_environment
    * default_vrf - **Mandatory**
    * configs
        * id
        * grupo_l3
        * ambiente_logico
        * divisao_dc
        * default_vrf

Update List of Environments
===========================

Here you need to call update() method at env_module.

You need to pass 1 parameter:
    * **environments**: List containing environments that you want to update.

Example:

.. code-block:: python

    envs_to_update = [
        {
            "id": 1,
            "grupo_l3": 1,
            "ambiente_logico": 2,
            "default_vrf": 1,
            "divisao_dc": 3
        },
        {
            "id": 2,
            "grupo_l3": 1,
            "ambiente_logico": 2,
            "divisao_dc": 4,
            "default_vrf": 1,
            "configs": [
                {
                    'id': 1,
                    'subnet': 'febe:bebe:bebe:8200:0:0:0:0/57',
                    'new_prefix': '64',
                    'type': 'v6',
                    'network_type': 8
                },
                {
                    'subnet': '10.10.0.0/16',
                    'new_prefix': '24',
                    'type': 'v4',
                    'network_type': 8
                }
            ]
        }
    ]

    env_module.update(environments=envs_to_update)

DELETE
******

Delete List of Environments
===========================

Here you need to call delete() method at env_module.

You need to pass 1 parameter:
    * **ids**: List containing identifiers of environments that you want to delete.

Example:

.. code-block:: python

    env_module.delete(ids=[1, 2, 3])


text:
import math
from PyQt4.QtCore import *
from PyQt4.QtGui import *
try:
    import okapy.videoio
except ImportError:
    pass

videos = []
scenes = []

class GraphicsView(QGraphicsView):
    # Signals
    scaleChanged = pyqtSignal(float)
    focusIn = pyqtSignal()

    def __init__(self, parent=None):
        QGraphicsView.__init__(self, parent)
        self.setDragMode(QGraphicsView.RubberBandDrag)
        #self.setDragMode(QGraphicsView.ScrollHandDrag)
        self.setMouseTracking(True)
        self.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform | QPainter.TextAntialiasing)
        self.setStyleSheet("QFrame { border: 3px solid black }")
        self._active = False
        self._pan = False
        self._panStartX = -1
        self._panStartY = -1

    def fitInView(self):
        if self.scene() is None:
            return
        si = self.scene().sceneItem()
        if si is None:
            return

        old_scale = self.getScale()
        QGraphicsView.fitInView(self, si, Qt.KeepAspectRatio)
        new_scale = self.getScale()

        if new_scale != old_scale:
            self.scaleChanged.emit(new_scale)

    def setScene(self, scene):
        QGraphicsView.setScene(self, scene)
        #self.setScaleAbsolute(1)

    def getScale(self):
        if self.isTransformed():
            return self.transform().m11()
        else:
            return 1

    def isActive(self):
        return self._active

    def activate(self):
        if not self._active:
            self._active = True
            self.setFocus(Qt.OtherFocusReason)
            self.setStyleSheet("QFrame { border: 3px solid red }")
            self.update()

    def deactivate(self):
        if self._active:
            self._active = False
            self.clearFocus()
            self.setStyleSheet("QFrame { border: 3px solid black }")
            self.update()

    def getMinScale(self):
        #min_scale_w = float(self.width()  - 2*self.frameWidth()) / (self.scene().width()+1)
        #min_scale_h = float(self.height() - 2*self.frameWidth()) / (self.scene().height()+1)
        #min_scale = min(min_scale_w, min_scale_h)
        return 0.1

    def getMaxScale(self):
        #max_scale_w = self.scene().height() / 5.0
        #max_scale_h = self.scene().width()  / 5.0
        #max_scale = min(max_scale_w, max_scale_h)
        #return max_scale
        return 20.0

    def setScaleAbsolute(self, scale):
        scale = max(scale, self.getMinScale())
        scale = min(scale, self.getMaxScale())
        self.setTransform(QTransform.fromScale(scale, scale))
        self.scaleChanged.emit(self.getScale())

    def setScaleRelative(self, factor):
        self.setScaleAbsolute(self.getScale() * factor)

    def wheelEvent(self, event):
        factor = 1.41 ** (event.delta() / 240.0)
        self.setScaleRelative(factor)

    def focusInEvent(self, event):
        self.focusIn.emit()

    def resizeEvent(self, event):
        #if self.getScale() < self.getMinScale():
        #    self.setScaleAbsolute(0)
        #if self.getScale() > self.getMaxScale():
        #    self.setScaleAbsolute(self.getMaxScale())
        QGraphicsView.resizeEvent(self, event)

    def mousePressEvent(self, event):
        if event.button() & Qt.MidButton != 0:
            self._pan = True
            self._panStartX = event.x()
            self._panStartY = event.y()
            self.setCursor(Qt.ClosedHandCursor)
            event.accept()
        else:
            return QGraphicsView.mousePressEvent(self, event)

    def mouseReleaseEvent(self, event):
        if self._pan:
            self._pan = False
            self.setCursor(Qt.ArrowCursor)
            event.accept()
        else:
            return QGraphicsView.mouseReleaseEvent(self, event)

    def mouseMoveEvent(self, event):
        if self._pan:
            self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - (event.x() - self._panStartX))
            self.verticalScrollBar().setValue(self.verticalScrollBar().value() - (event.y() - self._panStartY))
            self._panStartX = event.x()
            self._panStartY = event.y()
            event.accept()
        else:
            return QGraphicsView.mouseMoveEvent(self, event)

class FrameViewer(QWidget):
    # Signals
    activeSceneViewChanged = pyqtSignal(GraphicsView)

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

    def getActiveSceneView(self):
        pass

    def activateNextSceneView(self):
        pass

    def activatePreviousSceneView(self):
        pass

    def setActiveScaleAbsolute(self, scale):
        self.getActiveSceneView().setScaleAbsolute(scale)

    def setActiveScaleRelative(self, scale):
        self.getActiveSceneView().setScaleRelative(scale)

class SingleFrameViewer(FrameViewer):
    def __init__(self, annotation_scene, parent=None):
        FrameViewer.__init__(self, parent)
        self.scene = annotation_scene
        self.scene_view = GraphicsView()
        self.scene_view.setScene(self.scene)
        self.scene_view.activate()
        self.layout = QHBoxLayout(self)
        self.layout.addWidget(self.scene_view)
        self.setLayout(self.layout)

    def getActiveSceneView(self):
        return self.scene_view

class MultiFrameEqualViewer(FrameViewer):
    def __init__(self, annotation_scenes, parent=None):
        assert(len(annotation_scenes) > 0)
        FrameViewer.__init__(self, parent)
        self.active_scene_view = -1
        self.scenes = annotation_scenes
        self.scene_views = []
        for scene in self.scenes:
            scene_view = GraphicsView()
            scene_view.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
            scene_view.setScene(scene)
            scene_view.focusIn.connect(self.activateFocusedSceneView)
            self.scene_views.append(scene_view)
        n_rows = math.ceil(math.sqrt(len(self.scene_views)))
        n_cols = math.ceil(len(self.scenes) / n_rows)
        self.layout = QGridLayout(self)
        for i, scene_view in enumerate(self.scene_views):
            self.layout.addWidget(scene_view, i/n_cols, i % n_cols)
        self.setLayout(self.layout)
        self.activateSceneView(0)

    def activateSceneView(self, index):
        if index != self.active_scene_view:
            for scene_view in self.scene_views:
                scene_view.deactivate()
            self.active_scene_view = index
            self.scene_views[index].activate()
            self.activeSceneViewChanged.emit(self.getActiveSceneView())

    def activateFocusedSceneView(self):
        sender = self.sender()
        for index, scene_view in enumerate(self.scene_views):
            if scene_view == sender:
                self.activateSceneView(index)

    def getActiveSceneView(self):
        return self.scene_views[self.active_scene_view]


text:
Alloy.Globals.indexController = $;

var Http = require('http');

$.getView().addEventListener("android:back", function() {
	$.trigger("back");
});

if (OS_IOS) {
	$.ptr.init($.newsTable);
}

function pullToRefresh(e) {

	refreshNews(function() {
		e.hide();
	});

}

function viewArticle(e) {
	$.articleView.url = e.row.url;

	$.scrollableView.scrollToView(1);

	if (OS_ANDROID) {
		$.on("back", function() {
			$.scrollableView.scrollToView(0);
		});
	}

	if (OS_IOS) {
		$.back.show();
	}
}

if (OS_IOS) {
	function goBack() {
		if (OS_IOS) {
			$.back.hide();
		}
		$.scrollableView.scrollToView(0);
	}

}

function refreshNews(callback) {
	var Results = new Http("http://www.tidev.io/api/get_recent_posts/");

	var rows = [];

	Results.get(function(e) {

		//alert(e.pages);
		e.posts.forEach(function(post) {

			var row = Alloy.createController("newsRow");

			row.headline.text = post.title;

			post.attachments.forEach(function(a) {

				row.photo.image = a.url;
			});

			row.getView().url = post.url;

			rows.push(row.getView());

		});

		$.newsTable.setData(rows);

		if (callback) {
			callback();
		}

	});

}

refreshNews();

$.index.open();


text:
qrcodesvg-node
===========

[![Build Status](https://travis-ci.org/pinchtools/qrcodesvg-node.svg)](https://travis-ci.org/pinchtools/qrcodesvg-node)
[![npm version](https://badge.fury.io/js/qrcodesvg.svg)](https://badge.fury.io/js/qrcodesvg)

Create custom QR Code with SVG

## Install

    npm install qrcodesvg --save

## Usage

```js
var Qrcodesvg = require('qrcodesvg');

//create a simple Qrcode of 400px
var qrcode = new Qrcodesvg("Hello!", 400);
var data = qrcode.generate();
```
or

```js
var Qrcodesvg = require('qrcodesvg');

//Generate a Qrcode with a correction level of 2
//and affect randomly one of the colors defined to patterns
var qrcode = new Qrcodesvg("Hello!", 400, {"ecclevel" : 2});

var data = qrcode.generate({
                                "method":"classic",
                                "fill-colors":["#1C46ED","#021872","#0125C4"]
                            },
                            {
                                "stroke-width":1
                            });
```

## Examples

### Server-side

See Qrcodesvg in action with few examples

```
gulp server
```

### Bundling for browsers
```
gulp client
```

## API

### new Qrcodesvg(input, size, [, options])
- `input`
- `size`
  - size of the rendered QR Code
- `options`
  - `ecclevel`
    - Default is 1
    - accepted correction level from 1 to 4

### qrcodesvg.generate([settings, attributes])
  Returns the svg content as a string

- `settings`
  - `method`
    - drawing method, default is "classic"
    - available methods : "classic", "bevel", "round"
  - `scope`
    - scope where to applying drawing method
    - default is "pattern"
    - available options : "pattern", "square"
  - `fill-color`
    -  array of hexadecimal colors
  - `fill-colors-scope`
    - default is "pattern"
    - available options : "pattern", "square"
  - `radius`
    - for "round" and "bevel" methods only
    - Default is 5
- `attributes`
  - svg attributes added to square elements

### qrcodesvg.background(settings [, attributes])
Returns "this"

- `settings`
  - margin
    - Default is 0
  - padding
    - Default is 0
- `attributes`
  - svg attributes applied to the background element

## Test

```
mocha
```

## LICENSE

The MIT License (MIT)

Copyright (c) 2015 Vincent Pellé

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
import bot_header

def main(c):
    if bot_header.AUTO_EXEC_THREAD_INSTANCE is not None:
        print("Alive: %s rules loaded, interval: %s" % (len(bot_header.AUTO_EXEC_THREAD_INSTANCE.aexec_rules), bot_header.AUTO_EXEC_THREAD_INSTANCE.interval))
    else:
        print("Dead. Run it using 'aexec start'")


text:
require 'yaml'
require 'active_support/all'

# Configuration
nodes_path = File.join(File.dirname(__FILE__), 'nodes.yml')
fail "\nCould not load NODES configuration: #{nodes_path} not found" unless File.exist?(nodes_path)
NODES = YAML.load(File.open(nodes_path))

puts 'Enabled nodes:'
NODES.keys.each do |node_key|
  puts "#{node_key.upcase}: #{NODES[node_key]}" if NODES[node_key]['enabled']
end

NODES.keys.each do |node_key|
  if NODES[node_key]['enabled']
    cmd = "NODE=#{node_key} STAGE=#{ENV['STAGE']} bundle exec sprinkle -s install.rb -v"
    puts "\n#{cmd}\n"
    system(cmd)
  end
end


text:
require 'spec_helper'

describe BoxView::Webhook, '#create' do
  before do
    allow(BoxView).to receive(:post).and_return(mock_response)
  end

  context 'when response is 200' do
    let(:mock_response) { double('200 Response', { :code => 200, :body => '{"url": "http://example.com"}' }) }

    it 'returns the response' do
      response = BoxView::Webhook.create(:url => 'http://example.com')
      expect(response.code).to eq(200)
    end
  end

  context 'when response is not 200' do
    let(:mock_response) { double('401 Response', { :code => 401 }) }

    it 'raises an error' do
      expect {
        BoxView::Webhook.create(:url => 'http://example.com')
      }.to raise_error(BoxView::Errors::WebhookCreationFailed)
    end
  end
end

describe BoxView::Webhook, '#delete' do
  before do
    allow(BoxView).to receive(:delete).and_return(mock_response)
  end

  context 'when response is 200' do
    let(:mock_response) { double('200 Response', { :code => 200 }) }

    it 'returns the response' do
      response = BoxView::Webhook.delete
      expect(response.code).to eq(200)
    end
  end

  context 'when response is not 200' do
    let(:mock_response) { double('401 Response', { :code => 401 }) }

    it 'raises an error' do
      expect { BoxView::Webhook.delete }.to raise_error(BoxView::Errors::WebhookDeletionFailed)
    end
  end
end

describe BoxView::Webhook, '#get' do
  before do
    allow(BoxView).to receive(:get).and_return(mock_response)
  end

  context 'when response is 200' do
    let(:mock_response) { double('200 Response', { :code => 200 }) }

    it 'returns the response' do
      response = BoxView::Webhook.get
      expect(response.code).to eq(200)
    end
  end

  context 'when response is not 200' do
    let(:mock_response) { double('401 Response', { :code => 401 }) }

    it 'raises an error' do
      expect { BoxView::Webhook.get }.to raise_error(BoxView::Errors::WebhookFetchFailed)
    end
  end
end


text:
var express = require('express');
var cons = require('consolidate');

app = express();
/* primeiro teste */
// app.get('/',function(req,res){ res.send('Hello world!')});

app.listen(3000);
console.log('app rodando na localhost:3000');

app.engine('html', cons.swig);
app.set('view engine','html');
app.set('views',__dirname+'/views');

/* app.get('/',function(req,res){res.send();}); */
app.get('/',function(req,res){
  res.render('index')
});

app.use(express.static(__dirname + '/resources'));

app.use('/js',
  express.static(__dirname+'/resources/javascript'));


text:
package api

import (
	"encoding/xml"
	"gopkg.in/mgo.v2/bson"
)

type WithKey interface {
	FormKey() bson.M
}

type WithItems interface {
	Items() []WithKey
}

type Model interface {
	GetError() APIError
}

type ModelStore struct {
	Kills []WithKey
}

type APIError struct {
	Code string `xml:"code,attr"`
	Msg  string `xml:",chardata"`
}

type EVEAPI struct {
	XMLName xml.Name `xml:"eveapi"`
	Time    string   `xml:"currentTime"`
	Error   APIError `xml:"error"`
}

func (c EVEAPI) GetError() APIError {
	return c.Error
}

type Character struct {
	Name            string `xml:"name,attr"`
	CharacterID     string `xml:"characterID,attr"`
	CorporationName string `xml:"corporationName,attr"`
}

func (c Character) FormKey() bson.M {
	return bson.M{"characterid": c.CharacterID}
}

type Characters struct {
	EVEAPI
	Character []Character `xml:"result>rowset>row"`
}

type Skill struct {
	TypeID int `xml:"typeID,attr"`
}

type SkillQueue struct {
	EVEAPI
	CharacterID string
	Skill       []Skill `xml:"result>rowset>row"`
}

func (c SkillQueue) FormKey() bson.M {
	return bson.M{"characterid": c.CharacterID}
}

type GroupSkill struct {
	Name string `xml:"typeName,attr"`
}

type Group struct {
	Name  string       `xml:"groupName,attr"`
	Skill []GroupSkill `xml:"rowset>row"`
}

type Tree struct {
	EVEAPI
	Group []Group `xml:"result>rowset>row"`
}

type Kills struct {
	EVEAPI
	ModelStore
	Kills []Kill `xml:"result>rowset>row"`
}

type Kill struct {
	KillID string `xml:"killID,attr"`
	Victim Victim `xml:"victim"`
}

func (k Kills) Items() []WithKey {
	var items []WithKey = []WithKey{}
	for _, kill := range k.Kills {
		items = append(items, WithKey(kill))
	}
	return items
}

func (c Kill) FormKey() bson.M {
	return bson.M{"killid": c.KillID}
}

type Victim struct {
	Name            string `xml:"characterName,attr"`
	CharacterID     string `xml:"characterID,attr"`
	CorporationID   string `xml:"corporationID,attr"`
	CorporationName string `xml:"corporationName,attr"`
}


text:
#ifndef THEMIS_MAPRED_STREAM_INFO_H
#define THEMIS_MAPRED_STREAM_INFO_H

#include <set>

#include "core/constants.h"

/**
   StreamInfo contains information about a stream of data being converted by a
   ByteStreamConverter, including that stream's filename, and the set of job
   IDs that should process data from the stream. This information is used by
   byte stream converters to attach the appropriate metadata to the buffers
   that they emit.
 */
class StreamInfo {
public:
  /// Constructor
  /**
     \param streamID the stream ID for this stream
     \param filename the filename from which this stream's data originates
   */
  explicit StreamInfo(uint64_t streamID, const std::string& filename);

  /// Constructor
  /**
     \param streamID the stream ID for this stream
     \param filename the filename from which this stream's data originates
     \param size the size of the stream if specified by the user
   */
  explicit StreamInfo(
    uint64_t streamID, const std::string& filename, uint64_t size);

  /// Destructor
  virtual ~StreamInfo() {}

  /// Associate a job ID with this stream
  /**
     \param jobID the job ID to associate with this stream
   */
  void addJobID(uint64_t jobID);

  /// \return the stream ID for this stream
  uint64_t getStreamID() const;

  /// \return the set of job IDs that should consume this stream's data
  const std::set<uint64_t>& getJobIDs() const;

  /// \return the filename from which this stream's data originates
  const std::string& getFilename() const;

  /// \return the size of the stream if set, or uint64_t max otherwise
  uint64_t getSize() const;

private:
  const uint64_t streamID;
  std::set<uint64_t> jobIDs;
  const std::string filename;
  const uint64_t size;
};

#endif // THEMIS_MAPRED_STREAM_INFO_H


text:
"""Script to parse MAF file
"""

from isb_cgc_user_data.bigquery_etl.extract.utils import convert_file_to_dataframe
from isb_cgc_user_data.bigquery_etl.transform.tools import cleanup_dataframe

def convert_blob_to_dataframe(gcs, project_id, bucket_name, filename, skiprows=0, logger=None):
    """
    Function to connect to google cloud storage, download the file,
    and convert to a dataframe
    """

    filebuffer = gcs.download_blob_to_file(filename)

    # convert blob into dataframe
    data_df = convert_file_to_dataframe(filebuffer, skiprows=skiprows, logger=logger)

    # clean-up dataframe
    data_df = cleanup_dataframe(data_df, logger=logger)

    return data_df


text:
package com.globalsight.ling.tm3.core;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.globalsight.ling.tm3.core.TM3Data;

class Trigrammer {

    // Start/end of segment boundary
    private static final Long BOUNDARY = -1l;

    static class Trigram {
        long[] fingerprints;

        public Trigram(Long fp0, Long fp1, Long fp2) {
            fingerprints = new long[3];
            fingerprints[0] = fp0.longValue();
            fingerprints[1] = fp1.longValue();
            fingerprints[2] = fp2.longValue();
        }

        public String toString() {
            return Arrays.toString(fingerprints);
        }

        public Long getValue() {
            return fingerprints[0] + 31 *
                        (fingerprints[1] + 31 * fingerprints[2]);
        }

    }

    Trigrammer() {
    }

    // Like everything else, this is a slapdash affair.  There's lots of
    // normalization I would normally use.
    List<Trigram> getTrigrams(TM3Data data) {
        List<Long> fingerprints = new ArrayList<Long>();
        fingerprints.add(BOUNDARY);
        for (Long tok : data.tokenize()) {
            fingerprints.add(tok);
        }
        fingerprints.add(BOUNDARY);
        List<Trigram> trigrams = new ArrayList<Trigram>();
        for (int i = 0; i + 2 < fingerprints.size(); i++) {
            trigrams.add(new Trigram(fingerprints.get(i),
                                     fingerprints.get(i+1),
                                     fingerprints.get(i+2)));
        }
        return trigrams;
    }
}


text:
<workflow-app xmlns="uri:oozie:workflow:0.4" name="transformers_documentssimilarity">

	<parameters>
		<property>
			<name>input_metadata</name>
			<description>merged input datastore</description>
		</property>
		<property>
			<name>output_document_metadata</name>
			<description>output directory</description>
		</property>
	</parameters>

    <global>
        <job-tracker>${jobTracker}</job-tracker>
        <name-node>${nameNode}</name-node>
        <configuration>
            <property>
                <name>mapreduce.job.queuename</name>
                <value>${queueName}</value>
            </property>
            <property>
                <name>oozie.launcher.mapred.job.queue.name</name>
                <value>${oozieLauncherQueueName}</value>
            </property>
        </configuration>
    </global>

    <start to="generate-schema"/>

    <action name="generate-schema">
	    <java>
	        <main-class>eu.dnetlib.iis.common.javamapreduce.hack.AvroSchemaGenerator</main-class>
	        <arg>eu.dnetlib.iis.transformers.metadatamerger.schemas.ExtractedDocumentMetadataMergedWithOriginal</arg>
	        <arg>eu.dnetlib.iis.documentssimilarity.schemas.DocumentMetadata</arg>
	        <capture-output />
	    </java>
	    <ok to="transformer" />
	    <error to="fail" />
	</action>

    <action name="transformer">
        <pig>
            <!-- The data generated by this node is deleted in this section -->
            <prepare>
                <delete path="${nameNode}${output_document_metadata}" />
            </prepare>
            <!-- Path to PIG script the workflow executes. -->
            <script>lib/scripts/transformer.pig</script>

            <param>input_metadata=${input_metadata}</param>
            <param>schema_input_metadata=${wf:actionData('generate-schema')['eu.dnetlib.iis.transformers.metadatamerger.schemas.ExtractedDocumentMetadataMergedWithOriginal']}</param>

            <param>output_document_metadata=${output_document_metadata}</param>
            <param>schema_output_document_metadata=${wf:actionData('generate-schema')['eu.dnetlib.iis.documentssimilarity.schemas.DocumentMetadata']}</param>
        </pig>
        <ok to="end"/>
        <error to="fail"/>
    </action>
    <kill name="fail">
        <message>Unfortunately, the workflow failed -- error message:
            [${wf:errorMessage(wf:lastErrorNode())}]</message>
    </kill>
    <end name="end"/>
</workflow-app>


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2018] EMBL-European Bioinformatics Institute

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.

=cut

package EnsEMBL::Web::Controller::Share;

use strict;
use warnings;

use previous qw(share_create);

sub share_create {
  ## @plugin
  ## Change ticket visibility to 'public' before sharing Tools/Result url
  my $self  = shift;
  my $hub   = $self->hub;
  my $ref   = $hub->referer;

  if ($hub->tools_available && ($ref->{'ENSEMBL_TYPE'} || '') eq 'Tools' && $ref->{'ENSEMBL_ACTION'} && ($ref->{'ENSEMBL_FUNCTION'} || '') eq 'Results') {

    if (my $object = $self->new_object($ref->{'ENSEMBL_ACTION'}, {}, { _hub => $hub })) {

      $hub->param('tl', @{$ref->{'params'}{'tl'} || []}); # get_requested_ticket only looks at current url param

      # share link will only work if visibility is public
      $object->change_ticket_visibility('public') if $object->get_requested_ticket;
    }
  }

  return $self->PREV::share_create(@_);
}

1;


text:
using UnityEngine;
using System.Collections;

public class MechRandomizer : MonoBehaviour {

	public float rotateSpeed = 1f;
	private ProceduralMaterial mat;

	protected void Start()
	{
		mat = GetComponent<Renderer>().material as ProceduralMaterial;

		StartCoroutine(RandomizeRoutine());
	}

	private IEnumerator RandomizeRoutine()
	{
		for(;;)
		{
			Randomize();
			yield return new WaitForSeconds(Random.Range(3f, 5f));
		}
	}

	public void Randomize()
	{
		mat.SetProceduralFloat("Dirt", Random.Range(0f, 1f));
		mat.SetProceduralFloat("Hue", Random.Range(0f, 1f));
		mat.SetProceduralFloat("Saturation", Random.Range(0f, 1f));

		mat.SetProceduralColor("LensColor", new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f)));

		mat.RebuildTextures();
	}

	void Update ()
	{
		// Temp rotate model
		transform.Rotate(Vector3.forward, Time.deltaTime * rotateSpeed);
	}
}


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>UISref | @uirouter/angular</title>
	<meta name="description" content="Documentation for @uirouter/angular">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					@uirouter/angular

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals

					Menu

					@uirouter/angular

					"directives/uiSref"

					UISref

Class UISref

A directive when clicked, initiates a Transition to a TargetState.

Purpose

This directive is applied to anchor tags (<a>) or any other clickable element.  It is a state reference (or sref --
						similar to an href).  When clicked, the directive will transition to that state by calling StateService.go,
					and optionally supply state parameter values and transition options.

When this directive is on an anchor tag, it will also add an href attribute to the anchor.

Selector

[uiSref]: The directive is created as an attribute on an element, e.g., <a uiSref></a>

Inputs

uiSref: the target state's name, e.g., uiSref="foostate".  If a component template uses a relative uiSref,
							e.g., uiSref=".child", the reference is relative to that component's state.

uiParams: any target state parameter values, as an object, e.g., [uiParams]="{ fooId: bar.fooId }"

uiOptions: TransitionOptions, e.g., [uiOptions]="{ inherit: false }"

example

<!-- Targets bar state' -->
<a uiSref="bar">Bar</a>

<!-- Assume this component's state is "foo".
     Relatively targets "foo.child" -->
<a uiSref=".child">Foo Child</a>

<!-- Targets "bar" state and supplies parameter value -->
<a uiSref="bar" [uiParams]="{ barId: foo.barId }">Bar {{foo.barId}}</a>

<!-- Targets "bar" state and parameter, doesn't inherit existing parameters-->
<a uiSref="bar" [uiParams]="{ barId: foo.barId }" [uiOptions]="{ inherit: false }">Bar {{foo.barId}}</a>

Hierarchy

						UISref

Implements

OnChanges

Index

Constructors

constructor

Properties

options

params

state

target<wbr>State$

Methods

get<wbr>Options

go

ng<wbr>OnChanges

ng<wbr>OnDestroy

ng<wbr>OnInit

Constructors

constructor

new UISref(_router: UIRouter, _anchorUISref: AnchorUISref, parent: ParentUIViewInject): UISref

Defined in src/directives/uiSref.ts:120

Parameters

_router: UIRouter

_anchorUISref: AnchorUISref

parent: ParentUIViewInject

Returns UISref

Properties

options

options: TransitionOptions

Defined in src/directives/uiSref.ts:108

@Input('uiOptions') The transition options

<a uiSref="books" [uiOptions]="{ reload: true }">Book {{ book.name }}</a>

params

params: any

Defined in src/directives/uiSref.ts:99

@Input('uiParams') The parameter values to use (as key/values)

<a uiSref="book" [uiParams]="{ bookId: book.id }">Book {{ book.name }}</a>

state

state: string

Defined in src/directives/uiSref.ts:90

@Input('uiSref') The name of the state to link to

<a uiSref="hoome">Home</a>

target<wbr>State$

target<wbr>State$: ReplaySubject<TargetState> = new ReplaySubject<TargetState>(1)

Defined in src/directives/uiSref.ts:114

An observable (ReplaySubject) of the state this UISref is targeting.
							When the UISref is clicked, it will transition to this TargetState.

Methods

get<wbr>Options

get<wbr>Options(): any

Defined in src/directives/uiSref.ts:182

Returns any

go

go(button: number, ctrlKey: boolean, metaKey: boolean): boolean

Defined in src/directives/uiSref.ts:193

When triggered by a (click) event, this function transitions to the UISref's target state

Parameters

button: number

ctrlKey: boolean

metaKey: boolean

Returns boolean

ng<wbr>OnChanges

ng<wbr>OnChanges(changes: SimpleChanges): void

Defined in src/directives/uiSref.ts:155

Parameters

changes: SimpleChanges

Returns void

ng<wbr>OnDestroy

ng<wbr>OnDestroy(): void

Defined in src/directives/uiSref.ts:159

Returns void

ng<wbr>OnInit

ng<wbr>OnInit(): void

Defined in src/directives/uiSref.ts:150

Returns void

						UIRouter

						Services

						State<wbr>Service

						State<wbr>Registry

						Transition<wbr>Service

						Url<wbr>Service

						Url<wbr>Config

						Url<wbr>Rules

						Interfaces

						Ng2<wbr>State<wbr>Declaration

						Ui<wbr>OnParams<wbr>Changed

						Ui<wbr>OnExit

						Components

						UIView

						UISref

						UISref<wbr>Active

						Other

						Transition

						Trace

						UISref

								constructor

								options

								params

								state

								target<wbr>State$

								get<wbr>Options

								go

								ng<wbr>OnChanges

								ng<wbr>OnDestroy

								ng<wbr>OnInit

Legend

Generated using TypeDoc


text:
<?php

namespace Respect\Validation\Exceptions;

class NoneOfException extends AbstractNestedException
{

    public static $defaultTemplates = array(
        self::MODE_DEFAULT => array(
            self::STANDARD => 'None of these rules must pass for {{name}}',
        ),
        self::MODE_NEGATIVE => array(
            self::STANDARD => 'All of these rules must pass for {{name}}',
        )
    );

}


text:
@interface TestEventStore : XCTestCase

@end

@implementation TestEventStore

- (void)setUp {
    [super setUp];
}

- (void)tearDown {
    [super tearDown];
}

- (void)testInit {
    SPEventStore * eventStore = [[SPEventStore alloc] init];
    XCTAssertNotNil(eventStore);
}

- (void)testInsertPayload {
    SPEventStore * eventStore = [[SPEventStore alloc] init];
    [eventStore removeAllEvents];

    // Build an event
    SPPayload * payload = [[SPPayload alloc] init];
    [payload addValueToPayload:@"pv"                 forKey:@"e"];
    [payload addValueToPayload:@"www.foobar.com"     forKey:@"url"];
    [payload addValueToPayload:@"Welcome to foobar!" forKey:@"page"];
    [payload addValueToPayload:@"MEEEE"              forKey:@"refr"];

    // Insert an event
    [eventStore insertEvent:payload];

    XCTAssertEqual([eventStore count], 1);
    XCTAssertEqualObjects([eventStore getEventWithId:1], [payload getAsDictionary]);
    XCTAssertEqual([eventStore getLastInsertedRowId], 1);
    [eventStore removeEventWithId:1];

    XCTAssertEqual([eventStore count], 0);
}

- (void)testInsertManyPayloads {
    SPEventStore * eventStore = [[SPEventStore alloc] init];
    [eventStore removeAllEvents];

    // Build an event
    SPPayload * payload = [[SPPayload alloc] init];
    [payload addValueToPayload:@"pv"                 forKey:@"e"];
    [payload addValueToPayload:@"www.foobar.com"     forKey:@"url"];
    [payload addValueToPayload:@"Welcome to foobar!" forKey:@"page"];
    [payload addValueToPayload:@"MEEEE"              forKey:@"refr"];

    for (int i = 0; i < 250; i++) {
        [eventStore insertEvent:payload];
    }

    XCTAssertEqual([eventStore count], 250);
    XCTAssertEqual([eventStore getAllEventsLimited:600].count, 250);
    XCTAssertEqual([eventStore getAllEventsLimited:150].count, 150);
    XCTAssertEqual([eventStore getAllEvents].count, 250);
}

@end


text:
import { View } from "backbone.marionette";
import template from "./LaunchesWidgetView.hbs";

class LaunchesWidgetView extends View {
  template = template;
}

export default LaunchesWidgetView;


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--

 Copyright 2003 - 2015 The eFaps Team

 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.

-->
<ui-search xmlns="http://www.efaps.org/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">
    <uuid>66055c7c-917d-4447-a5e5-f51987d43051</uuid>
    <file-application>eFapsApp-Sales</file-application>
    <definition>
        <version-expression>(version==latest)</version-expression>
        <name>Sales_IncomingCreditNoteTree_Doc_Menu_Action_AddIncomingInvoice_Search</name>
        <default>
            <command>Sales_IncomingInvoiceSearch</command>
        </default>
        <childs>
            <child>Sales_IncomingInvoiceSearch</child>
        </childs>
    </definition>
</ui-search>


text:
JBAPPROOT=$HOME/.jbashing

JBENABLED_FOLDER=$JBAPPROOT/enabled
JBAVAILABLE_FOLDER=$JBAPPROOT/available
JBEXTRAS_FOLDER=$JBAPPROOT/extras

shopt -s nullglob
for f in $JBAPPROOT/enabled/*.sh
do
  source $f
done
shopt -u nullglob

#HELP
alias jbhelp='echo "INSTALL: git clone https://github.com/Sector7B/jbashing.git ~/.jbashing
CMDS:    jbenable, jbdisable, jbupdate, jbinstall, jbprime"'
#MANAGEMENT
alias jbprime='source $JBAPPROOT/primer.sh'
function jbenable { ln -s $JBAVAILABLE_FOLDER/$1.sh $JBENABLED_FOLDER/$1.sh && source $JBAPPROOT/primer.sh; }
function jbdisable { rm $JBENABLED_FOLDER/$1.sh && source $JBAPPROOT/primer.sh; }
function jbupdate { JBCD=`pwd` && cd $JBAPPROOT && git pull && cd $JBCD && source $JBAPPROOT/primer.sh; }
function jbinstall { ln -s $1 $JBENABLED_FOLDER/$2 && source $JBAPPROOT/primer.sh; }

export -f jbenable jbdisable jbupdate jbinstall

#alias jbupdate='cd $JBAPPROOT && git pull'


text:
namespace base {
template <typename T>
struct DefaultSingletonTraits;
}

namespace enterprise_connectors {

// Controls whether the Enterprise Connectors policies should be read by
// ConnectorsManager.
extern const base::Feature kEnterpriseConnectorsEnabled;

// For the moment, service provider configurations are static and only support
// google endpoints.  Therefore the configuration is placed here directly.
// Once the configuration becomes more dynamic this static string will be
// removed and replaced with a service to keep it up to date.
extern const char kServiceProviderConfig[];

// Accessor for the ServiceProviderConfig.
ServiceProviderConfig* GetServiceProviderConfig();

// A keyed service to access ConnectorsManager, which tracks Connector policies.
class ConnectorsService : public KeyedService {
 public:
  ConnectorsService(content::BrowserContext* context,
                    std::unique_ptr<ConnectorsManager> manager);
  ~ConnectorsService() override;

  // Accessors that check kEnterpriseConnectorsEnabled is enabled, and then call
  // the corresponding method in ConnectorsManager.
  absl::optional<ReportingSettings> GetReportingSettings(
      ReportingConnector connector);
  absl::optional<AnalysisSettings> GetAnalysisSettings(
      const GURL& url,
      AnalysisConnector connector);
  absl::optional<FileSystemSettings> GetFileSystemGlobalSettings(
      FileSystemConnector connector);
  absl::optional<FileSystemSettings> GetFileSystemSettings(
      const GURL& url,
      FileSystemConnector connector);

  bool IsConnectorEnabled(AnalysisConnector connector) const;
  bool IsConnectorEnabled(ReportingConnector connector) const;
  bool IsConnectorEnabled(FileSystemConnector connector) const;

  bool DelayUntilVerdict(AnalysisConnector connector);
  absl::optional<std::u16string> GetCustomMessage(AnalysisConnector connector,
                                                  const std::string& tag);
  absl::optional<GURL> GetLearnMoreUrl(AnalysisConnector connector,
                                       const std::string& tag);
  bool HasCustomInfoToDisplay(AnalysisConnector connector,
                              const std::string& tag);

  std::vector<std::string> GetAnalysisServiceProviderNames(
      AnalysisConnector connector);
  std::vector<std::string> GetReportingServiceProviderNames(
      ReportingConnector connector);

  // DM token accessor function for real-time URL checks. Returns a profile or
  // browser DM token depending on the policy scope, and absl::nullopt if there
  // is no token to use.
  absl::optional<std::string> GetDMTokenForRealTimeUrlCheck() const;

  // Returns the value to used by the enterprise real-time URL check Connector
  // if it is set and if the scope it's set at has a valid browser-profile
  // affiliation.
  safe_browsing::EnterpriseRealTimeUrlCheckMode GetAppliedRealTimeUrlCheck()
      const;

  // Returns the CBCM domain or profile domain that enables connector policies.
  // If both set Connector policies, the CBCM domain is returned as it has
  // precedence.
  std::string GetManagementDomain();

  // Testing functions.
  ConnectorsManager* ConnectorsManagerForTesting();

 private:
  struct DmToken {
    DmToken(const std::string& value, policy::PolicyScope scope);
    DmToken(DmToken&&);
    DmToken& operator=(DmToken&&);
    ~DmToken();

    // The value of the token to use.
    std::string value;

    // The scope of the token. This is determined by the scope of the Connector
    // policy used to get a DM token.
    policy::PolicyScope scope;
  };

  // Returns the DM token to use with the given |scope_pref|. That pref should
  // contain either POLICY_SCOPE_MACHINE or POLICY_SCOPE_USER.
  absl::optional<DmToken> GetDmToken(const char* scope_pref) const;
  absl::optional<DmToken> GetBrowserDmToken() const;
#if !BUILDFLAG(IS_CHROMEOS)
  absl::optional<DmToken> GetProfileDmToken() const;

  // Returns true if the browser isn't managed by CBCM, otherwise this checks if
  // the affiliations IDs from the profile and browser policy fetching responses
  // indicate that the same customer manages both.
  bool CanUseProfileDmToken() const;
#endif

  // Returns the policy::PolicyScope stored in the given |scope_pref|.
  policy::PolicyScope GetPolicyScope(const char* scope_pref) const;

  // Returns whether Connectors are enabled at all. This can be false if:
  // - The kEnterpriseConnectorsEnabled feature is disabled
  // - The profile is incognito
  bool ConnectorsEnabled() const;

  // Obtain a ClientMetadata instance corresponding to the current
  // OnSecurityEvent policy value.
  std::unique_ptr<ClientMetadata> BuildClientMetadata();

  raw_ptr<content::BrowserContext> context_;
  std::unique_ptr<ConnectorsManager> connectors_manager_;
};

class ConnectorsServiceFactory : public BrowserContextKeyedServiceFactory {
 public:
  static ConnectorsServiceFactory* GetInstance();
  static ConnectorsService* GetForBrowserContext(
      content::BrowserContext* context);

 private:
  ConnectorsServiceFactory();
  ~ConnectorsServiceFactory() override;
  friend struct base::DefaultSingletonTraits<ConnectorsServiceFactory>;

  // BrowserContextKeyedServiceFactory:
  KeyedService* BuildServiceInstanceFor(
      content::BrowserContext* context) const override;
  content::BrowserContext* GetBrowserContextToUse(
      content::BrowserContext* context) const override;
};

}  // namespace enterprise_connectors

#endif  // CHROME_BROWSER_ENTERPRISE_CONNECTORS_CONNECTORS_SERVICE_H_


text:
```
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
```

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.

## Two trailing spaces causes a hard break
```
Lorem ipsum dolor
sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
```

Lorem ipsum dolor
sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.

## Break on single newline?
```
Break
on
single
newline?
```

Break
on
single
newline?

(No, but Pandoc \[[example](http://pandoc.org/try/?text=Break%0Aon%0Asingle%0Anewline&from=markdown_github&to=html)\] and atom's [markdown-preview](https://github.com/atom/markdown-preview) think otherwise.))

## It depends, actually

It turns out, GitHub _does_ break on single newline in parts of GitHub, like issue comments, but not in .md documents.

https://github.com/gettalong/kramdown/issues/82#issuecomment-25339617


text:
package alluxio.client.block;

import alluxio.resource.DummyCloseableResource;
import alluxio.wire.BlockInfo;
import alluxio.wire.BlockLocation;
import alluxio.wire.LockBlockResult;
import alluxio.wire.WorkerNetAddress;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.io.File;
import java.util.Arrays;

/**
 * Tests for {@link AlluxioBlockStore}.
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest({BlockStoreContext.class})
public final class AlluxioBlockStoreTest {
  private static final long BLOCK_ID = 3L;
  private static final long LOCK_ID = 44L;
  private static final String WORKER_HOSTNAME_LOCAL = "localhost";
  private static final String WORKER_HOSTNAME_REMOTE = "remote";
  private static final WorkerNetAddress WORKER_NET_ADDRESS_LOCAL = new WorkerNetAddress()
      .setHost(WORKER_HOSTNAME_LOCAL);
  private static final WorkerNetAddress WORKER_NET_ADDRESS_REMOTE = new WorkerNetAddress()
      .setHost(WORKER_HOSTNAME_REMOTE);
  private static final BlockLocation BLOCK_LOCATION_LOCAL = new BlockLocation()
      .setWorkerAddress(WORKER_NET_ADDRESS_LOCAL);
  private static final BlockLocation BLOCK_LOCATION_REMOTE = new BlockLocation()
      .setWorkerAddress(WORKER_NET_ADDRESS_REMOTE);

  /**
   * The rule for a temporary folder.
   */
  @Rule
  public TemporaryFolder mTestFolder = new TemporaryFolder();

  private BlockMasterClient mMasterClient;
  private BlockWorkerClient mBlockWorkerClient;
  private AlluxioBlockStore mBlockStore;

  @Before
  public void before() throws Exception {
    mBlockWorkerClient = PowerMockito.mock(BlockWorkerClient.class);
    mMasterClient = PowerMockito.mock(BlockMasterClient.class);

    BlockStoreContext blockStoreContext = PowerMockito.mock(BlockStoreContext.class);
    // Mock block store context to return our mock clients
    Mockito.when(blockStoreContext.acquireWorkerClient(Mockito.any(WorkerNetAddress.class)))
        .thenReturn(mBlockWorkerClient);
    Mockito.when(blockStoreContext.acquireMasterClientResource()).thenReturn(
        new DummyCloseableResource<>(mMasterClient));

    mBlockStore = new AlluxioBlockStore(blockStoreContext, WORKER_HOSTNAME_LOCAL);
  }

  /**
   * Tests {@link AlluxioBlockStore#getInStream(long)} when a local block exists, making sure that
   * the local block is preferred.
   */
  @Test
  public void getInStreamLocal() throws Exception {
    Mockito.when(mMasterClient.getBlockInfo(BLOCK_ID)).thenReturn(new BlockInfo()
        .setLocations(Arrays.asList(BLOCK_LOCATION_REMOTE, BLOCK_LOCATION_LOCAL)));

    File mTestFile = mTestFolder.newFile("testFile");
    // When a block lock for id BLOCK_ID is requested, a path to a temporary file is returned
    Mockito.when(mBlockWorkerClient.lockBlock(BLOCK_ID)).thenReturn(
        new LockBlockResult().setLockId(LOCK_ID).setBlockPath(mTestFile.getAbsolutePath()));

    BufferedBlockInStream stream = mBlockStore.getInStream(BLOCK_ID);
    Assert.assertEquals(LocalBlockInStream.class, stream.getClass());
  }

  /**
   * Tests {@link AlluxioBlockStore#getInStream(long)} when no local block exists, making sure that
   * the first {@link BlockLocation} in the {@link BlockInfo} list is chosen.
   */
  @Test
  public void getInStreamRemote() throws Exception {
    Mockito.when(mMasterClient.getBlockInfo(BLOCK_ID)).thenReturn(new BlockInfo()
        .setLocations(Arrays.asList(BLOCK_LOCATION_REMOTE)));

    File mTestFile = mTestFolder.newFile("testFile");
    // When a block lock for id BLOCK_ID is requested, a path to a temporary file is returned
    Mockito.when(mBlockWorkerClient.lockBlock(BLOCK_ID)).thenReturn(
        new LockBlockResult().setLockId(LOCK_ID).setBlockPath(mTestFile.getAbsolutePath()));

    BufferedBlockInStream stream = mBlockStore.getInStream(BLOCK_ID);
    Assert.assertEquals(RemoteBlockInStream.class, stream.getClass());
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Grevillea 4(no. 32): 161 (1876)

#### Original name
Lenzites cookei Berk.

### Remarks
null


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Crystal Slider | Slider with thumbnails navigation</title>

  <meta name="viewport" content="width=device-width,user-scalable=no">

  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto">
  <link rel="stylesheet" href="../assets/css/styles.css">
  <link rel="stylesheet" href="../dist/crystalslider.min.css">

Crystal Slider

HTML

<div class="crystal-slider">
  <div data-crystal-thumbnail="img/slide-thumbnail-1.jpg">
    <img src="img/slide-1.jpg" alt="">
  </div>
  <div data-crystal-thumbnail="img/slide-thumbnail-2.jpg">
    <img src="img/slide-2.jpg" alt="">
  </div>
  <div data-crystal-thumbnail="img/slide-thumbnail-3.jpg">
    <img src="img/slide-3.jpg" alt="">
  </div>
</div>

JavaScript

const crystalSlider = new CrystalSlider({
  pagination: true,
  thumbnails: true
});


text:
def triangle(a, b, c):

# Ugly way
#     if a <= 0 or b <=0 or c <= 0:
#         raise TriangleError('All sides should be greater than 0')
#     elif a+b < c or a+c < b or b+c < a:
#         raise TriangleError('The sum of any two sides should be greater than the third one')
#     elif a == b == c:
#         return 'equilateral'
#     elif a == b or a == c or b == c:
#         return 'isosceles'
#     return 'scalene'

# "Oficial solution" for about_triangle_project.py

    sides = sorted([a, b, c])
    unique_sides = sorted(set(sides))

    if unique_sides[0] <= 0:
        raise TriangleError('All sides should be greater than 0')
    if sides[2] >= sides[0] + sides[1]:
        raise TriangleError('The sum of any two sides should be greater than the third one')
    if len(unique_sides) == 1:
        return 'equilateral'
    elif len(unique_sides) == 2:
        return 'isosceles'
    elif len(unique_sides) == 3:
        return 'scalene'

# Error class used in part 2.  No need to change this code.
class TriangleError(Exception):
    pass


text: import '../modules/alert-manager-sk';


text:
const express = require('express');
const userRoutes = require('./user.route');
const authRoutes = require('./auth.route');

const router = express.Router();

/**
 * GET v1/status
 */
router.get('/status', (req, res) => res.send('OK'));

/**
 * GET v1/docs
 */
router.use('/docs', express.static('docs'));

router.use('/users', userRoutes);
router.use('/auth', authRoutes);

module.exports = router;


text:
package scala.util

import org.junit.Assert._
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4

import scala.tools.testing.AssertUtil._

/** The java version property uses the spec version
 *  and must work for legacy "major.minor" and plain version_number,
 *  and fail otherwise.
 */
@RunWith(classOf[JUnit4])
class SpecVersionTest {
  class TestProperties(versionAt: String) extends PropertiesTrait {
    override def javaSpecVersion = versionAt

    override protected def pickJarBasedOn: Class[_] = ???
    override protected def propCategory: String = "test"

    // override because of vals like releaseVersion
    override lazy val scalaProps = new java.util.Properties
  }

  @Test
  def comparesJDK9Correctly(): Unit = {
    val sut9 = new TestProperties("9")
    assert(sut9 isJavaAtLeast "1")
    assert(sut9 isJavaAtLeast "1.5")
    assert(sut9 isJavaAtLeast "5")
    assert(sut9 isJavaAtLeast "1.8")
    assert(sut9 isJavaAtLeast "8")
    assert(sut9 isJavaAtLeast "9")
    assert(sut9.isJavaAtLeast(9))
    assertFalse(sut9.isJavaAtLeast(10))
    assertFalse(sut9.isJavaAtLeast("10"))
  }

  // SI-7265
  @Test
  def comparesCorrectly(): Unit = {
    val sut7 = new TestProperties("1.7")
    assert(sut7 isJavaAtLeast "1")
    assert(sut7 isJavaAtLeast "1.5")
    assert(sut7 isJavaAtLeast "5")
    assert(sut7 isJavaAtLeast "1.6")
    assert(sut7 isJavaAtLeast "1.7")
    assert(sut7.isJavaAtLeast(7))
    assertFalse(sut7.isJavaAtLeast(9))
    assertFalse(sut7 isJavaAtLeast "1.8")
    assertFalse(sut7 isJavaAtLeast "9")
    assertFalse(sut7 isJavaAtLeast "10")
  }

  @Test def variousBadVersionStrings(): Unit = {
    val sut = new TestProperties("9")
    assertThrows[NumberFormatException](sut.isJavaAtLeast("1.9"), _ == "Not a version: 1.9")
    assertThrows[NumberFormatException](sut.isJavaAtLeast("1."))
    assertThrows[NumberFormatException](sut.isJavaAtLeast("1.8."))
    assertThrows[NumberFormatException](sut.isJavaAtLeast("1.a"))
    assertThrows[NumberFormatException](sut.isJavaAtLeast(""))
    assertThrows[NumberFormatException](sut.isJavaAtLeast("."))
    assertThrows[NumberFormatException](sut.isJavaAtLeast(".."))
    assertThrows[NumberFormatException](sut.isJavaAtLeast(".5"))
    assertThrows[NumberFormatException](sut.isJavaAtLeast("9-ea"))  //version number, not version string
  }

  @Test def `spec has minor or more`(): Unit = {
    val sut = new TestProperties("9.2.5")
    assert(sut.isJavaAtLeast(9))
    assert(sut.isJavaAtLeast("9"))
    assert(sut.isJavaAtLeast("9.0.1"))
    assert(sut.isJavaAtLeast("9.2.1"))
    assert(sut.isJavaAtLeast("8.3.1"))
    assert(sut.isJavaAtLeast("8.3.1.1.1"))
    assertFalse(sut.isJavaAtLeast("9.3.1"))
    assertFalse(sut.isJavaAtLeast("10.3.1"))
  }

  @Test def `compares only major minor security`(): Unit = {
    val sut = new TestProperties("9.2.5.1.2.3")
    assert(sut.isJavaAtLeast(9))
    assert(sut.isJavaAtLeast("9"))
    assert(sut.isJavaAtLeast("9.0.1"))
    assert(sut.isJavaAtLeast("9.2.5.9.9.9"))
    assertFalse(sut.isJavaAtLeast("9.2.6"))
  }

  @Test def `futurely proofed`(): Unit = {
    val sut = new TestProperties("10.2.5")
    assert(sut.isJavaAtLeast(9))
    assert(sut.isJavaAtLeast(10))
    assert(sut.isJavaAtLeast("9"))
    assert(sut.isJavaAtLeast("9.0.1"))
    assert(sut.isJavaAtLeast("9.2.1"))
    assert(sut.isJavaAtLeast("8.3.1"))
    assert(sut.isJavaAtLeast("8.3.1.1.1"))
    assert(sut.isJavaAtLeast("9.3.1"))
    assertFalse(sut.isJavaAtLeast("10.3.1"))
  }
}


text:
path: "/docs/web/stencil"
title: Kitura Stencil
---

#Kitura Stencil

To implement [Stencil](https://github.com/stencilproject/Stencil) templating with a Kitura server, we use [Kitura-StencilTemplateEngine](https://github.com/Kitura/Kitura-StencilTemplateEngine). This package makes it easy to to create an HTML page with integrated Swift variables.

---

##Step 1: Create your Stencil routes

To use Stencil from a server, we first need to [add Kitura-StencilTemplateEngine to our dependencies](https://github.com/Kitura/Kitura-StencilTemplateEngine#add-dependencies).

> If you don't have a server, follow our [Create a server](../getting-started/create-server-cli) guide.

Next, we need to import the Stencil package:

```swift
import Stencil
```

Next, we need a file for our Stencil routes.

Open your `Application.swift` file:

```
open Sources/Application/Application.swift
```

Inside the `postInit()` function add:

```swift
initializeStencilRoutes(app: self)
```

Create a new file, called `StencilRoutes.swift`:

```
touch Sources/Application/Routes/StencilRoutes.swift
```

Open your `StencilRoutes.swift` file:

```
open Sources/Application/Routes/StencilRoutes.swift
```

Inside this file, add the framework for our routes code:

```swift
import KituraStencil

func initializeStencilRoutes(app: App) {
    // register template engine here
    app.router.get("/stencil") { request, response, next in
        // render response here
        next()
    }
}
```

---

##Step 2: Add a Stencil template engine

Next we'll register a Stencil temple engine to our router instance.

Open your `Application.swift` file:

```
open Sources/Application/Application.swift
```

Inside the `postInit()` function, below the line where we define the router, add:

```swift
app.router.add(templateEngine: StencilTemplateEngine())
```

The above line of code tells the server that on this instance of the router we'd like to use the Stencil template engine.

> Kitura supports multiple template engines being registered to a single instance of a router. By default each templating engine will handle files in the `./Views` directory that match the file extension it supports.

We've just added the Stencil template engine to our router, so now we can use it in a route.

Inside our get route, add the following:

```swift
let book = Book(id: 0, title: "A Game of Thrones", price: 14.99, genre: "fantasy")
try response.render("book.stencil", with: book)
```

Your completed `StencilRoutes.swift` should now look as follows:

```swift
import KituraStencil

func initializeStencilRoutes(app: App) {
    app.router.add(templateEngine: StencilTemplateEngine())
    app.router.get("/stencil") { request, response, next in
        let book = Book(id: 0, title: "A Game of Thrones", price: 14.99, genre: "fantasy")
        try response.render("book.stencil", with: book)
        next()
    }
}
```

The `response.render()` method attempts to populate the provided template file with the provided data.

In our case, the file `book.stencil` template will be populated with the `book` data and then rendered in the browser on `"/book"`.

This obviously will not work as we haven't created our `book.stencil` file.

---

##Step 3: Create the template file

By default Kitura looks for template files in a `./Views` directory found at the root of the project.

> Typically the root of your project is where the `.xcodeproj` directory is.

Once we are in the root of our project we can create the directory:

```
mkdir Views
```

Then we need to create our template file within the Views directory.

In a terminal run the following:

```
cd Views && touch book.stencil
```

Now we have everything we need to start creating our templates.

The last thing we need to do is recreate our Xcode project:

```
swift package generate-xcodeproj
```

This is to enable Xcode to pick up the new directory we've just added.

---

##Step 4: Populate the Stencil template file

> Stencil is a templating language that has a lot of powerful features, you can learn about them in the [Stencil guide](http://stencil.fuller.li/en/latest/).

We first need some template code to populate.

Open the `book.stencil` file and add the following:

```html
<html>
  <p> Id: {{ id }} </p>
  <p> Title: {{ title }} </p>
  <p> Price: {{ price }} </p>
  <p> Genre: {{ genre }} </p>
</html>
```

Now to test our templating, we first need to start the Kitura server.

Then in a browser open: localhost:8080/stencil

In the browser we should see:

```
Id: 0

Title: A Game of Thrones

Price: 14.99

Genre: "fantasy"
```

That's it! We've just rendered a simple data type in the browser using Kitura Stencil.