text:
namespace Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    public partial class ImageCreateResult
    {
        /// <summary>
        /// Initializes a new instance of the ImageCreateResult class.
        /// </summary>
        public ImageCreateResult()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the ImageCreateResult class.
        /// </summary>
        /// <param name="sourceUrl">Source URL of the image.</param>
        /// <param name="status">Status of the image creation. Possible values
        /// include: 'OK', 'OKDuplicate', 'ErrorSource', 'ErrorImageFormat',
        /// 'ErrorImageSize', 'ErrorStorage', 'ErrorLimitExceed',
        /// 'ErrorTagLimitExceed', 'ErrorRegionLimitExceed', 'ErrorUnknown',
        /// 'ErrorNegativeAndRegularTagOnSameImage', 'ErrorImageDimensions',
        /// 'ErrorInvalidTag'</param>
        /// <param name="image">The image.</param>
        public ImageCreateResult(string sourceUrl = default(string), string status = default(string), Image image = default(Image))
        {
            SourceUrl = sourceUrl;
            Status = status;
            Image = image;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets source URL of the image.
        /// </summary>
        [JsonProperty(PropertyName = "sourceUrl")]
        public string SourceUrl { get; private set; }

        /// <summary>
        /// Gets status of the image creation. Possible values include: 'OK',
        /// 'OKDuplicate', 'ErrorSource', 'ErrorImageFormat', 'ErrorImageSize',
        /// 'ErrorStorage', 'ErrorLimitExceed', 'ErrorTagLimitExceed',
        /// 'ErrorRegionLimitExceed', 'ErrorUnknown',
        /// 'ErrorNegativeAndRegularTagOnSameImage', 'ErrorImageDimensions',
        /// 'ErrorInvalidTag'
        /// </summary>
        [JsonProperty(PropertyName = "status")]
        public string Status { get; private set; }

        /// <summary>
        /// Gets the image.
        /// </summary>
        [JsonProperty(PropertyName = "image")]
        public Image Image { get; private set; }

    }
}


text:
#include <cms/TextMessage.h>

using namespace cms;

////////////////////////////////////////////////////////////////////////////////
TextMessage::~TextMessage() {

}

redpajama_set_name: RedPajamaGithub


text:
extern crate cassandra;
use cassandra::*;
use errors::*;
use std::str::FromStr;

fn insert_into_collections(session: &mut Session, key: &str, items: Vec<&str>) -> Result<CassResult> {
    let mut statement = stmt!("INSERT INTO examples.collections (key, items) VALUES (?, ?);");
    statement.bind(0, key)?;
    let mut set = Set::new(2);
    for item in items {
        set.append_string(item)?;
    }
    statement.bind_set(1, set)?;
    session.execute(&statement).wait()
}

fn select_from_collections(session: &mut Session, key: &str) -> Result<()> {
    let mut statement = stmt!("SELECT items FROM examples.collections WHERE key = ?");
    statement.bind(0, key)?;
    let result = session.execute(&statement).wait()?;
    println!("{:?}", result);
    for row in result.iter() {
        let column = row.get_column(0);
        let items_iterator: SetIterator = column?.set_iter()?;
        for item in items_iterator {
            println!("item: {:?}", item);
        }
    }
    Ok(())
}

fn main() {
    let create_ks = stmt!("CREATE KEYSPACE IF NOT EXISTS examples WITH replication = { \'class\': \
                           \'SimpleStrategy\', \'replication_factor\': \'1\' };");
    let create_table = stmt!("CREATE TABLE IF NOT EXISTS examples.collections (key text, items set<text>, PRIMARY \
                              KEY (key))");

    let items = vec!["apple", "orange", "banana", "mango"];
    let contact_points = ContactPoints::from_str("127.0.0.1").unwrap();
    let mut cluster = Cluster::default();
    cluster.set_contact_points(contact_points).unwrap();

    match cluster.connect() {
        Ok(ref mut session) => {
            session.execute(&create_ks).wait().unwrap();
            session.execute(&create_table).wait().unwrap();
            insert_into_collections(session, "test", items).unwrap();
            select_from_collections(session, "test").unwrap();
        }
        err => println!("{:?}", err),
    }
}


text:
import bs4
from collections import defaultdict
from functools import lru_cache
import lxml.etree
from nullroute.core import *
from nullroute.scrape import urljoin
from pprint import pprint
import re
import requests

FAKE_UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36"

def _grep(pat, strings):
    pat = re.compile(pat)
    for string in strings:
        m = re.match(pat, string)
        if m:
            return m.group(1)
    raise IndexError("inputs %r do not match %r" % (strings, pat))

def _strip_prefix(arg, prefix, strict=True):
    if arg.startswith(prefix):
        return arg[len(prefix):]
    elif strict:
        raise ValueError("input %r does not match prefix %r" % (arg, prefix))
    else:
        return arg

def _strip_suffixes(arg, sfs):
    for sf in sfs:
        if arg.endswith(sf):
            return arg[:-len(sf)]
    return arg

class BooruApi(object):
    NAME_RE = []
    URL_RE = []

    HASH_SUFFIX = True

    def __init__(self, tag_filter=None):
        self.tag_filter = tag_filter
        self.ua = requests.Session()

    def match_file_name(self, name):
        for pat in self.NAME_RE:
            m = pat.match(name)
            if m:
                return m.group("id")

    def match_post_url(self, url):
        for pat in self.URL_RE:
            m = pat.match(url)
            if m:
                return m.group("id")

    def find_posts(self, tags, page=1, limit=100):
        raise NotImplementedError

    def find_post_by_id(self, post_id):
        return next(self.find_posts("id:%s" % post_id, limit=1))

    def find_posts_by_md5(self, md5):
        yield from self.find_posts("md5:%s" % md5)

    def get_post_info(self, post_id):
        info = self.find_post_by_id(post_id)
        return info

    def get_post_tags(self, post_id):
        raise NotImplementedError

    def get_post_original(self, post_id):
        raise NotImplementedError

    def sort_tags(self, raw_tags):
        all_tags = []
        for key in ("artist", "copyright", "character"):
            val = [t.replace(" ", "_") for t in raw_tags[key]]
            if key == "character" and len(val) <= 2:
                bad_suffixes = ["_(%s)" % s for s in raw_tags["copyright"]]
                val = [_strip_suffixes(t, bad_suffixes) for t in val]
            if key == "character" and len(val) > 8:
                val = []
            all_tags += sorted(val)
        if self.tag_filter:
            all_tags = self.tag_filter.filter(all_tags)
        return all_tags

## Danbooru

class DanbooruApi(BooruApi):
    SITE_URL = "https://danbooru.donmai.us"
    URL_RE = [
        re.compile(r"https?://danbooru.donmai.us/posts/(?P<id>\d+)"),
        #re.compile(r"https?://danbooru\.donmai\.us/data/.+__(?<md5>[^_]+)\.\w+$"),
    ]
    ID_PREFIX = "db%s"
    HASH_SUFFIX = True

    _cache = {}

    def find_posts(self, tags, page=1, limit=100):
        ep = "/posts.xml"
        args = {"tags": tags,
                "page": page,
                "limit": limit}

        resp = self.ua.get(self.SITE_URL + ep, params=args)
        resp.raise_for_status()

        tree = lxml.etree.XML(resp.content)
        for item in tree.xpath("/posts/post"):
            attrib = {child.tag.replace("-", "_"): child.text
                      for child in item.iterchildren()}
            attrib = {"tags": {}}
            for child in item.iterchildren():
                key = child.tag.replace("-", "_")
                val = child.text
                attrib[key] = val
                if key.startswith("tag_string_"):
                    kind = _strip_prefix(key, "tag_string_")
                    attrib["tags"][kind] = val.split() if val else []
            pprint(attrib)
            self._cache["id:%(id)s" % attrib] = attrib
            yield attrib

    def get_post_tags(self, post_id):
        key = "id:%s" % post_id
        post = self._cache.get(key)
        if not post:
            posts = self.find_posts(key)
            try:
                post = next(posts)
            except StopIteration:
                raise KeyError("post %r not found" % key)
        return post["tags"]

## Gelbooru

class GelbooruApi(BooruApi):
    SITE_URL = "https://gelbooru.com/"
    POST_URL = "https://gelbooru.com/index.php?page=post&s=view&id=%s"
    ID_PREFIX = "g%s"
    TAG_SCRAPE = True

    def _fetch_url(self, url, *args, **kwargs):
        Core.debug("fetching %r" % url)
        resp = self.ua.get(url, *args, **kwargs)
        resp.raise_for_status()
        return resp

    def find_posts(self, query, limit=100):
        # API has been blocked
        post_ids = []
        next_url = None

        while True:
            if next_url:
                resp = self._fetch_url(next_url)
            else:
                args = {"page": "post", "s": "list", "tags": query}
                resp = self._fetch_url(self.SITE_URL, params=args)
            body = bs4.BeautifulSoup(resp.content, "lxml")
            post_ids = []
            for span in body.select("span.thumb"):
                post_id = span["id"].lstrip("s")
                post_ids.append(post_id)
                if len(post_ids) >= limit:
                    break
            tmp = body.select_one("#paginater a[alt='next']")
            if not tmp:
                break
            next_url = urljoin(self.SITE_URL, tmp["href"])

        for post_id in post_ids:
            yield {"id": post_id}

    def _scrape_post_info(self, post_id):
        args = {"page": "post", "s": "view", "id": post_id}
        resp = self.ua.get(self.SITE_URL, params=args)
        resp.raise_for_status()

        page = bs4.BeautifulSoup(resp.content, "lxml")

        post = {"id": post_id,
                "tags": defaultdict(set)}

        for tag_li in page.select("li[class^='tag-type-']"):
            tag_type = _grep(r"^tag-type-(.+)", tag_li["class"])
            tag_value = tag_li.find_all("a")[-1].get_text()
            post["tags"][tag_type].add(tag_value)

        return post

    def get_post_tags(self, post_id):
        info = self._scrape_post_info(post_id)
        return info["tags"]

## Sankaku Complex

class SankakuApi(BooruApi):
    SITE_URL = "https://chan.sankakucomplex.com"
    POST_URL = "https://chan.sankakucomplex.com/post/show/%s"
    URL_RE = [
        re.compile(r"^https://chan\.sankakucomplex\.com/post/show/(?P<id>\d+)"),
        re.compile(r"^https://cs\.sankakucomplex\.com/data/\w+/\w+/(?P<md5>\w+)\.\w+\?(?P<id>\d+)"),
    ]
    ID_PREFIX = "san%s"

    def _fetch_url(self, *args, **kwargs):
        headers = kwargs.setdefault("headers", {})
        headers["User-Agent"] = FAKE_UA
        while True:
            resp = self.ua.get(*args, **kwargs)
            Core.debug("fetched %r" % resp.url)
            if resp.status_code == 503:
                Core.debug("error %r, retrying in 1s" % resp.status_code)
                time.sleep(1)
            else:
                resp.raise_for_status()
                return resp

    def find_posts(self, query, limit=20):
        # API has been blocked a long time ago; resort to scraping
        post_ids = []
        next_url = True
        page = 1

        while next_url:
            Core.debug("scraping %r (page %d)" % (query, page))
            args = {"tags": query,
                    "page": page}
            resp = self._fetch_url(self.SITE_URL, params=args)
            body = bs4.BeautifulSoup(resp.content, "lxml")
            div = body.select_one("div.content div")
            post_ids = []
            for span in div.find_all("span", {"id": True}):
                post_id = span["id"].lstrip("p")
                post_ids.append(post_id)
                if len(post_ids) >= limit:
                    break
            next_url = body.get("next-page-url")
            page += 1

        for post_id in post_ids:
            yield {"id": post_id}

    def _scrape_post_info(self, post_id):
        resp = self._fetch_url(self.POST_URL % post_id)
        resp.raise_for_status()

        page = bs4.BeautifulSoup(resp.content, "lxml")
        sidebar = page.select_one("ul#tag-sidebar")

        post = {"id": post_id,
                "tags": defaultdict(set)}

        for tag_li in sidebar.find_all("li"):
            tag_type = _grep(r"^tag-type-(.+)", tag_li["class"])
            tag_value = tag_li.select_one("a[itemprop='keywords']").get_text()
            post["tags"][tag_type].add(tag_value)

        return post

    def get_post_tags(self, post_id):
        info = self._scrape_post_info(post_id)
        return info["tags"]

## Yande.re

class MoebooruApi(BooruApi):
    # official API

    def find_posts(self, tags, page=1, limit=100):
        ep = "/post.xml"
        args = {"tags": tags,
                "page": page,
                "limit": limit}

        resp = self.ua.get(self.SITE_URL + ep, params=args)
        resp.raise_for_status()

        tree = lxml.etree.XML(resp.content)
        for item in tree.xpath("/posts/post"):
            yield dict(item.attrib)

    # information unavailable via API (tag types)

    @lru_cache(maxsize=1024)
    def _fetch_post_page(self, post_id):
        resp = self.ua.get(self.POST_URL % post_id)
        resp.raise_for_status()

        page = bs4.BeautifulSoup(resp.content, "lxml")
        return page

    def _scrape_post_info(self, post_id):
        page = self._fetch_post_page(post_id)
        sidebar = page.select_one("ul#tag-sidebar")

        post = {"id": post_id,
                "tags": defaultdict(set)}

        for tag_li in sidebar.find_all("li"):
            tag_type = _grep(r"^tag-type-(.+)", tag_li["class"])
            tag_value = tag_li.find_all("a")[-1].get_text()
            post["tags"][tag_type].add(tag_value)

        return post

    def get_post_tags(self, post_id):
        info = self._scrape_post_info(post_id)
        return info["tags"]

    def get_post_original(self, post_id):
        info = self.find_post_by_id(post_id)
        return urljoin(self.SITE_URL, info["file_url"])

class KonachanApi(MoebooruApi):
    SITE_URL = "http://konachan.com/"
    POST_URL = "http://konachan.com/post/show/%s"
    URL_RE = [
        re.compile(r"^https?://konachan\.com/post/show/(?P<id>\d+)"),
        re.compile(r"^https?://konachan\.com/image/(?P<md5>\w+)/Konachan.com - (?P<id>\d+) "),
    ]
    ID_PREFIX = "kona%s"

class YandereApi(MoebooruApi):
    SITE_URL = "https://yande.re"
    POST_URL = "https://yande.re/post/show/%s"
    URL_RE = [
        re.compile(r"^https://yande\.re/post/show/(?P<id>\d+)"),
        re.compile(r"^https://files\.yande\.re/image/(?P<md5>\w+)/yande.re (?P<id>\d+) "),
    ]
    ID_PREFIX = "yande.re %s"
    HASH_SUFFIX = False

apis = {
    "gelbooru": GelbooruApi,
    "sankaku": SankakuApi,
    "danbooru": DanbooruApi,
    "yandere": YandereApi,
    "konachan": KonachanApi,
}


text:
#ifndef CPPMICROSERVICES_PROTOTYPESERVICEFACTORY_H
#define CPPMICROSERVICES_PROTOTYPESERVICEFACTORY_H

#include "cppmicroservices/ServiceFactory.h"

namespace cppmicroservices {

/**
 * @ingroup MicroServices
 *
 * A factory for \link Constants::SCOPE_PROTOTYPE prototype scope\endlink services.
 * The factory can provide multiple, unique service objects.
 *
 * When registering a service, a PrototypeServiceFactory object can be used
 * instead of a service object, so that the bundle developer can create a
 * unique service object for each caller that is using the service.
 * When a caller uses a ServiceObjects to request a service instance, the
 * framework calls the GetService method to return a service object specifically
 * for the requesting caller. The caller can release the returned service object
 * and the framework will call the UngetService method with the service object.
 * When a bundle uses the BundleContext::GetService(const ServiceReferenceBase&)
 * method to obtain a service object, the framework acts as if the service
 * has bundle scope. That is, the framework will call the GetService method to
 * obtain a bundle-scoped instance which will be cached and have a use count.
 * See ServiceFactory.
 *
 * A bundle can use both ServiceObjects and BundleContext::GetService(const ServiceReferenceBase&)
 * to obtain a service object for a service. ServiceObjects::GetService() will always
 * return an instance provided by a call to GetService(const Bundle&, const ServiceRegistrationBase&)
 * and BundleContext::GetService(const ServiceReferenceBase&) will always
 * return the bundle-scoped instance.
 * PrototypeServiceFactory objects are only used by the framework and are not made
 * available to other bundles. The framework may concurrently call a PrototypeServiceFactory.
 *
 * @see BundleContext::GetServiceObjects()
 * @see ServiceObjects
 */
struct PrototypeServiceFactory : public ServiceFactory
{

  /**
   * Returns a service object for a caller.
   *
   * The framework invokes this method for each caller requesting a service object using
   * ServiceObjects::GetService(). The factory can then return a specific service object for the caller.
   * The framework checks that the returned service object is valid. If the returned service
   * object is empty or does not contain entries for all the interfaces named when the service
   * was registered, a warning is issued and nullptr is returned to the caller. If this
   * method throws an exception, a warning is issued and nullptr is returned to the caller.
   *
   * @param bundle The bundle requesting the service.
   * @param registration The ServiceRegistrationBase object for the requested service.
   * @return A service object that must contain entries for all the interfaces named when
   *         the service was registered.
   *
   * @see ServiceObjects#GetService()
   * @see InterfaceMapConstPtr
   */
  InterfaceMapConstPtr GetService(
    const Bundle& bundle,
    const ServiceRegistrationBase& registration) override = 0;

  /**
   * Releases a service object created for a caller.
   *
   * The framework invokes this method when a service has been released by a bundles such as
   * by calling ServiceObjects::UngetService(). The service object may then be destroyed.
   * If this method throws an exception, a warning is issued.
   *
   * @param bundle The bundle releasing the service.
   * @param registration The ServiceRegistrationBase object for the service being released.
   * @param service The service object returned by a previous call to the GetService method.
   *
   * @see ServiceObjects::UngetService()
   */
  void UngetService(const Bundle& bundle,
                            const ServiceRegistrationBase& registration,
                            const InterfaceMapConstPtr& service) override = 0;
};
}

#endif // CPPMICROSERVICES_PROTOTYPESERVICEFACTORY_H


text:
package com.intellij.debugger.impl.descriptors.data;

import com.intellij.debugger.ui.impl.watch.ArgumentValueDescriptorImpl;
import com.intellij.openapi.project.Project;
import com.sun.jdi.Value;
import org.jetbrains.annotations.NotNull;

public class ArgValueData extends DescriptorData<ArgumentValueDescriptorImpl>{
  private final int myIndex;
  private final Value myValue;
  private final boolean myIsParam;

  public ArgValueData(int index, Value value, boolean isParam) {
    super();
    myIndex = index;
    myValue = value;
    myIsParam = isParam;
  }

  protected ArgumentValueDescriptorImpl createDescriptorImpl(@NotNull Project project) {
    return new ArgumentValueDescriptorImpl(project, myIndex, myValue, myIsParam);
  }

  public boolean equals(Object object) {
    if(!(object instanceof ArgValueData)) return false;

    return myIndex == ((ArgValueData)object).myIndex;
  }

  public int hashCode() {
    return myIndex;
  }

  public DisplayKey<ArgumentValueDescriptorImpl> getDisplayKey() {
    return new SimpleDisplayKey<ArgumentValueDescriptorImpl>(myIndex);
  }
}


text:
<?php
require_once("scrt/conexion.php");
if(!isset($_POST['unidad']))$idusuario=1;else $idusuario=$_POST['unidad'];

$desde=date("Y/m/d H:i:s",mktime(date("H"), date("i"), date("s"), date("m")-2, date("d"), date("Y")));
$sql="SELECT idpos, fechahora, latitud, longitud, estado FROM posicion
        WHERE fechahora>='$desde' and idusuario=$idusuario ORDER BY idpos";
$rs=$cnx->query($sql);
$taxis="";$lugares="";
$centro="new google.maps.LatLng(-12.058434, -77.0117529)";
$cont=0;
while($reg=$rs->fetchObject()){
  $cont++;
  if($cont==1)$centro="new google.maps.LatLng($reg->latitud, $reg->longitud)";
  $hora=substr($reg->fechahora,11,5);
  $lugares.="new google.maps.LatLng($reg->latitud, $reg->longitud),";
  $taxis.="['($cont) - $hora', $reg->latitud, $reg->longitud, '$reg->estado',$cont],";
}
$taxis=substr($taxis,0,strlen($taxis)-1);
$lugares=substr($lugares,0,strlen($lugares)-1);

$sqlu="select idusuario,nombre from usuario";
$rsu=$cnx->query($sqlu);
?>
<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Ruta</title>

  <form name="form1" action="" method="post">
    <select name="unidad" id="unidad" onchange="form1.submit()">
    <?php while($regu=$rsu->fetchObject()){
      if($regu->idusuario==$idusuario) $selected="selected='selected'";
      else $selected='';
      ?>
      <option value="<?php echo $regu->idusuario?>" <?php echo $selected?>><?php echo $regu->nombre?></option>
    <?php } ?>
    </select>
  </form>


text:
function updateFcn = indexingTooltip(xname, yname)
%BETTER TOOLTIP - Get an "UpdateFcn" for a datacursormode object
%which also shows the index of the point

    function txt = myUpdateFcn(~, event_obj)
        pos = get(event_obj, 'Position');
        idx = get(event_obj, 'DataIndex');

%         if exist(indexInto, 'var')
%             idx = indexInto(idx);
%         end
        txt = {[xname, ': ', num2str(pos(1))], ...
               [yname, ': ', num2str(pos(2))], ...
               ['idx: ', num2str(idx)]};
    end

    updateFcn = @myUpdateFcn;

end


text:
@interface AppDelegate : UIResponder <UIApplicationDelegate,ICETutorialControllerDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ICETutorialController *viewController;

@end


text:
package com.ciplogic.jsinjector;

public class ParsedFile {
    private String path;
    private String debugName;

    public ParsedFile(String path, String debugName) {
        this.path = path;
        this.debugName = debugName;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getDebugName() {
        return debugName;
    }

    public void setDebugName(String debugName) {
        this.debugName = debugName;
    }
}


text:
/**
 * @file Label Factory
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */

import { AA1 } from '../structure/structure-constants'
import AtomProxy from '../proxy/atom-proxy'
import { sprintf } from 'sprintf-js'

export const LabelFactoryTypes = {
  '': '',
  'atomname': 'atom name',
  'atomindex': 'atom index',
  'occupancy': 'occupancy',
  'bfactor': 'b-factor',
  'serial': 'serial',
  'element': 'element',
  'atom': 'atom name + index',
  'resname': 'residue name',
  'resno': 'residue no',
  'res': 'one letter code + no',
  'residue': '[residue name] + no + inscode',
  'text': 'text',
  'format': 'format',
  'qualified': 'qualified name'
}
export type LabelType = keyof typeof LabelFactoryTypes

class LabelFactory {

  static types = LabelFactoryTypes
  errorLogged: boolean = false

  constructor(readonly type: LabelType, readonly text: { [k: number]: string } = {},
    readonly format: string = '') {}

  atomLabel (a: AtomProxy) {
    const type = this.type

    let l

    switch (type) {
      case 'atomname':
        l = a.atomname
        break

      case 'atomindex':
        l = `${a.index}`
        break

      case 'occupancy':
        l = a.occupancy.toFixed(2)
        break

      case 'bfactor':
        l = a.bfactor.toFixed(2)
        break

      case 'serial':
        l = `${a.serial}`
        break

      case 'element':
        l = a.element
        break

      case 'atom':
        l = `${a.atomname}|${a.index}`
        break

      case 'resname':
        l = a.resname
        break

      case 'resno':
        l = `${a.resno}`
        break

      case 'res':
        l = `${(AA1[ a.resname.toUpperCase() ] || a.resname)}${a.resno}`
        break

      case 'residue':
        const aa1 = AA1[ a.resname.toUpperCase() ]
        if (aa1 && !a.inscode) {
          l = `${aa1}${a.resno}`
        } else {
          l = `[${a.resname}]${a.resno}${a.inscode}`
        }
        break

      case 'text':
        l = this.text[ a.index ]
        break

      case 'format':
        try {
          l = sprintf(this.format, a)
        } catch (e) {
          if (!this.errorLogged) {
            this.errorLogged = true
            console.log(e.message)
          }
        }
        break

      // case "qualified":
      default:
        l = a.qualifiedName()
        break
    }

    return l === undefined ? '' : l
  }
}

export default LabelFactory


text:
/**
 * Autogenerated by Thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 */
package org.apache.cassandra.thrift;
/*
 *
 * 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.
 *
 */

import org.apache.commons.lang.builder.HashCodeBuilder;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A KeySlice is key followed by the data it maps to. A collection of KeySlice is returned by the get_range_slice operation.
 *
 * @param key. a row key
 * @param columns. List of data represented by the key. Typically, the list is pared down to only the columns specified by
 *                 a SlicePredicate.
 */
public class KeySlice implements org.apache.thrift.TBase<KeySlice, KeySlice._Fields>, java.io.Serializable, Cloneable {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("KeySlice");

  private static final org.apache.thrift.protocol.TField KEY_FIELD_DESC = new org.apache.thrift.protocol.TField("key", org.apache.thrift.protocol.TType.STRING, (short)1);
  private static final org.apache.thrift.protocol.TField COLUMNS_FIELD_DESC = new org.apache.thrift.protocol.TField("columns", org.apache.thrift.protocol.TType.LIST, (short)2);

  public ByteBuffer key;
  public List<ColumnOrSuperColumn> columns;

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    KEY((short)1, "key"),
    COLUMNS((short)2, "columns");

    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

    static {
      for (_Fields field : EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // KEY
          return KEY;
        case 2: // COLUMNS
          return COLUMNS;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    public static _Fields findByName(String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final String _fieldName;

    _Fields(short thriftId, String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments

  public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.KEY, new org.apache.thrift.meta_data.FieldMetaData("key", org.apache.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING        , true)));
    tmpMap.put(_Fields.COLUMNS, new org.apache.thrift.meta_data.FieldMetaData("columns", org.apache.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
            new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, ColumnOrSuperColumn.class))));
    metaDataMap = Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(KeySlice.class, metaDataMap);
  }

  public KeySlice() {
  }

  public KeySlice(
    ByteBuffer key,
    List<ColumnOrSuperColumn> columns)
  {
    this();
    this.key = key;
    this.columns = columns;
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public KeySlice(KeySlice other) {
    if (other.isSetKey()) {
      this.key = org.apache.thrift.TBaseHelper.copyBinary(other.key);
;
    }
    if (other.isSetColumns()) {
      List<ColumnOrSuperColumn> __this__columns = new ArrayList<ColumnOrSuperColumn>();
      for (ColumnOrSuperColumn other_element : other.columns) {
        __this__columns.add(new ColumnOrSuperColumn(other_element));
      }
      this.columns = __this__columns;
    }
  }

  public KeySlice deepCopy() {
    return new KeySlice(this);
  }

  @Override
  public void clear() {
    this.key = null;
    this.columns = null;
  }

  public byte[] getKey() {
    setKey(org.apache.thrift.TBaseHelper.rightSize(key));
    return key == null ? null : key.array();
  }

  public ByteBuffer bufferForKey() {
    return key;
  }

  public KeySlice setKey(byte[] key) {
    setKey(key == null ? (ByteBuffer)null : ByteBuffer.wrap(key));
    return this;
  }

  public KeySlice setKey(ByteBuffer key) {
    this.key = key;
    return this;
  }

  public void unsetKey() {
    this.key = null;
  }

  /** Returns true if field key is set (has been assigned a value) and false otherwise */
  public boolean isSetKey() {
    return this.key != null;
  }

  public void setKeyIsSet(boolean value) {
    if (!value) {
      this.key = null;
    }
  }

  public int getColumnsSize() {
    return (this.columns == null) ? 0 : this.columns.size();
  }

  public java.util.Iterator<ColumnOrSuperColumn> getColumnsIterator() {
    return (this.columns == null) ? null : this.columns.iterator();
  }

  public void addToColumns(ColumnOrSuperColumn elem) {
    if (this.columns == null) {
      this.columns = new ArrayList<ColumnOrSuperColumn>();
    }
    this.columns.add(elem);
  }

  public List<ColumnOrSuperColumn> getColumns() {
    return this.columns;
  }

  public KeySlice setColumns(List<ColumnOrSuperColumn> columns) {
    this.columns = columns;
    return this;
  }

  public void unsetColumns() {
    this.columns = null;
  }

  /** Returns true if field columns is set (has been assigned a value) and false otherwise */
  public boolean isSetColumns() {
    return this.columns != null;
  }

  public void setColumnsIsSet(boolean value) {
    if (!value) {
      this.columns = null;
    }
  }

  public void setFieldValue(_Fields field, Object value) {
    switch (field) {
    case KEY:
      if (value == null) {
        unsetKey();
      } else {
        setKey((ByteBuffer)value);
      }
      break;

    case COLUMNS:
      if (value == null) {
        unsetColumns();
      } else {
        setColumns((List<ColumnOrSuperColumn>)value);
      }
      break;

    }
  }

  public Object getFieldValue(_Fields field) {
    switch (field) {
    case KEY:
      return getKey();

    case COLUMNS:
      return getColumns();

    }
    throw new IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new IllegalArgumentException();
    }

    switch (field) {
    case KEY:
      return isSetKey();
    case COLUMNS:
      return isSetColumns();
    }
    throw new IllegalStateException();
  }

  @Override
  public boolean equals(Object that) {
    if (that == null)
      return false;
    if (that instanceof KeySlice)
      return this.equals((KeySlice)that);
    return false;
  }

  public boolean equals(KeySlice that) {
    if (that == null)
      return false;

    boolean this_present_key = true && this.isSetKey();
    boolean that_present_key = true && that.isSetKey();
    if (this_present_key || that_present_key) {
      if (!(this_present_key && that_present_key))
        return false;
      if (!this.key.equals(that.key))
        return false;
    }

    boolean this_present_columns = true && this.isSetColumns();
    boolean that_present_columns = true && that.isSetColumns();
    if (this_present_columns || that_present_columns) {
      if (!(this_present_columns && that_present_columns))
        return false;
      if (!this.columns.equals(that.columns))
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    HashCodeBuilder builder = new HashCodeBuilder();

    boolean present_key = true && (isSetKey());
    builder.append(present_key);
    if (present_key)
      builder.append(key);

    boolean present_columns = true && (isSetColumns());
    builder.append(present_columns);
    if (present_columns)
      builder.append(columns);

    return builder.toHashCode();
  }

  public int compareTo(KeySlice other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;
    KeySlice typedOther = (KeySlice)other;

    lastComparison = Boolean.valueOf(isSetKey()).compareTo(typedOther.isSetKey());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetKey()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.key, typedOther.key);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetColumns()).compareTo(typedOther.isSetColumns());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetColumns()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.columns, typedOther.columns);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
    org.apache.thrift.protocol.TField field;
    iprot.readStructBegin();
    while (true)
    {
      field = iprot.readFieldBegin();
      if (field.type == org.apache.thrift.protocol.TType.STOP) {
        break;
      }
      switch (field.id) {
        case 1: // KEY
          if (field.type == org.apache.thrift.protocol.TType.STRING) {
            this.key = iprot.readBinary();
          } else {
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
          }
          break;
        case 2: // COLUMNS
          if (field.type == org.apache.thrift.protocol.TType.LIST) {
            {
              org.apache.thrift.protocol.TList _list16 = iprot.readListBegin();
              this.columns = new ArrayList<ColumnOrSuperColumn>(_list16.size);
              for (int _i17 = 0; _i17 < _list16.size; ++_i17)
              {
                ColumnOrSuperColumn _elem18;
                _elem18 = new ColumnOrSuperColumn();
                _elem18.read(iprot);
                this.columns.add(_elem18);
              }
              iprot.readListEnd();
            }
          } else {
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
          }
          break;
        default:
          org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
      }
      iprot.readFieldEnd();
    }
    iprot.readStructEnd();

    // check for required fields of primitive type, which can't be checked in the validate method
    validate();
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    validate();

    oprot.writeStructBegin(STRUCT_DESC);
    if (this.key != null) {
      oprot.writeFieldBegin(KEY_FIELD_DESC);
      oprot.writeBinary(this.key);
      oprot.writeFieldEnd();
    }
    if (this.columns != null) {
      oprot.writeFieldBegin(COLUMNS_FIELD_DESC);
      {
        oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, this.columns.size()));
        for (ColumnOrSuperColumn _iter19 : this.columns)
        {
          _iter19.write(oprot);
        }
        oprot.writeListEnd();
      }
      oprot.writeFieldEnd();
    }
    oprot.writeFieldStop();
    oprot.writeStructEnd();
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder("KeySlice(");
    boolean first = true;

    sb.append("key:");
    if (this.key == null) {
      sb.append("null");
    } else {
      org.apache.thrift.TBaseHelper.toString(this.key, sb);
    }
    first = false;
    if (!first) sb.append(", ");
    sb.append("columns:");
    if (this.columns == null) {
      sb.append("null");
    } else {
      sb.append(this.columns);
    }
    first = false;
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.thrift.TException {
    // check for required fields
    if (key == null) {
      throw new org.apache.thrift.protocol.TProtocolException("Required field 'key' was not present! Struct: " + toString());
    }
    if (columns == null) {
      throw new org.apache.thrift.protocol.TProtocolException("Required field 'columns' was not present! Struct: " + toString());
    }
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
    try {
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

}


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview The entry point for all ChromeVox2 related code for the
 * background page.
 */

goog.provide('Background');
goog.provide('global');

goog.require('AutomationPredicate');
goog.require('AutomationUtil');
goog.require('ClassicCompatibility');
goog.require('Output');
goog.require('Output.EventType');
goog.require('cursors.Cursor');
goog.require('cvox.BrailleKeyCommand');
goog.require('cvox.ChromeVoxEditableTextBase');
goog.require('cvox.ExtensionBridge');
goog.require('cvox.NavBraille');

goog.scope(function() {
var AutomationNode = chrome.automation.AutomationNode;
var Dir = AutomationUtil.Dir;
var EventType = chrome.automation.EventType;
var RoleType = chrome.automation.RoleType;

/**
 * All possible modes ChromeVox can run.
 * @enum {string}
 */
var ChromeVoxMode = {
  CLASSIC: 'classic',
  COMPAT: 'compat',
  NEXT: 'next',
  FORCE_NEXT: 'force_next'
};

/**
 * ChromeVox2 background page.
 * @constructor
 */
Background = function() {
  /**
   * A list of site substring patterns to use with ChromeVox next. Keep these
   * strings relatively specific.
   * @type {!Array<string>}
   * @private
   */
  this.whitelist_ = ['chromevox_next_test'];

  /**
   * @type {cursors.Range}
   * @private
   */
  this.currentRange_ = null;

  /**
   * Which variant of ChromeVox is active.
   * @type {ChromeVoxMode}
   * @private
   */
  this.mode_ = ChromeVoxMode.CLASSIC;

  /** @type {!ClassicCompatibility} @private */
  this.compat_ = new ClassicCompatibility();

  // Manually bind all functions to |this|.
  for (var func in this) {
    if (typeof(this[func]) == 'function')
      this[func] = this[func].bind(this);
  }

  /**
   * Maps an automation event to its listener.
   * @type {!Object<EventType, function(Object) : void>}
   */
  this.listeners_ = {
    alert: this.onEventDefault,
    focus: this.onFocus,
    hover: this.onEventDefault,
    loadComplete: this.onLoadComplete,
    menuStart: this.onEventDefault,
    menuEnd: this.onEventDefault,
    menuListValueChanged: this.onEventDefault,
    textChanged: this.onTextOrTextSelectionChanged,
    textSelectionChanged: this.onTextOrTextSelectionChanged,
    valueChanged: this.onValueChanged
  };

  chrome.automation.getDesktop(this.onGotDesktop);

  // Handle messages directed to the Next background page.
  cvox.ExtensionBridge.addMessageListener(function(msg, port) {
    var target = msg['target'];
    var action = msg['action'];

    switch (target) {
      case 'next':
        if (action == 'getIsClassicEnabled') {
          var url = msg['url'];
          var isClassicEnabled = this.shouldEnableClassicForUrl_(url);
          port.postMessage({
            target: 'next',
            isClassicEnabled: isClassicEnabled
          });
        }
        break;
    }
  }.bind(this));
};

Background.prototype = {
  /** Forces ChromeVox Next to be active for all tabs. */
  forceChromeVoxNextActive: function() {
    this.setChromeVoxMode(ChromeVoxMode.FORCE_NEXT);
  },

  /**
   * Handles all setup once a new automation tree appears.
   * @param {chrome.automation.AutomationNode} desktop
   */
  onGotDesktop: function(desktop) {
    // Register all automation event listeners.
    for (var eventType in this.listeners_)
      desktop.addEventListener(eventType, this.listeners_[eventType], true);

    // Register a tree change observer.
    chrome.automation.addTreeChangeObserver(this.onTreeChange);

    // The focused state gets set on the containing webView node.
    var webView = desktop.find({role: RoleType.webView,
                                state: {focused: true}});
    if (webView) {
      var root = webView.find({role: RoleType.rootWebArea});
      if (root) {
        this.onLoadComplete(
            {target: root,
             type: chrome.automation.EventType.loadComplete});
      }
    }
  },

  /**
   * Handles chrome.commands.onCommand.
   * @param {string} command
   * @param {boolean=} opt_skipCompat Whether to skip compatibility checks.
   */
  onGotCommand: function(command, opt_skipCompat) {
    if (!this.currentRange_)
      return;

    if (!opt_skipCompat && this.mode_ === ChromeVoxMode.COMPAT) {
      if (this.compat_.onGotCommand(command))
        return;
    }

    var current = this.currentRange_;
    var dir = Dir.FORWARD;
    var pred = null;
    var predErrorMsg = undefined;
    switch (command) {
      case 'nextCharacter':
        current = current.move(cursors.Unit.CHARACTER, Dir.FORWARD);
        break;
      case 'previousCharacter':
        current = current.move(cursors.Unit.CHARACTER, Dir.BACKWARD);
        break;
      case 'nextWord':
        current = current.move(cursors.Unit.WORD, Dir.FORWARD);
        break;
      case 'previousWord':
        current = current.move(cursors.Unit.WORD, Dir.BACKWARD);
        break;
      case 'nextLine':
        current = current.move(cursors.Unit.LINE, Dir.FORWARD);
        break;
      case 'previousLine':
        current = current.move(cursors.Unit.LINE, Dir.BACKWARD);
        break;
      case 'nextButton':
        dir = Dir.FORWARD;
        pred = AutomationPredicate.button;
        predErrorMsg = 'no_next_button';
        break;
      case 'previousButton':
        dir = Dir.BACKWARD;
        pred = AutomationPredicate.button;
        predErrorMsg = 'no_previous_button';
        break;
      case 'nextCheckBox':
        dir = Dir.FORWARD;
        pred = AutomationPredicate.checkBox;
        predErrorMsg = 'no_next_checkbox';
        break;
      case 'previousCheckBox':
        dir = Dir.BACKWARD;
        pred = AutomationPredicate.checkBox;
        predErrorMsg = 'no_previous_checkbox';
        break;
      case 'nextComboBox':
        dir = Dir.FORWARD;
        pred = AutomationPredicate.comboBox;
        predErrorMsg = 'no_next_combo_box';
        break;
      case 'previousComboBox':
        dir = Dir.BACKWARD;
        pred = AutomationPredicate.comboBox;
        predErrorMsg = 'no_previous_combo_box';
        break;
      case 'nextEditText':
        dir = Dir.FORWARD;
        pred = AutomationPredicate.editText;
        predErrorMsg = 'no_next_edit_text';
        break;
      case 'previousEditText':
        dir = Dir.BACKWARD;
        pred = AutomationPredicate.editText;
        predErrorMsg = 'no_previous_edit_text';
        break;
      case 'nextFormField':
        dir = Dir.FORWARD;
        pred = AutomationPredicate.formField;
        predErrorMsg = 'no_next_form_field';
        break;
      case 'previousFormField':
        dir = Dir.BACKWARD;
        pred = AutomationPredicate.formField;
        predErrorMsg = 'no_previous_form_field';
        break;
      case 'nextHeading':
        dir = Dir.FORWARD;
        pred = AutomationPredicate.heading;
        predErrorMsg = 'no_next_heading';
        break;
      case 'previousHeading':
        dir = Dir.BACKWARD;
        pred = AutomationPredicate.heading;
        predErrorMsg = 'no_previous_heading';
        break;
      case 'nextLink':
        dir = Dir.FORWARD;
        pred = AutomationPredicate.link;
        predErrorMsg = 'no_next_link';
        break;
      case 'previousLink':
        dir = Dir.BACKWARD;
        pred = AutomationPredicate.link;
        predErrorMsg = 'no_previous_link';
        break;
      case 'nextTable':
        dir = Dir.FORWARD;
        pred = AutomationPredicate.table;
        predErrorMsg = 'no_next_table';
        break;
      case 'previousTable':
        dir = Dir.BACKWARD;
        pred = AutomationPredicate.table;
        predErrorMsg = 'no_previous_table';
        break;
      case 'nextVisitedLink':
        dir = Dir.FORWARD;
        pred = AutomationPredicate.visitedLink;
        predErrorMsg = 'no_next_visited_link';
        break;
      case 'previousVisitedLink':
        dir = Dir.BACKWARD;
        pred = AutomationPredicate.visitedLink;
        predErrorMsg = 'no_previous_visited_link';
        break;
      case 'nextElement':
        current = current.move(cursors.Unit.NODE, Dir.FORWARD);
        break;
      case 'previousElement':
        current = current.move(cursors.Unit.NODE, Dir.BACKWARD);
        break;
      case 'goToBeginning':
        var node =
            AutomationUtil.findNodePost(current.start.node.root,
                                        Dir.FORWARD,
                                        AutomationPredicate.leaf);
        if (node)
          current = cursors.Range.fromNode(node);
        break;
      case 'goToEnd':
        var node =
            AutomationUtil.findNodePost(current.start.node.root,
                                        Dir.BACKWARD,
                                        AutomationPredicate.leaf);
        if (node)
          current = cursors.Range.fromNode(node);
        break;
      case 'doDefault':
        if (this.currentRange_) {
          var actionNode = this.currentRange_.start.node;
          if (actionNode.role == RoleType.inlineTextBox)
            actionNode = actionNode.parent;
          actionNode.doDefault();
        }
        // Skip all other processing; if focus changes, we should get an event
        // for that.
        return;
      case 'continuousRead':
        global.isReadingContinuously = true;
        var continueReading = function(prevRange) {
          if (!global.isReadingContinuously || !this.currentRange_)
            return;

          new Output().withSpeechAndBraille(
                  this.currentRange_, prevRange, Output.EventType.NAVIGATE)
              .onSpeechEnd(function() { continueReading(prevRange); })
              .go();
          prevRange = this.currentRange_;
          this.currentRange_ =
              this.currentRange_.move(cursors.Unit.NODE, Dir.FORWARD);

          if (!this.currentRange_ || this.currentRange_.equals(prevRange))
            global.isReadingContinuously = false;
        }.bind(this);

        continueReading(null);
        return;
      case 'showContextMenu':
        if (this.currentRange_) {
          var actionNode = this.currentRange_.start.node;
          if (actionNode.role == RoleType.inlineTextBox)
            actionNode = actionNode.parent;
          actionNode.showContextMenu();
          return;
        }
        break;
      case 'showOptionsPage':
        var optionsPage = {url: 'chromevox/background/options.html'};
        chrome.tabs.create(optionsPage);
        break;
    }

    if (pred) {
      var node = AutomationUtil.findNextNode(
          current.getBound(dir).node, dir, pred);

      if (node) {
        current = cursors.Range.fromNode(node);
      } else {
        if (predErrorMsg) {
          cvox.ChromeVox.tts.speak(cvox.ChromeVox.msgs.getMsg(predErrorMsg),
                                   cvox.QueueMode.FLUSH);
        }
        return;
      }
    }

    if (current) {
      // TODO(dtseng): Figure out what it means to focus a range.
      var actionNode = current.start.node;
      if (actionNode.role == RoleType.inlineTextBox)
        actionNode = actionNode.parent;
      actionNode.focus();

      var prevRange = this.currentRange_;
      this.currentRange_ = current;

      new Output().withSpeechAndBraille(
              this.currentRange_, prevRange, Output.EventType.NAVIGATE)
          .go();
    }
  },

  /**
   * Handles a braille command.
   * @param {!cvox.BrailleKeyEvent} evt
   * @param {!cvox.NavBraille} content
   * @return {boolean} True if evt was processed.
   */
  onBrailleKeyEvent: function(evt, content) {
    if (this.mode_ === ChromeVoxMode.CLASSIC)
      return false;

    switch (evt.command) {
      case cvox.BrailleKeyCommand.PAN_LEFT:
        this.onGotCommand('previousElement', true);
        break;
      case cvox.BrailleKeyCommand.PAN_RIGHT:
        this.onGotCommand('nextElement', true);
        break;
      case cvox.BrailleKeyCommand.LINE_UP:
        this.onGotCommand('previousLine', true);
        break;
      case cvox.BrailleKeyCommand.LINE_DOWN:
        this.onGotCommand('nextLine', true);
        break;
      case cvox.BrailleKeyCommand.TOP:
        this.onGotCommand('goToBeginning', true);
        break;
      case cvox.BrailleKeyCommand.BOTTOM:
        this.onGotCommand('goToEnd', true);
        break;
      case cvox.BrailleKeyCommand.ROUTING:
        this.brailleRoutingCommand_(
            content.text,
            // Cast ok since displayPosition is always defined in this case.
            /** @type {number} */ (evt.displayPosition));
        break;
      default:
        return false;
    }
    return true;
  },

  /**
   * Provides all feedback once ChromeVox's focus changes.
   * @param {Object} evt
   */
  onEventDefault: function(evt) {
    var node = evt.target;

    if (!node)
      return;

    var prevRange = this.currentRange_;

    this.currentRange_ = cursors.Range.fromNode(node);

    // Check to see if we've crossed roots. Continue if we've crossed roots or
    // are not within web content.
    if (node.root.role == 'desktop' ||
        !prevRange ||
        prevRange.start.node.root != node.root)
      this.setupChromeVoxVariants_(node.root.docUrl || '');

    // Don't process nodes inside of web content if ChromeVox Next is inactive.
    if (node.root.role != RoleType.desktop &&
        this.mode_ === ChromeVoxMode.CLASSIC) {
      chrome.accessibilityPrivate.setFocusRing([]);
      return;
    }

    // Don't output if focused node hasn't changed.
    if (prevRange &&
        evt.type == 'focus' &&
        this.currentRange_.equals(prevRange))
      return;

    new Output().withSpeechAndBraille(
            this.currentRange_, prevRange, evt.type)
        .go();
  },

  /**
   * Provides all feedback once a focus event fires.
   * @param {Object} evt
   */
  onFocus: function(evt) {
    var node = evt.target;

    // It almost never makes sense to place focus directly on a rootWebArea.
    if (node.role == RoleType.rootWebArea) {
      // Try to find a focusable descendant.
      node = AutomationUtil.findNodePost(node,
                                         Dir.FORWARD,
                                         AutomationPredicate.focused) || node;

      // Fall back to the first leaf node in the document.
      if (node.role == RoleType.rootWebArea) {
        node = AutomationUtil.findNodePost(node,
                                           Dir.FORWARD,
                                           AutomationPredicate.leaf);
      }
    }
    this.onEventDefault({target: node, type: 'focus'});
  },

  /**
   * Provides all feedback once a load complete event fires.
   * @param {Object} evt
   */
  onLoadComplete: function(evt) {
    this.setupChromeVoxVariants_(evt.target.docUrl);

    // Don't process nodes inside of web content if ChromeVox Next is inactive.
    if (evt.target.root.role != RoleType.desktop &&
        this.mode_ === ChromeVoxMode.CLASSIC)
      return;

    // If initial focus was already placed on this page (e.g. if a user starts
    // tabbing before load complete), then don't move ChromeVox's position on
    // the page.
    if (this.currentRange_ &&
        this.currentRange_.start.node.role != RoleType.rootWebArea &&
        this.currentRange_.start.node.root.docUrl == evt.target.docUrl)
      return;

    var root = evt.target;
    var webView = root;
    while (webView && webView.role != RoleType.webView)
      webView = webView.parent;

    if (!webView || !webView.state.focused)
      return;

    var node = AutomationUtil.findNodePost(root,
        Dir.FORWARD,
        AutomationPredicate.leaf);

    if (node)
      this.currentRange_ = cursors.Range.fromNode(node);

    if (this.currentRange_)
      new Output().withSpeechAndBraille(
              this.currentRange_, null, evt.type)
          .go();
  },

  /**
   * Provides all feedback once a text selection change event fires.
   * @param {Object} evt
   */
  onTextOrTextSelectionChanged: function(evt) {
    // Don't process nodes inside of web content if ChromeVox Next is inactive.
    if (evt.target.root.role != RoleType.desktop &&
        this.mode_ === ChromeVoxMode.CLASSIC)
      return;

    if (!evt.target.state.focused)
      return;

    if (!this.currentRange_) {
      this.onEventDefault(evt);
      this.currentRange_ = cursors.Range.fromNode(evt.target);
    }

    var textChangeEvent = new cvox.TextChangeEvent(
        evt.target.value,
        evt.target.textSelStart,
        evt.target.textSelEnd,
        true);  // triggered by user
    if (!this.editableTextHandler ||
        evt.target != this.currentRange_.start.node) {
      this.editableTextHandler =
          new cvox.ChromeVoxEditableTextBase(
              textChangeEvent.value,
              textChangeEvent.start,
              textChangeEvent.end,
              evt.target.state['protected'],
              cvox.ChromeVox.tts);
    }

    this.editableTextHandler.changed(textChangeEvent);
    new Output().withBraille(
            this.currentRange_, null, evt.type)
        .go();
  },

  /**
   * Provides all feedback once a value changed event fires.
   * @param {Object} evt
   */
  onValueChanged: function(evt) {
    // Don't process nodes inside of web content if ChromeVox Next is inactive.
    if (evt.target.root.role != RoleType.desktop &&
        this.mode_ === ChromeVoxMode.CLASSIC)
      return;

    if (!evt.target.state.focused)
      return;

    // Value change events fire on web text fields and text areas when pressing
    // enter; suppress them.
    if (!this.currentRange_ ||
        evt.target.role != RoleType.textField) {
      this.onEventDefault(evt);
      this.currentRange_ = cursors.Range.fromNode(evt.target);
    }
  },

  /**
   * Called when the automation tree is changed.
   * @param {chrome.automation.TreeChange} treeChange
   */
  onTreeChange: function(treeChange) {
    var node = treeChange.target;
    if (!node.containerLiveStatus)
      return;

    if (node.containerLiveRelevant.indexOf('additions') >= 0 &&
        treeChange.type == 'nodeCreated')
      this.outputLiveRegionChange_(node, null);
    if (node.containerLiveRelevant.indexOf('text') >= 0 &&
        treeChange.type == 'nodeChanged')
      this.outputLiveRegionChange_(node, null);
    if (node.containerLiveRelevant.indexOf('removals') >= 0 &&
        treeChange.type == 'nodeRemoved')
      this.outputLiveRegionChange_(node, '@live_regions_removed');
  },

  /**
   * Given a node that needs to be spoken as part of a live region
   * change and an additional optional format string, output the
   * live region description.
   * @param {!chrome.automation.AutomationNode} node The changed node.
   * @param {?string} opt_prependFormatStr If set, a format string for
   *     cvox2.Output to prepend to the output.
   * @private
   */
  outputLiveRegionChange_: function(node, opt_prependFormatStr) {
    var range = cursors.Range.fromNode(node);
    var output = new Output();
    if (opt_prependFormatStr) {
      output.format(opt_prependFormatStr);
    }
    output.withSpeech(range, null, Output.EventType.NAVIGATE);
    output.go();
  },

  /**
   * Returns true if the url should have Classic running.
   * @return {boolean}
   * @private
   */
  shouldEnableClassicForUrl_: function(url) {
    return this.mode_ != ChromeVoxMode.FORCE_NEXT &&
        !this.isWhitelistedForCompat_(url) &&
        !this.isWhitelistedForNext_(url);
  },

  /**
   * @return {boolean}
   * @private
   */
  isWhitelistedForCompat_: function(url) {
    return url.indexOf('chrome://md-settings') != -1 ||
          url.indexOf('chrome://oobe/login') != -1 ||
          url.indexOf(
              'https://accounts.google.com/embedded/setup/chromeos') === 0 ||
          url === '';
  },

  /**
   * @private
   * @param {string} url
   * @return {boolean} Whether the given |url| is whitelisted.
   */
  isWhitelistedForNext_: function(url) {
    return this.whitelist_.some(function(item) {
      return url.indexOf(item) != -1;
    }.bind(this));
  },

  /**
   * Setup ChromeVox variants.
   * @param {string} url
   * @private
   */
  setupChromeVoxVariants_: function(url) {
    var mode = this.mode_;
    if (mode != ChromeVoxMode.FORCE_NEXT) {
      if (this.isWhitelistedForCompat_(url))
        mode = ChromeVoxMode.COMPAT;
      else if (this.isWhitelistedForNext_(url))
        mode = ChromeVoxMode.NEXT;
      else
        mode = ChromeVoxMode.CLASSIC;
    }

    this.setChromeVoxMode(mode);
  },

  /**
   * Disables classic ChromeVox in current web content.
   */
  disableClassicChromeVox_: function() {
    cvox.ExtensionBridge.send({
        message: 'SYSTEM_COMMAND',
        command: 'killChromeVox'
    });
  },

  /**
   * Sets the current ChromeVox mode.
   * @param {ChromeVoxMode} mode
   */
  setChromeVoxMode: function(mode) {
    if (mode === ChromeVoxMode.NEXT ||
        mode === ChromeVoxMode.COMPAT ||
        mode === ChromeVoxMode.FORCE_NEXT) {
      if (!chrome.commands.onCommand.hasListener(this.onGotCommand))
        chrome.commands.onCommand.addListener(this.onGotCommand);
    } else {
      if (chrome.commands.onCommand.hasListener(this.onGotCommand))
        chrome.commands.onCommand.removeListener(this.onGotCommand);
    }

    chrome.tabs.query({active: true}, function(tabs) {
      if (mode === ChromeVoxMode.CLASSIC) {
        // This case should do nothing because Classic gets injected by the
        // extension system via our manifest. Once ChromeVox Next is enabled
        // for tabs, re-enable.
        // cvox.ChromeVox.injectChromeVoxIntoTabs(tabs);
      } else {
        // When in compat mode, if the focus is within the desktop tree proper,
        // then do not disable content scripts.
        if (this.currentRange_.start.node.root.role == 'desktop')
          return;

        this.disableClassicChromeVox_();
      }
    }.bind(this));

    this.mode_ = mode;
  },

  /**
   * @param {!cvox.Spannable} text
   * @param {number} position
   * @private
   */
  brailleRoutingCommand_: function(text, position) {
    var actionNode = null;
    var selectionSpan = null;
    text.getSpans(position).forEach(function(span) {
      if (span instanceof Output.SelectionSpan) {
        selectionSpan = span;
      } else if (span instanceof Output.NodeSpan) {
        if (!actionNode ||
            (text.getSpanEnd(actionNode) - text.getSpanStart(actionNode) >
            text.getSpanEnd(span) - text.getSpanStart(span))) {
          actionNode = span.node;
        }
      }
    });
    if (!actionNode)
      return;
    if (actionNode.role === RoleType.inlineTextBox)
      actionNode = actionNode.parent;
    actionNode.doDefault();
    if (selectionSpan) {
      var start = text.getSpanStart(selectionSpan);
      actionNode.setSelection(position - start, position - start);
    }
  }
};

/** @type {Background} */
global.backgroundObj = new Background();

});  // goog.scope


text:
{% extends 'base.html' %}
{% block scripts %}
	{{ block.super}}
	<link rel="stylesheet" type="text/css" href="/static/css/site.css">
	<link rel="stylesheet" type="text/css" href="/static/css/SegDaInf.css">
	<title>Faculdade Lorenzinni - Segurança da Informação</title>
{% endblock %}
{% block conteudo %}

Segurança da informação

O Curso Superior de Tecnologia em Segurança da Informação da Lorenzinni tem o objetivo de capacitar o aluno a perceber, aprimorar e dinamizar os métodos de proteção aplicados sobre um conjunto de dados no sentido de preservar o valor que possui para um indivíduo ou uma organização, tendo como características básicas da segurança da informação os aspectos de confidencialidade, integridade e disponibilidade, não estando restritos somente a sistemas computacionais, informações eletrônicas ou sistemas de armazenamento. O conceito se aplica a todos os aspectos de proteção de informações e dados, acompanhando sempre o surgimento das inovações tecnológicas. Para tanto, o curso prepara o aluno por meio de tecnologias atuais, empregadas nesse exigente mercado de trabalho, e de professores altamente qualificados.

Este profissional é um especialista na segurança de redes de computadores. Ele evita que a rede seja invadida por pessoas não autorizadas, protegendo as informações dos usuários da empresa e seus clientes. Com isso, garante a confiabilidade, a integridade e a disponibilidade dos dados. Trabalha também na segurança de softwares e da própria infraestrutura de informática da companhia. Faz análises de risco, administra sistemas de informações e gerencia redes de computadores. Pode fazer auditorias e recuperar informações. O curso traz boa carga de disciplinas de administração, marketing e legislação, além de matemática. As matérias específicas incluem criptografa, segurança na internet e recuperação de dados. Muitas escolas exigem estágio e trabalho de conclusão de curso.

Duração média: 2 anos

			<button class="buttonDisc">Disciplinas</button>

{% endblock %}


text:
'use strict';

quail.inputWithoutLabelHasTitle = function (quail, test, Case) {

  test.get('$scope').each(function () {

    var testableElements = $(this).find('input, select, textarea');

    if (testableElements.length === 0) {
      var _case = Case({
        element: this,
        status: 'inapplicable'
      });
      test.add(_case);
      return;
    } else {
      testableElements.each(function () {
        var _case = Case({
          element: this
        });
        test.add(_case);

        if ($(this).css('display') === 'none') {
          _case.set({
            status: 'inapplicable'
          });
          return;
        }
        if (!test.get('$scope').find('label[for=' + $(this).attr('id') + ']').length && (!$(this).attr('title') || quail.isUnreadable($(this).attr('title')))) {
          _case.set({
            status: 'failed'
          });
        } else {
          _case.set({
            status: 'passed'
          });
        }
      });
    }
  });
};


text:
declare module 'native-base' {
  declare module.exports: any;
}


text:
package org.apache.fineract.integrationtests.loanaccount.guarantor;

import java.util.HashMap;
import java.util.List;

import org.apache.fineract.integrationtests.common.CommonConstants;
import org.apache.fineract.integrationtests.common.Utils;

import com.jayway.restassured.specification.RequestSpecification;
import com.jayway.restassured.specification.ResponseSpecification;

public class GuarantorHelper {

    private static final String LOAN_URL = "/fineract-provider/api/v1/loans/";
    private static final String GUARANTOR_API_URL = "/guarantors/";
    private static final String TENANT = "?" + Utils.TENANT_IDENTIFIER;
    private final RequestSpecification requestSpec;
    private final ResponseSpecification responseSpec;

    public GuarantorHelper(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) {
        this.requestSpec = requestSpec;
        this.responseSpec = responseSpec;
    }

    public Integer createGuarantor(final Integer loanId, final String guarantorJSON) {
        return Utils.performServerPost(this.requestSpec, this.responseSpec, LOAN_URL + loanId + GUARANTOR_API_URL + TENANT, guarantorJSON,
                CommonConstants.RESPONSE_RESOURCE_ID);
    }

    public HashMap updateGuarantor(final Integer guarantorId, final Integer loanId, final String guarantorJSON) {
        return Utils.performServerPut(this.requestSpec, this.responseSpec, LOAN_URL + loanId + GUARANTOR_API_URL + guarantorId + TENANT,
                guarantorJSON, CommonConstants.RESPONSE_CHANGES);
    }

    public HashMap deleteGuarantor(final Integer guarantorId, final Integer fundId, final Integer loanId) {
        return Utils.performServerDelete(this.requestSpec, this.responseSpec, LOAN_URL + loanId + GUARANTOR_API_URL + guarantorId + TENANT
                + "&guarantorFundingId=" + fundId, "");
    }

    public HashMap deleteGuarantor(final Integer guarantorId, final Integer loanId) {
        return Utils.performServerDelete(this.requestSpec, this.responseSpec, LOAN_URL + loanId + GUARANTOR_API_URL + guarantorId + TENANT,
                "");
    }

    public Object getGuarantor(final Integer guarantorId, final Integer loanId, final String jsonToGetBack) {
        return Utils.performServerGet(this.requestSpec, this.responseSpec, LOAN_URL + loanId + GUARANTOR_API_URL + guarantorId + TENANT,
                jsonToGetBack);
    }

    public List getAllGuarantor(final Integer loanId) {
        return Utils.performServerGet(this.requestSpec, this.responseSpec, LOAN_URL + loanId + GUARANTOR_API_URL + TENANT, "");
    }

}


text:
use core::{fmt, result};

pub struct Error {
    errno: isize,
}

pub type Result = result::Result<usize, Error>;

impl Error {
    pub fn new(errno: isize) -> Error {
        Error { errno: errno }
    }

    pub fn mux(result: Result) -> usize {
        match result {
            Ok(value) => value,
            Err(error) => -error.errno as usize,
        }
    }

    pub fn demux(value: usize) -> Result {
        let errno = -(value as isize);
        if errno >= 1 && errno < STR_ERROR.len() as isize {
            Err(Error::new(errno))
        } else {
            Ok(value)
        }
    }

    pub fn text(&self) -> &str {
        if let Some(description) = STR_ERROR.get(self.errno as usize) {
            description
        } else {
            "Unknown Error"
        }
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
        f.write_str(self.text())
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
        f.write_str(self.text())
    }
}

pub const EPERM: isize = 1;  /* Operation not permitted */
pub const ENOENT: isize = 2;  /* No such file or directory */
pub const ESRCH: isize = 3;  /* No such process */
pub const EINTR: isize = 4;  /* Interrupted system call */
pub const EIO: isize = 5;  /* I/O error */
pub const ENXIO: isize = 6;  /* No such device or address */
pub const E2BIG: isize = 7;  /* Argument list too long */
pub const ENOEXEC: isize = 8;  /* Exec format error */
pub const EBADF: isize = 9;  /* Bad file number */
pub const ECHILD: isize = 10;  /* No child processes */
pub const EAGAIN: isize = 11;  /* Try again */
pub const ENOMEM: isize = 12;  /* Out of memory */
pub const EACCES: isize = 13;  /* Permission denied */
pub const EFAULT: isize = 14;  /* Bad address */
pub const ENOTBLK: isize = 15;  /* Block device required */
pub const EBUSY: isize = 16;  /* Device or resource busy */
pub const EEXIST: isize = 17;  /* File exists */
pub const EXDEV: isize = 18;  /* Cross-device link */
pub const ENODEV: isize = 19;  /* No such device */
pub const ENOTDIR: isize = 20;  /* Not a directory */
pub const EISDIR: isize = 21;  /* Is a directory */
pub const EINVAL: isize = 22;  /* Invalid argument */
pub const ENFILE: isize = 23;  /* File table overflow */
pub const EMFILE: isize = 24;  /* Too many open files */
pub const ENOTTY: isize = 25;  /* Not a typewriter */
pub const ETXTBSY: isize = 26;  /* Text file busy */
pub const EFBIG: isize = 27;  /* File too large */
pub const ENOSPC: isize = 28;  /* No space left on device */
pub const ESPIPE: isize = 29;  /* Illegal seek */
pub const EROFS: isize = 30;  /* Read-only file system */
pub const EMLINK: isize = 31;  /* Too many links */
pub const EPIPE: isize = 32;  /* Broken pipe */
pub const EDOM: isize = 33;  /* Math argument out of domain of func */
pub const ERANGE: isize = 34;  /* Math result not representable */
pub const EDEADLK: isize = 35;  /* Resource deadlock would occur */
pub const ENAMETOOLONG: isize = 36;  /* File name too long */
pub const ENOLCK: isize = 37;  /* No record locks available */
pub const ENOSYS: isize = 38;  /* Function not implemented */
pub const ENOTEMPTY: isize = 39;  /* Directory not empty */
pub const ELOOP: isize = 40;  /* Too many symbolic links encountered */
pub const EWOULDBLOCK: isize = 41;  /* Operation would block */
pub const ENOMSG: isize = 42;  /* No message of desired type */
pub const EIDRM: isize = 43;  /* Identifier removed */
pub const ECHRNG: isize = 44;  /* Channel number out of range */
pub const EL2NSYNC: isize = 45;  /* Level 2 not synchronized */
pub const EL3HLT: isize = 46;  /* Level 3 halted */
pub const EL3RST: isize = 47;  /* Level 3 reset */
pub const ELNRNG: isize = 48;  /* Link number out of range */
pub const EUNATCH: isize = 49;  /* Protocol driver not attached */
pub const ENOCSI: isize = 50;  /* No CSI structure available */
pub const EL2HLT: isize = 51;  /* Level 2 halted */
pub const EBADE: isize = 52;  /* Invalid exchange */
pub const EBADR: isize = 53;  /* Invalid request descriptor */
pub const EXFULL: isize = 54;  /* Exchange full */
pub const ENOANO: isize = 55;  /* No anode */
pub const EBADRQC: isize = 56;  /* Invalid request code */
pub const EBADSLT: isize = 57;  /* Invalid slot */
pub const EDEADLOCK: isize = 58; /* Resource deadlock would occur */
pub const EBFONT: isize = 59;  /* Bad font file format */
pub const ENOSTR: isize = 60;  /* Device not a stream */
pub const ENODATA: isize = 61;  /* No data available */
pub const ETIME: isize = 62;  /* Timer expired */
pub const ENOSR: isize = 63;  /* Out of streams resources */
pub const ENONET: isize = 64;  /* Machine is not on the network */
pub const ENOPKG: isize = 65;  /* Package not installed */
pub const EREMOTE: isize = 66;  /* Object is remote */
pub const ENOLINK: isize = 67;  /* Link has been severed */
pub const EADV: isize = 68;  /* Advertise error */
pub const ESRMNT: isize = 69;  /* Srmount error */
pub const ECOMM: isize = 70;  /* Communication error on send */
pub const EPROTO: isize = 71;  /* Protocol error */
pub const EMULTIHOP: isize = 72;  /* Multihop attempted */
pub const EDOTDOT: isize = 73;  /* RFS specific error */
pub const EBADMSG: isize = 74;  /* Not a data message */
pub const EOVERFLOW: isize = 75;  /* Value too large for defined data type */
pub const ENOTUNIQ: isize = 76;  /* Name not unique on network */
pub const EBADFD: isize = 77;  /* File descriptor in bad state */
pub const EREMCHG: isize = 78;  /* Remote address changed */
pub const ELIBACC: isize = 79;  /* Can not access a needed shared library */
pub const ELIBBAD: isize = 80;  /* Accessing a corrupted shared library */
pub const ELIBSCN: isize = 81;  /* .lib section in a.out corrupted */
pub const ELIBMAX: isize = 82;  /* Attempting to link in too many shared libraries */
pub const ELIBEXEC: isize = 83;  /* Cannot exec a shared library directly */
pub const EILSEQ: isize = 84;  /* Illegal byte sequence */
pub const ERESTART: isize = 85;  /* Interrupted system call should be restarted */
pub const ESTRPIPE: isize = 86;  /* Streams pipe error */
pub const EUSERS: isize = 87;  /* Too many users */
pub const ENOTSOCK: isize = 88;  /* Socket operation on non-socket */
pub const EDESTADDRREQ: isize = 89;  /* Destination address required */
pub const EMSGSIZE: isize = 90;  /* Message too long */
pub const EPROTOTYPE: isize = 91;  /* Protocol wrong type for socket */
pub const ENOPROTOOPT: isize = 92;  /* Protocol not available */
pub const EPROTONOSUPPORT: isize = 93;  /* Protocol not supported */
pub const ESOCKTNOSUPPORT: isize = 94;  /* Socket type not supported */
pub const EOPNOTSUPP: isize = 95;  /* Operation not supported on transport endpoint */
pub const EPFNOSUPPORT: isize = 96;  /* Protocol family not supported */
pub const EAFNOSUPPORT: isize = 97;  /* Address family not supported by protocol */
pub const EADDRINUSE: isize = 98;  /* Address already in use */
pub const EADDRNOTAVAIL: isize = 99;  /* Cannot assign requested address */
pub const ENETDOWN: isize = 100; /* Network is down */
pub const ENETUNREACH: isize = 101; /* Network is unreachable */
pub const ENETRESET: isize = 102; /* Network dropped connection because of reset */
pub const ECONNABORTED: isize = 103; /* Software caused connection abort */
pub const ECONNRESET: isize = 104; /* Connection reset by peer */
pub const ENOBUFS: isize = 105; /* No buffer space available */
pub const EISCONN: isize = 106; /* Transport endpoint is already connected */
pub const ENOTCONN: isize = 107; /* Transport endpoint is not connected */
pub const ESHUTDOWN: isize = 108; /* Cannot send after transport endpoint shutdown */
pub const ETOOMANYREFS: isize = 109; /* Too many references: cannot splice */
pub const ETIMEDOUT: isize = 110; /* Connection timed out */
pub const ECONNREFUSED: isize = 111; /* Connection refused */
pub const EHOSTDOWN: isize = 112; /* Host is down */
pub const EHOSTUNREACH: isize = 113; /* No route to host */
pub const EALREADY: isize = 114; /* Operation already in progress */
pub const EINPROGRESS: isize = 115; /* Operation now in progress */
pub const ESTALE: isize = 116; /* Stale NFS file handle */
pub const EUCLEAN: isize = 117; /* Structure needs cleaning */
pub const ENOTNAM: isize = 118; /* Not a XENIX named type file */
pub const ENAVAIL: isize = 119; /* No XENIX semaphores available */
pub const EISNAM: isize = 120; /* Is a named type file */
pub const EREMOTEIO: isize = 121; /* Remote I/O error */
pub const EDQUOT: isize = 122; /* Quota exceeded */
pub const ENOMEDIUM: isize = 123; /* No medium found */
pub const EMEDIUMTYPE: isize = 124; /* Wrong medium type */
pub const ECANCELED: isize = 125; /* Operation Canceled */
pub const ENOKEY: isize = 126; /* Required key not available */
pub const EKEYEXPIRED: isize = 127; /* Key has expired */
pub const EKEYREVOKED: isize = 128; /* Key has been revoked */
pub const EKEYREJECTED: isize = 129; /* Key was rejected by service */
pub const EOWNERDEAD: isize = 130; /* Owner died */
pub const ENOTRECOVERABLE: isize = 131; /* State not recoverable */

pub static STR_ERROR: [&'static str; 132] = ["Success",
                                             "Operation not permitted",
                                             "No such file or directory",
                                             "No such process",
                                             "Interrupted system call",
                                             "I/O error",
                                             "No such device or address",
                                             "Argument list too long",
                                             "Exec format error",
                                             "Bad file number",
                                             "No child processes",
                                             "Try again",
                                             "Out of memory",
                                             "Permission denied",
                                             "Bad address",
                                             "Block device required",
                                             "Device or resource busy",
                                             "File exists",
                                             "Cross-device link",
                                             "No such device",
                                             "Not a directory",
                                             "Is a directory",
                                             "Invalid argument",
                                             "File table overflow",
                                             "Too many open files",
                                             "Not a typewriter",
                                             "Text file busy",
                                             "File too large",
                                             "No space left on device",
                                             "Illegal seek",
                                             "Read-only file system",
                                             "Too many links",
                                             "Broken pipe",
                                             "Math argument out of domain of func",
                                             "Math result not representable",
                                             "Resource deadlock would occur",
                                             "File name too long",
                                             "No record locks available",
                                             "Function not implemented",
                                             "Directory not empty",
                                             "Too many symbolic links encountered",
                                             "Operation would block",
                                             "No message of desired type",
                                             "Identifier removed",
                                             "Channel number out of range",
                                             "Level 2 not synchronized",
                                             "Level 3 halted",
                                             "Level 3 reset",
                                             "Link number out of range",
                                             "Protocol driver not attached",
                                             "No CSI structure available",
                                             "Level 2 halted",
                                             "Invalid exchange",
                                             "Invalid request descriptor",
                                             "Exchange full",
                                             "No anode",
                                             "Invalid request code",
                                             "Invalid slot",
                                             "Resource deadlock would occur",
                                             "Bad font file format",
                                             "Device not a stream",
                                             "No data available",
                                             "Timer expired",
                                             "Out of streams resources",
                                             "Machine is not on the network",
                                             "Package not installed",
                                             "Object is remote",
                                             "Link has been severed",
                                             "Advertise error",
                                             "Srmount error",
                                             "Communication error on send",
                                             "Protocol error",
                                             "Multihop attempted",
                                             "RFS specific error",
                                             "Not a data message",
                                             "Value too large for defined data type",
                                             "Name not unique on network",
                                             "File descriptor in bad state",
                                             "Remote address changed",
                                             "Can not access a needed shared library",
                                             "Accessing a corrupted shared library",
                                             ".lib section in a.out corrupted",
                                             "Attempting to link in too many shared libraries",
                                             "Cannot exec a shared library directly",
                                             "Illegal byte sequence",
                                             "Interrupted system call should be restarted",
                                             "Streams pipe error",
                                             "Too many users",
                                             "Socket operation on non-socket",
                                             "Destination address required",
                                             "Message too long",
                                             "Protocol wrong type for socket",
                                             "Protocol not available",
                                             "Protocol not supported",
                                             "Socket type not supported",
                                             "Operation not supported on transport endpoint",
                                             "Protocol family not supported",
                                             "Address family not supported by protocol",
                                             "Address already in use",
                                             "Cannot assign requested address",
                                             "Network is down",
                                             "Network is unreachable",
                                             "Network dropped connection because of reset",
                                             "Software caused connection abort",
                                             "Connection reset by peer",
                                             "No buffer space available",
                                             "Transport endpoint is already connected",
                                             "Transport endpoint is not connected",
                                             "Cannot send after transport endpoint shutdown",
                                             "Too many references: cannot splice",
                                             "Connection timed out",
                                             "Connection refused",
                                             "Host is down",
                                             "No route to host",
                                             "Operation already in progress",
                                             "Operation now in progress",
                                             "Stale NFS file handle",
                                             "Structure needs cleaning",
                                             "Not a XENIX named type file",
                                             "No XENIX semaphores available",
                                             "Is a named type file",
                                             "Remote I/O error",
                                             "Quota exceeded",
                                             "No medium found",
                                             "Wrong medium type",
                                             "Operation Canceled",
                                             "Required key not available",
                                             "Key has expired",
                                             "Key has been revoked",
                                             "Key was rejected by service",
                                             "Owner died",
                                             "State not recoverable"];


text:
ScoreText = function (game, x, y, text) {

	Phaser.Text.call(this, game, x, y, text || '0', { font: '18px Arial', fill: '#666666', align: 'left'});
	game.add.existing(this);

	var tween = null;
	var originalValue = 0;
	var tweenObject = { tweenAttribute:0 };

	this.setAnimatedText = function(newText){

		//cancel previous tween if exists
		if (tween && tween.isRunning)
			tween.stop(true);

		//assign new values
		originalValue = newText;
		tweenObject.tweenAttribute = isNaN(this.text) ? 0 : this.text;

		//tween if numeric value, else just set text
		if (!isNaN(originalValue)){
			tween = this.game.add
           				.tween(tweenObject)
           				.to( { tweenAttribute:newText }, 300, Phaser.Easing.Quadratic.Out, true)
           				.onUpdateCallback(this.updateTweenedText, this);
            tween.onComplete.addOnce(this.setOriginalValue, this);
      	}
      	else{
      		this.setText(originalValue);
      	}
	};

	this.updateTweenedText = function(){
		this.setText(Math.round(tweenObject.tweenAttribute));
	};

	this.setOriginalValue = function(){
		this.setText(originalValue);
	};
};

ScoreText.prototype = Object.create(Phaser.Text.prototype);
ScoreText.prototype.constructor = ScoreText;


text:
function f(x) {
  return [x][0];
};
%PrepareFunctionForOptimization(f);

// Test data element on prototype.
Object.prototype[0] = 23;
assertSame(1, f(1));
assertSame(2, f(2));
%OptimizeFunctionOnNextCall(f);
assertSame(3, f(3));
%DeoptimizeFunction(f);

// Test accessor element on prototype.
Object.prototype.__defineGetter__(0, function() { throw Error(); });
assertSame(4, f(4));
assertSame(5, f(5));
%PrepareFunctionForOptimization(f);
%OptimizeFunctionOnNextCall(f);
assertSame(6, f(6));
%DeoptimizeFunction(f);

// Test the same on boilerplate objects for object literals that contain
// both non-constant properties and non-constant elements.

function g(x, y) {
  var o = { foo:x, 0:y };
  return o.foo + o[0];
};
%PrepareFunctionForOptimization(g);

// Test data property and element on prototype.
Object.prototype[0] = 23;
Object.prototype.foo = 42;
assertSame(3, g(1, 2));
assertSame(5, g(2, 3));
%OptimizeFunctionOnNextCall(g);
assertSame(7, g(3, 4));
%DeoptimizeFunction(g);

// Test accessor property and element on prototype.
Object.prototype.__defineGetter__(0, function() { throw Error(); });
Object.prototype.__defineGetter__('foo', function() { throw Error(); });
assertSame(3, g(1, 2));
assertSame(5, g(2, 3));
%PrepareFunctionForOptimization(g);
%OptimizeFunctionOnNextCall(g);
assertSame(7, g(3, 4));
%DeoptimizeFunction(g);


text:
layout: post
title:  "First Look at AngularJS"
date:   2017-04-16 23:00:00 +0800
categories: blog
id: 30
---
*AngularJS* is by far the most popular JavaScript framework. Comparied with JavaScript libraries such as jQuery, JavaScript frameworks provide more functionalities, mainly design patterns, to web developers. By using JavaScript frameworks, developers can work with web apps, mobile apps, desktop apps, even server side code in a more maintainable way, especially for *SPAs(Single Page Applications)*.

*AngularJS* was developped in 2009 and strongly supported by Google. *Angular 2* was coming out in 2015 with almost completely new architectures and features. Starting from this post, I am writing a series of posts on *Angular 1* which is also often called *AngularJS* :link:[angularJS][angularJS].

*AngularJS* is based on the design pattern of *MVC* or *MVVM*. This concept was originally being used on the back-end by software developers. *MVC* is an abbreviation for *Model, View, Controller*. The basic idea is that *All the data should be going from Model through Controller to View and vice versa*. By following this pattern, the code is more readable and maintainable when web application is being large scaled.

The key features of *AngularJS* are:

* Two-way data binding:

Two-way data binding allows for automatic data update on both *Model* and *View* whenever there is a data change. In this way, traditional DOM manipulation of adding and removing is no longer necessary. All you need to do is updating the HTML template through *Controllers*.

{% highlight html %}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>angularjs</title>

This is angularjs two-way data binding

  <input type="text" ng-model="yourName">

    Hello  {{yourName}}

>
{% endhighlight %}

{% highlight javascript %}
angular.module("myApp", [])
       .controller("myCtrl", ['$scope', function($scope) {
          $scope.name = "Xiaoming";
       }]);
{% endhighlight %}
* Dependency injection:

Dependency injection is a way of injecting(providing) the dependencies(needed modules, normally JS files or functions) to the *modules*, *controllers* or *services* whenever required. It is a concept that is better understood by showing real code like follows:

{% highlight javascript %}
angular.module('myApp', ['ngRoute', 'ngAnimate']);
{% endhighlight %}

* Extending HTML vocabulary

*AngularJS* lets you write your own HTML tags which are called *Directives* in angular's words. In this way, you can extend the HTML vocabulary by inventing new HTML syntax thus build the *View* the way your want and reuse it whereever needed in your project.

You first need to define your own HTML tags in *Controller* like follows:

{% highlight javascript %}
app.directive('myTag', function(){
    return {
      restrict: 'E',
      template: '
This is my tag
'
    };
});
{% endhighlight %}

Then you can use your own HTML tags in *Views* like follows:

{% highlight html %}
<my-tag></my-tag>
{% endhighlight %}

The above three features are the main pros for *AnguarJS*. It is really worth trying if you haven't used it before.

[angularJS]:https://angularjs.org/


text:
namespace FlappyDon.Game
{
    internal enum GameState
    {
        Ready,
        Playing,
        GameOver
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center">

    <ImageButton
        android:id="@+id/actionbar.mapbutton"
        android:background="@drawable/selector_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_my_location_white_24dp"
        android:layout_marginStart="@dimen/actionbar_margin"
        android:layout_marginEnd="@dimen/actionbar_margin"/>

    <ImageView
        android:id="@+id/actionbar.profileimage"
        android:layout_width="@dimen/actionbar_size"
        android:layout_height="@dimen/actionbar_size"
        android:layout_marginStart="@dimen/actionbar_margin_profile"
        android:src="@drawable/logo_image"
        />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginStart="@dimen/actionbar_margin_profile">

        <TextView
            android:id="@+id/actionbar.profilename"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textStyle="bold"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:textSize="@dimen/actionbar_username_size"
            android:text="Hung Nguyen"/>

        <TextView
            android:layout_marginTop="@dimen/actionbar_margin"
            android:id="@+id/actionbar.nickname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/white"
            android:textSize="@dimen/actionbar_nickname_size"
            android:textAllCaps="false"
            android:text="Admin"/>
    </LinearLayout>

</LinearLayout>


text:
using System;
using System.Collections.Generic;
namespace ImpactMan.Core
{
    using System.Linq;
    using ImpactMan.Context.Db;
    using ImpactMan.Interfaces.Core;

    /// <summary>
    /// The DataLoader contains all the classes responsible for taking the data from the context
    /// </summary>
    class DataLoader:IDataLoader
    {
        private ImpactManContext context;
        public DataLoader(ImpactManContext context)
        {
            this.context = context;
        }
        public Dictionary<string, int> LoadHighScores()
        {

            Dictionary<string, int> topUsersDict = new Dictionary<string, int>();
            var topUsers = this.context.Users.ToList().OrderByDescending(u => u.HighScore).Take(10).ToList();
            if (topUsers.Count>0)
            {
                foreach (var user in topUsers)
                {
                    topUsersDict.Add(user.Name, user.HighScore);
                }
            }
            return topUsersDict;

        }

        public Dictionary<string, int> LoadLogInfo()
        {
            throw new NotImplementedException();
        }
    }
}


text:
<!DOCTYPE html>

		<title>FAQ</title>
		<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
		<link type="text/css" rel="stylesheet" href="../css/materialize.min.css"  media="screen,projection"/>
		<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

FAQ

Ringkasan

Riwayat

Lihat IRS

Jadwal Kelas

Pembayaran

Daftar Kontak

FAQ

				menu

								1. Apa saja jenis profile pengisian IRS ?

								Ada tiga jenis profile pengisian IRS, yaitu:

							    		Cara otomatis, dimana IRS akan langsung disimpan dan statusnya diset menjadi disetujui jika IRS tersebut tidak bermasalah. Dalam metode ini penasihat akademik tidak dilibatkan dalam proses persetujuan IRS.

							    		Cara semi otomatis, dimana IRS dapat langsung disimpan tanpa meminta persetujuan PA jika IRS tidak bermasalah. Jika IRS bermasalah atau mahasiswa/i ingin meminta pendapat dari PA maka IRS dapat diserahkan pada PA.

							    		Cara manual, dimana semua IRS harus disetujui oleh PA.

2. Bagaimana cara mengubah password?

								Pastikan masa berlaku password anda belum berakhir. Anda dapat melihatnya setiap kali masuk SIAKNG atau dengan memilih menu Home.
								Jika belum berakhir,

silahkan mengkases https://profile.ui.ac.id

Masukkan username dan password Anda yang sekarang

Di layar akan tampil halaman dengan menu Ganti Password di sebelah kiri.

Klik di menu tersebut

Anda akan diminta memasukkan password lama Anda, dan password yang Anda inginkan.

Password baru tidak boleh sama dengan password lama, harus terdiri atas angka dan huruf, dengan panjang minimal 6, maksimal 12 karakter.