text:
/**
 * @file org_graphlab_Core.hpp
 * \c javah will generate \c org_graphlab_Core.h from the native methods
 * defined in \c org.graphlab.Context (and so will overwrite the file every time).
 * Define any additional classes/structs/typedefs in this hpp file.
 * @author Jiunn Haur Lim <jiunnhal@cmu.edu>
 */

#ifndef ORG_GRAPHLAB_CORE_HPP
#define ORG_GRAPHLAB_CORE_HPP

#include <execinfo.h>
#include <graphlab.hpp>

#include "java_any.hpp"
#include "org_graphlab_Core.h"

namespace graphlab {

  /**
   * Wrapper for graphlab::core.
   * Contains the core, a reference to the Java core object (so that it
   * doesn't get garbage collected), and other utility functions for dealing
   * with the JVM.
   */
  template <typename Graph, typename UpdateFunctor>
  class jni_core : public java_any {

  public:

    /** ID of pointer to JNI environment in thread local store */
    static const size_t ENV_ID;

  private:

    typedef core<Graph, UpdateFunctor> core_type;

    /** graphlab::core object - the soul that this body wraps around */
    core_type *mcore;

    /** Java virtual machine reference - set only once for each process */
    static JavaVM *mjvm;

  public:

    /**
     * Creates a new graphlab core and a new reference to the associated
     * Java org.graphlab.Core object (so that it doesn't get garbage collected.)
     * @param[in] env   JNI environment, which will be used to create the
     *                  reference to the Java object.
     * @param[in] obj   associated org.graphlab.Core object.
     */
    jni_core (JNIEnv *env, jobject &obj) : java_any (env, obj) {
      this->mcore = new core_type();
    }

    /**
     * Gets the real graphlab core that this method wraps around
     * @return graphlab::core
     */
    core_type &operator()(){
      return *mcore;
    }

    /**
     * Deallocates the graphlab core. Parent constructor will delete jobject
     * reference.
     */
    ~jni_core(){
      delete mcore;
    }

    /**
     * Saves a reference to the Java Virtual Machine.
     * @param[in] jvm   pointer to the Java Virtual Machine
     */
    static void set_jvm (JavaVM *jvm){
      mjvm = jvm;
    }

    /**
     * Gets a reference to the Java Virtual Machine.
     * @return pointer to the Java Virtual Machine
     */
    static JavaVM *get_jvm (){
      return mjvm;
    }

    /**
     * Detaches the current thread from the JVM.
     * If a pointer to the JNI environment cannot be found in the thread-local
     * store, that means that this thread has already been detached, and the
     * function will return immediately. Otherwise, the thread is detached and
     * the pointer to the JNI environment is removed from the thread-local
     * store.
     */
    static void detach_from_jvm() {

      // if the current thread is still attached, detach it
      if (thread::contains(ENV_ID)) {
        int res = mjvm->DetachCurrentThread();
        assert(res >= 0);
        thread::get_local(ENV_ID) = NULL;
      }

    }

    static void dump_backtrace(int sig){

      void *array[10];
      size_t size;

      // get void*'s for all entries on the stack
      size = backtrace(array, 10);

      // print out all the frames to stderr
      backtrace_symbols_fd(array, size, 2);

    }

    /** Convenience method for throwing Java exceptions */
    static void throw_exception(JNIEnv* env,
                                const char *exception,
                                const char *message){
      jclass exc = env->FindClass(exception);
      if (NULL == exc) return;
      env->ThrowNew(exc, message);
    }

    /**
     * Retrieves the JNI environment for the current thread.
     * If a pointer to the JNI environment can be found in the thread-local
     * store, returns immediately; otherwise, that means that the current
     * thread has not been attached to the JVM yet. In that case, this
     * function will attach the current thread to the JVM and save the
     * associated JNI environment to the thread-local storage.
     * @return JNI environment associated with the current thread.
     */
    static JNIEnv *get_jni_env (){

      JNIEnv *jenv = NULL;

      // if current thread is not already on the JVM, attach it
      if (!thread::contains(ENV_ID)) {

        int res = mjvm->AttachCurrentThread((void **)&jenv, NULL);
        assert(res >= 0);

        // store JNI environment in thread-local storage
        thread::get_local(ENV_ID) = jenv;
        thread::set_thread_destroy_callback(detach_from_jvm);

      }

      // return the environment associated with the current thread
      return thread::get_local(ENV_ID).as<JNIEnv *>();

    }

  };

}

#endif


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Interface org.myrobotlab.service.interfaces.StepperControl</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.myrobotlab.service.interfaces.StepperControl

Packages that use StepperControl

Package
Description

org.myrobotlab.service

org.myrobotlab.service.interfaces

Uses of StepperControl in org.myrobotlab.service

Classes in org.myrobotlab.service that implement StepperControl

Modifier and Type
Class and Description

class
Stepper

Methods in org.myrobotlab.service with parameters of type StepperControl

Modifier and Type
Method and Description

boolean
Propeller.stepperAttach(StepperControl stepper)

boolean
Arduino2.stepperAttach(StepperControl stepper)

boolean
Arduino.stepperAttach(StepperControl stepper)

boolean
AdafruitMotorShield.stepperAttach(StepperControl stepperControl)

Uses of StepperControl in org.myrobotlab.service.interfaces

Methods in org.myrobotlab.service.interfaces with parameters of type StepperControl

Modifier and Type
Method and Description

boolean
StepperController.stepperAttach(StepperControl stepper)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

redpajama_set_name: RedPajamaGithub


text:
/** @module reiter/cycle */

import cycleN from "./cycleN";

/**
 * Cycles through `iterable` infinitely.
 *
 * @since 0.0.1
 * @generator
 * @function cycle
 * @param {ForOfIterable} iterable The iterable.
 * @yields {*} The next item in the infinite cycle of `iterable`.
 * @see [cycleN]{@link module:reiter/cycleN}
 * @example
 *
 * reiter.cycle([1, 2, 3])
 * // => 1, 2, 3, 1, 2, 3, ...
 */
export default cycleN(Infinity);


text:
This tool supports indexing and normalizing various columns in BigQuery tables.
It reads an input BigQuery SQL statement to select the columns and outputs a new
BigQuery table with the indexed columns.

# Running locally (development)

Build the runner container image with RDKit and Beam dependencies installed. Install the gcloud SDK and authenticate.

```
$ podman --cgroup-manager=cgroupfs build ./beam-rdkit-runner --format docker
...
STEP 14: COMMIT
--> 49b365fef6f
$ podman run -it --entrypoint "/bin/bash" -v .:/opt/bigquery-indexer 49b365fef6f
(beam-env) root@94bb44368d14$ wget https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-sdk-352.0.0-linux-x86_64.tar.gz
(beam-env) root@94bb44368d14$ tar -xzf google-cloud-sdk-352.0.0-linux-x86_64.tar.gz
(beam-env) root@94bb44368d14$ google-cloud-sdk/install.sh
(beam-env) root@94bb44368d14$ gcloud init
(beam-env) root@94bb44368d14$ gcloud auth application-default login
(beam-env) root@94bb44368d14$ cd /opt/bigquery-indexer && python3 -m main --input_sql "SELECT * FROM nih-nci-cbiit-chem-prod.savi.all LIMIT 100" --output_table <project>:savi.fingerprints --project <project> --temp_location gs://<cloud storage bucket>/tmp/ --skip_fingerprint_columns reaction_smiles
```

# Running in Dataflow on GCP

```
$ pip install 'apache-beam[gcp]=2.31.0'
```

See https://cloud.google.com/dataflow/docs/quickstarts/quickstart-python,
specifically setting GOOGLE_APPLICATION_CREDENTIALS is required.

Use your local GCP account credentials by executing:

```
$ gcloud init
$ gcloud auth application-default login
```

Build the runner container.

```
patents-public-data$ cd tools/bigquery-indexer/beam-rdkit-runner
beam-rdkit-runner$ gcloud builds submit --tag gcr.io/<project>/beam-rdkit-runner:latest
```

This example indexes a column containing SMILES (the computer representation of a chemical).

```$ python3 -m main --input_sql "SELECT * FROM nih-nci-cbiit-chem-prod.savi.all LIMIT 100" --output_table <project>:savi.fingerprints --project <project> --temp_location gs://<cloud storage bucket>/tmp/ --skip_fingerprint_columns reaction_smiles --runner DataflowRunner --max_num_workers=20 --region us-central1 --machine_type=n2-highcpu-16 --disk_size_gb=50 --experiment=use_runner_v2 --sdk_container_image=gcr.io/<project>/beam-rdkit-runner:latest --save_main_session```

See more configuration flags at https://cloud.google.com/dataflow/docs/guides/flexrs and regions at https://cloud.google.com/dataflow/docs/resources/locations.


text:
define([
    'Underscore',
    'jquery',
    'ui/Mask',
    'util/Event',
    'util/ViewportRelative',
    'text!resources/menu.tpl'
], function (_, $, Mask, Event, ViewportRelative, menuTpl) {
    'use strict';

    var menuTplFunc = _.template(menuTpl);

    var PopupMenu = function (menuDef, callback, stateFunc, isMultiSelect) {
        this.menuDef = menuDef;
        this.callback = callback;
        this.stateFunc = stateFunc;
        this.isMultiSelect = isMultiSelect;
        this.state = [];
    };

    PopupMenu.prototype.MENU_ITEM_SELECTOR = '.qk_popup_menu_item';
    PopupMenu.prototype.HIDDEN_CSS = 'qk_invisible';

    PopupMenu.prototype.updateUiState = function (markup, state) {
        if (state) {
            markup.find('.qk_popup_menu_item[data-value="' + state + '"] .qk_popup_menu_item_state').toggleClass(this.HIDDEN_CSS);
        }
    };

    PopupMenu.prototype.updateState = function (state, newValue) {
        var index = state.indexOf(newValue),
            result = {};
        if (index >= 0) {
            state.splice(index, 1);
            result.deselected = newValue;
        } else {
            if (this.isMultiSelect) {
                state.push(newValue);
            } else {
                result.deselected = state[0];
                state[0] = newValue;
            }
            result.selected = newValue;
        }
        return result;
    };

    PopupMenu.prototype.onSelect = function (event) {
        var menuItem = $(event.target).closest(this.MENU_ITEM_SELECTOR),
            id = menuItem.attr('data-value'),
            selectedDef = _.find(this.menuDef, function (def) {
                return def.value === id;
            }),
            newValue = selectedDef.value,
            delta = {};
        event.preventDefault(); // stops the menu being focused
        if (newValue !== 'close') {
            delta = this.updateState(this.state, newValue);
            this.updateUiState(this.menu, delta.selected);
            this.updateUiState(this.menu, delta.deselected);
        }
        this.callback(delta.selected, delta.deselected, this.state, this.menuDef);
        if (!this.isMultiSelect || newValue === 'close') {
            this.hide();
        }
    };

    PopupMenu.prototype.applyState = function (markup, menuState) {
        var HIDDEN_CSS = this.HIDDEN_CSS;
        markup.find('.qk_popup_menu_item').each(function () {
            var itemEl = $(this),
                stateEl = itemEl.find('.qk_popup_menu_item_state'),
                id = itemEl.attr('data-value'),
                func = menuState.indexOf(id) >= 0 ? stateEl.removeClass : stateEl.addClass;
            func.call(stateEl, HIDDEN_CSS);
        });
    };

    PopupMenu.prototype.createMenu = function (def) {
        var markup = $(menuTplFunc({options: def}));
        markup.on(Event.eventName('start'), this.MENU_ITEM_SELECTOR, this.onSelect.bind(this));
        markup.find('.qk_popup_menu_item_state').addClass(this.HIDDEN_CSS);
        return markup;
    };

    PopupMenu.prototype.doShowMenu = function (menu, x, y) {
        var vpRight = document.documentElement.clientWidth || window.innerWidth || 0,
            vpBottom = document.documentElement.clientHeight || window.height || 0,
            hScroll = document.documentElement.scrollLeft || document.body.scrollLeft || 0,
            vScroll = document.documentElement.scrollTop || document.body.scrollTop || 0;
        menu.css({
            top: -500,
            left: -500
        });
        menu.removeClass('qk_hidden'); // so that the menu has a width
        if (x + menu.outerWidth() > vpRight + hScroll) {
            x -= menu.outerWidth();
        }
        if (y + menu.outerHeight() > vpBottom + vScroll) {
            y -= menu.outerHeight();
        }
        menu.css({
            top: y,
            left: x
        });
        this.vpMenu.adjust();
    };

    PopupMenu.prototype.show = function (x, y) {
        var menu = this.menu;
        if (!menu) {
            this.menu = this.createMenu(this.menuDef);
            menu = this.menu;
            this.mask = Mask.create(this.hide.bind(this), 0);
            menu.appendTo('body');
            this.vpMenu = ViewportRelative.create(menu, {
                top: y
            });
        }
        this.state = (this.stateFunc && this.stateFunc(this.menuDef)) || this.state;
        this.applyState(menu, this.state);
        this.mask.show();
        this.doShowMenu(menu, x, y);
    };

    PopupMenu.prototype.hide = function () {
        this.menu.addClass('qk_hidden');
        this.mask.hide();
        this.state = [];
    };

    PopupMenu.prototype.destroy = function () {
        this.menu.remove();
    };

    function create(menuDef, callback, stateFunc, isMultiSelect) {
        return new PopupMenu(menuDef, callback, stateFunc, isMultiSelect);
    }

    return {
        create: create
    };
});


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityStandardAssets.ImageEffects;

public class SlideScene : MonoBehaviour {

    h4g2.GameState.SceneDef def;
    GameObject canvas;

	// Use this for initialization
	void Start () {

       /* var b = Camera.main.GetComponent<Blackout>();
        var bl = Camera.main.GetComponent<Blur>();
        b.enabled = false;
        b.rampOffset = 0;
        bl.enabled = false;
        bl.Iterations = 0;
        bl.BlurSpread = 0;*/

        this.def = h4g2.GameState.S.nextScene ();

        this.canvas = GameObject.Find ("Canvas");

        GameObject.Find ("title").GetComponent<Text> ().text = def.title;
        GameObject.Find ("subtitle").GetComponent<Text> ().text = def.subtitle;

        fade_in ();
	}

    private float msg_time = 1.5f;
    private float time_since_last_msg = 0;
    int times = 0;
    void Update () {
        time_since_last_msg += Time.deltaTime;
        if (time_since_last_msg > msg_time) {
            time_since_last_msg = 0;
            if (times==1) {
                fade_out ();
            } else if (times == 2) {
                loadnext ();
            }
            times++;
        }
    }

    public void loadnext(){
        SceneManager.LoadScene (def.next_scene);
    }

    public void fade_in(){
        Graphic[] graphics = canvas.GetComponentsInChildren<Graphic>();

        for (int i = 0; i < graphics.Length; ++i)
        {
            graphics[i].CrossFadeAlpha(0f, 0f, false);
            graphics[i].CrossFadeAlpha(1f, 1.5f, false);
        }
    }

    public void fade_out(){
        Graphic[] graphics = canvas.GetComponentsInChildren<Graphic>();

        for (int i = 0; i < graphics.Length; ++i)
        {
            graphics[i].CrossFadeAlpha(0f, 1.5f, false);
        }
    }
}


text:
namespace raytracer {

struct CheckerboardSampler : public Sampler {

    CheckerboardSampler(float check_size, glm::vec3 color1, glm::vec3 color2)
        : check_size(check_size), color1(color1), color2(color2) {}

    glm::vec3 get_color(float u, float v) const override;

    float check_size;
    glm::vec3 color1, color2;
};
}


text:
import paper from 'paper'

export default {
  setTask: (state, task) => {
    state.task = task
  },

  activateSnackbar: (state, payload) => {
    state.snackbar.active = true
    state.snackbar.text = payload.text ? payload.text : 'notification'
    state.snackbar.color = payload.color ? payload.color : 'info'
    state.snackbar.timeout = payload.timeout ? payload.timeout : 4000
  },

  dismissSnackbar: state => {
    state.snackbar.active = false
  },

  // Add a handler function that will run when osd-viewport is updated.
  // This will synchronously update the paperJS viewport.
  // This is an expensive operation as it ensures all parameters are in sync
  // on every viewport update. For example, zoom may not have changed but it
  // would still fire this event and update the zoom. However, separating into
  // the individual parts led to a far less smooth experience. Leave it here
  // for now at least.
  synchroniseAnnotationAndOSDCanvas: (state, viewer) => {
    const strokeScale = state.strokeScale

    viewer.addHandler('update-viewport', function (e) {
      // Sync Zoom
      const viewportZoom = viewer.viewport.getZoom(true)
      const image1 = viewer.world.getItemAt(0)
      paper.view.zoom = image1.viewportToImageZoom(viewportZoom)

      // Sync Center
      const center = image1.viewportToImageCoordinates(
        viewer.viewport.getCenter(true)
      )
      paper.view.center = new paper.Point(center.x, center.y)

      // Update paths to have strokeWidth reactive to zoom level.
      // TODO: consider the computational expensive of this and find a more
      // effectively method of handling it.
      paper.project.getItems({
        class: paper.Path
      }).map(path => {
        path.strokeWidth = (image1.getContentSize().x * strokeScale) / (viewportZoom * 1000)
      })
    })

    viewer.addHandler('resize', function (e) {
      const image1 = viewer.world.getItemAt(0)

      // Sync Size
      paper.view.viewSize.width = e.newContainerSize.x
      paper.view.viewSize.height = e.newContainerSize.y

      // Sync Center
      const center = image1.viewportToImageCoordinates(
        viewer.viewport.getCenter(true)
      )
      paper.view.center = new paper.Point(center.x, center.y)
    })
  },

  setActiveStep: (state, stepIndex) => {
    state.activeStep = stepIndex
  },

  setActiveLayer: (state, layerIndex) => {
    state.activeLayer = layerIndex
  },

  toggleSettings: state => {
    state.settingsFlag = !state.settingsFlag
  },

  setActiveValidationIndex: (state, payload) => {
    state.activeValidationIndex = payload
  },

  setSteps: state => {
    state.toolsDrawer = false
    state.studioDrawer = false
    if (state.task === 'review') {
      state.steps = [{
        id: 1,
        instruction: 'Review the data',
        type: 'review'
      }]
    } else if (state.task === 'validate') {
      state.steps = [{
        id: 1,
        instruction: 'Cycle through each of the predicted Megakaryocyte classifications and verify whether the prediction is correct or incorrect. In cases where you are not certain, flag the prediction for review.',
        type: 'validate'
      }]
    } else {
      state.toolsDrawer = true
      state.studioDrawer = true
      state.steps = null
    }
  },

  toggleToolsDrawer: state => {
    state.toolsDrawer = !state.toolsDrawer
  },

  toggleStudioDrawer: state => {
    state.studioDrawer = !state.studioDrawer
  },

  setToolsDrawerState: (state, payload) => {
    state.toolsDrawer = payload
  },

  setStudioDrawerState: (state, payload) => {
    state.studioDrawer = payload
  }
}


text:
- list item 1
- list item 2
    + list item
    + another list item
    + another.


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CodeCracker.CSharp.Style
{
    [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(RemoveTrailingWhitespaceCodeFixProvider)), Shared]
    public class RemoveTrailingWhitespaceCodeFixProvider : CodeFixProvider
    {
        public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(DiagnosticId.RemoveTrailingWhitespace.ToDiagnosticId());

        public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;

        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
            var diagnostic = context.Diagnostics.First();
            var trivia = root.FindTrivia(diagnostic.Location.SourceSpan.End - 1);
            var newRoot = RemoveTrailingWhiteSpace(root, trivia);
            context.RegisterCodeFix(CodeAction.Create("Remove trailing whitespace", ct => Task.FromResult(context.Document.WithSyntaxRoot(newRoot))), diagnostic);
        }

        private static SyntaxNode RemoveTrailingWhiteSpace(SyntaxNode root, SyntaxTrivia trivia)
        {
            SyntaxNode newRoot;
            if (trivia.IsKind(SyntaxKind.WhitespaceTrivia))
            {
                newRoot = root.ReplaceTrivia(trivia, new SyntaxTrivia[] { });
            }
            else if (trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia, SyntaxKind.MultiLineDocumentationCommentTrivia))
            {
                var commentText = trivia.ToFullString();
                var commentLines = commentText.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
                var newComment = "";
                var builder = new System.Text.StringBuilder();
                builder.Append(newComment);
                for (int i = 0; i < commentLines.Length; i++)
                {
                    var commentLine = commentLines[i];
                    builder.Append(Regex.Replace(commentLine, @"\s+$", ""));
                    if (i < commentLines.Length - 1) builder.Append(Environment.NewLine);
                }
                newComment = builder.ToString();
                newRoot = root.ReplaceTrivia(trivia, SyntaxFactory.SyntaxTrivia(SyntaxKind.DocumentationCommentExteriorTrivia, newComment));
            }
            else
            {
                var triviaNoTrailingWhiteSpace = Regex.Replace(trivia.ToFullString(), @"\s+$", "");
                newRoot = root.ReplaceTrivia(trivia, SyntaxFactory.ParseTrailingTrivia(triviaNoTrailingWhiteSpace));
            }
            return newRoot;
        }
    }
}


text:
import org.jetbrains.annotations.NotNull;

import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;

public class Main {

  public void test(Optional<String> opt, Function<String, @NotNull Object> onPresent, Supplier<Object> onEmpty) {
    Object o = opt.i<caret>sPresent() ? onPresent.apply(opt.get()) : onEmpty.get();
  }
}


text:
"oi câmara"
===========

Desenvolvido no [**1º Hackathon da Câmara Federal**](http://www2.camara.leg.br/responsabilidade-social/edulegislativa/hackathon/hackathon-maratona-hacker) em 29/10/2013

Baixe o aplicativo: [https://chrome.google.com/webstore/detail/oi-câmara/fmmbgnkciddfgghniaonobpdfgipdejb](http://bit.ly/17wgBmn)

![screenshot](https://raw.github.com/luisleao/oicamara/master/docs/screen_0.png)

#Descrição do aplicativo
Este aplicativo é uma **plataforma interativa focada em acessibilidade** das informações baseadas em dados abertos, a ser a utilizado por pessoas com visão comprometida.

Entendemos que o formato e a **forma de acesso aos dados abertos representa a vontade política** de incluir a participação cidadã do processo legislativo. Mais do que nunca, pensar em acessibilidade e nas diversas possibilidades de tornar as informações acessíveis e compreensíveis para a população deve fazer parte dessa vontade.

Com este aplicativo quero demostrar como fazer isso, utilizando as tecnologias de **reconhecimento de fala** para que qualquer pessoa possa saber informações da Câmara Federal.

Além disso, este aplicativo pode ser remixado com poucas alterações e para utilizar outras informações.

Você pode utilizá-lo de duas formas:
- como uma instalação interativa, focada em acessibilidade
- como um aplicativo interativo

Este é um aplicativo Chrome (Chrome Packaged App)!
Para distribuí-lo, publique o código fonte (pasta webapp compactada) na [Chrome Web Store](https://chrome.google.com/webstore/developer/dashboard). Você também pode adicionar manualmente o através do link "chrome://extensions", desde que o "modo de desenvolvedor" esteja ativo.

Como foi desenvolvivo?
----------------------

A **API de reconhecimento de voz** (*Web Speech API*), [documentada no w3c](https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html) foi implementada no navegador Google Chrome (a partir da versão 25) e disponibilizada ao público no início de 2013. Ela representa uma mudança no modelo de uso do reconhecimento de voz em sites web, permitindo o uso totalmente através de javascript, sem vínculo com a interface. Assim, novas possibilidades surgiram, como demonstrado nesse aplicativo.

Para exemplos de uso dessa API acesse http://updates.html5rocks.com/2013/01/Voice-Driven-Web-Apps-Introduction-to-the-Web-Speech-API

Desde então, tenho estudado formas de uso dessa API, integrando inclusive com **automação residencial** (apresentação "oi casa" realizada no Meetup de Front-End dia 26/08/2013 do [Google Developers Group, capítulo São Paulo](https://developers.google.com/groups/chapter/102774871279745079139/), na qual sou um dos coordenadores).

O código do "oi casa" pode ser acessado em https://github.com/luisleao/oicasa

##O que mudou?
A principal diferença do "oi casa" para o "oi câmara" é a forma como foi implementada a lista de comandos, agora baseada em expressões regulares e com uma função de *callback*, que é acionada quando uma das funções valida a transcrição encontrada. Ele permite também criar comandos hierárquicos (por exemplo: pedir confirmações ou informações complementares). Além disso, não há necessidade de falar o comando de ativação "oi câmara" para executar os comandos raiz (ele funciona como um comando de ajuda e quando acionado indica que o usuário deve falar um dos comandos previstos), mas lembre-se de que é importante criar um comando com mais de uma palavra para que não ocorra reconhecimentos indevidos.

Outra diferença importante é que o sistema agora ignora as transcrição enquanto estiver falando algum texto. Isso significa que o próprio sistema não vai se retroalimentar e gerar falsos comandos.

##Os dados da Câmara Federal
Nesse primeiro momento utilizamos os [dados da Câmara Federal](http://www2.camara.leg.br/transparencia/dados-abertos) para essa instalação.
Ele consulta, na versão beta, a **pauta do plenário**, a **presença dos parlamentares** em uma determinada data, além de **curiosidades sobre a casa**.

Acreditamos que mais informações podem ser adicionadas, relacionadas ao processo legislativo e cotas parlamentares, mas isso significará

Ainda tenho previsto a implementação da tramitação por dia, além da consulta do regimento interno.

##Dificuldades no desenvolvimento
Principalmente sobre o entendimento dos dados da Câmara Federal e na tradução desses dados "técnicos" para uma linguagem mais informal.

Encontrei algumas inconsistências, como por exemplo o formato de identificação de propostas no webservice: algumas chamadas separam a identificação das propostas (tipo, número e ano) e outros deixam o dado unificado (TIPO-NUMERO/ANO). Senti falta de alguns agrupamentos e filtros nas consultas no que se refere a tramitação e as consultas de presença poderiam permitir listar modelos mais simples.

Sobre o desenvolvimento, o reconhecimento de voz não é 100% preciso e isso dificulta na identificação dos comandos e passagens de parâmetros em comandos. Nesse caso, o uso das expressões regulares ajuda a minimizar essa questão.

Com relação a equipe, recebi ajuda de algumas pessoas, como a Lívia Ascava, que ajudou com os textos e as "curiosidades" da Câmara e o Pedro Markun, sempre solícito a gerar um ruído de fundo para testar a aplicação.

Quero remixar este aplicativo e utilizar outros dados
-----------------------------------------------------

Baixe este repositório e altera os arquivos "main.js". Nele você pode editar a variável "comandos", ela é um dicionário e cada chave segue o modelo abaixo.

```javascript
{
	"nome": "NOME DO COMANDO A SER EXECUTADO",
	"alias": [/oi câmara/g, new RegExp("artigo\\s([\\d]**)º?\\sdo\\sregimento")], //expressões regulares
	"action": function(texto, tag, regex_result) {

		//texto = texto encontrado
		//tag = expressão regular que validou o texto
		//regex_result = último valor da matrix de resultado da expressão regular (se tiver usado grupos)

		//... insira aqui seu código de retorno

	}
}
```

Crie quantos itens desejar e não esqueça de incluí-los na função "inicia_comandos". Ela funciona como a raiz de comandos da sua aplicação e contém as principais palavras-chave que serão acionadas ao receber as transcrições da API de reconhecimento de voz.

Se quiser que seja falado algum texto utilize uma das funções conforme a seguir:

```javascript
falar(TEXTO, callback); //para texto simples - até 100 caracteres.
falar_mais(ARRAY_DE_STRINGS, callback); //textos longos.

divide_texto_em_100(TEXTO_LONGO); //retorna um array com as palavras separadas em grupos de até 100 caracteres
plural_ou_nenhum(NUMERO, STRING_SINGULAR, STRING_PLURAL, STRING_ZERO) //para escrever textos com variação de número
```

Para retomar o reconhecimento de voz, utilize os comandos abaixo
```javascript
inicia_comandos(); //para reativar a lista de comandos disponíveis
comando_on(); //ativa a repeção imediata de comandos, tocando um aviso sonoro e indicar para o usuário que ele deve falar um comando IMEDIATAMENTE
comando_off(); //desativa a recepção de comandos

```

##Dicas de acessibilidade
- lembre-se de adicionar a mensagem final "Diga, oi câmara, para ouvir as opções possíveis.". Ela indica que o comando foi finalizado e que ele está no início do programa e pode solicitar um novo comando.
- ao criar comandos com hierarquia, sempre que possível indique a informação do passo anterior. Para que ele lembre o que falou e complemente a informação necessária para o comando.
- não crie níveis muito completos!

#tecnologias utilizadas
- webspeech API: padrão aberto para implementação de reconhecimento de voz, documentado no w3c
- chrome packaged app: para criação de um aplicativo web, com funcionalidades de aplicativo nativo
- google translate TTS: (API não documentada)

[Wheelchair User](http://thenounproject.com/noun/wheelchair-user/#icon-No21977) designed by [NATAPON CHANTABUTR](http://thenounproject.com/pique) from The Noun Project.

LICENSE
=======

Copyright 2013 Luis Leao All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

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


text:
require('../../lib/projections')
	.aggregate({
		stream: 'Quest',
		$init: function(){
			return {
				active: true,
				traveled: 0,
				location: null,
				members: []
			}
		},

		QuestStarted: function(state, evt){
			state.active = true;
			state.location = evt.location;
			state.members = evt.members.slice(0);

			state.members.sort();
		},

		FoeDispatched: function(state, evt){
			// just need another event
		},

		TownReached: function(state, evt){
			state.location = evt.location;
			state.traveled += evt.traveled;
		},

		EndOfDay: function(state, evt){
			state.traveled += evt.traveled;
		},

		QuestEnded: function(state, evt){
			state.active = false;
			state.location = evt.location;
		},

		MembersJoined: function(state, evt){
			state.members = state.members.concat(evt.members);
			state.members.sort();
		},

		MembersDeparted: function(state, evt){
			state.location = evt.location;

			for (var i = 0; i < evt.members.length; i++){
				var index = state.members.indexOf(evt.members[i]);
				state.members.splice(index, 1);
			}

			state.members.sort();
		}

	});


text:
from webob.exc import HTTPBadRequest
from webob.exc import HTTPForbidden
from webob.exc import HTTPConflict
from webob.exc import HTTPNotFound

from webob import Response
import eventlet

from volt.common import policy
from volt.common import exception
from volt import executor
from volt.common import wsgi
from volt.openstack.common import log as logging
from volt.openstack.common.gettextutils import _
from volt.openstack.common import jsonutils

SUPPORTED_PARAMS = ('host', 'port', 'iqn', 'lun', 'peer_id')

LOG = logging.getLogger(__name__)

class Controller(object):
    """
    WSGI controller for tracked volumes information in Volt v1 API

    The tracked volumes API is a RESTful web service for volume
    metadata. The API is as follows::

        GET /volumes -- Returns a set of brief metadata about volumes
        HEAD /volumes/<ID> -- Returns detailed metadata about volumes
                            with id <ID>
        GET /volumes/<ID> -- Search volumes metadata about volumes
                             matching the id <ID>. Because the client
                             uses this result to build the iscsi
                             connections, in order to promote overall
                             r/w performance and limit the number of
                             connections, executor always returns
                             partial matching list.
        POST /volumes/<ID> -- Register a new volume and store metadata
                             with id <ID>
        DELETE /volumes/<ID> -- Delete all tracked volume with id <ID>
        DELETE /volumes -- Delete all tracked volumes
    """

    def __init__(self):
        self.policy = policy.Enforcer()
        self.pool = eventlet.GreenPool(size=1024)
        self.executor = executor.get_default_executor()
#         self.pool.spawn_n(self.executor.kickoff_dead_node())
        self.scanning_thread = executor.ScanningThread(self.executor)

    def _enforce(self, req, action):
        """Authorize an action against our policies"""
        try:
            self.policy.enforce(req.context, action, {})
        except exception.Forbidden:
            raise HTTPForbidden()

    def _get_query_params(self, req):
        """
        Extracts necessary query params from request.

        :param req: the WSGI Request object
        :retval dict of parameters that can be used by registry client
        """
        params = {}
        for PARAM in SUPPORTED_PARAMS:
            if req and PARAM in req:
                params[PARAM] = req.get(PARAM)

        return params

    def index(self, req, volume_id=None):
        """
        Returns the following information for all tracked volumes:

            * id -- The opaque volume identifier
            * count -- The number of registered volumes with this id

        :param req: The WSGI/Webob Request object
        :retval The response body is a mapping of the following form::

            {'volumes': [
                {'id': <ID>,
                 'count': <COUNT>}, ...
            ]}
        """
        #self._enforce(req, 'get_volumes')

        try:
            if volume_id is None:
                volumes = self.executor.get_volumes_list()
            else:
                volumes = self.executor.get_volumes_detail(volume_id)
        except exception.Invalid as e:
            raise HTTPBadRequest(explanation="%s" % e)

        return volumes

    def remove(self, req, volume_id, peer_id=None, body=None):
        """
        Remove the volume metadata from Volt

        :param req: The WSGI/Webob Request object
        :param volume_id: The volume identifier of the volume.
        :param peer_id: The opaque volume identifier allocated by
                        volt

        :raises HttpNotFound if volume is not available
        """
        #self._enforce(req, 'remove_volume')
        params = self._get_query_params(body)
        assert(peer_id is not None)
        try:
            self.executor.delete_volume_metadata(volume_id, peer_id, **params)
        except exception.NotFound as e:
            msg = _("Failed to find volume to delete: %(e)s") % {'e': e}
            for line in msg.split('\n'):
                LOG.info(line)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        else:
            return Response(body='', status=200)

    def register(self, req, volume_id, peer_id, body=None):
        """
        Adds the volume metadata to the registry and assigns
        an volume identifier if one is not supplied in the request
        headers.

        :param req: The WSGI/Webob Request object
        :param volume_meta: The volume metadata

        :raises HTTPConflict if volume already exists
        :raises HTTPBadRequest if volume metadata is not valid
        """
        #self._enforce(req, 'register_volume')
        params = self._get_query_params(body)
        #if self.scanning_thread.status == 'init':
        #    self.scanning_thread.start()
        #    self.scanning_thread.status = 'running'
        try:
            volume_meta = self.executor.add_volume_metadata(volume_id,
                                                            peer_id, **params)
        except exception.DuplicateItem:
            msg = (_("An volume with identifier %s already exists") %
                   volume_id)
            LOG.debug(msg)
            raise HTTPConflict(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Invalid as e:
            msg = _("Failed to register volume. Got error: %(e)s") % {'e': e}
            for line in msg.split('\n'):
                LOG.debug(line)
            raise HTTPBadRequest(explanation=msg,
                                 request=req,
                                 content_type="text/plain")
        except exception.NotFound as e:
            msg = _("Failed to register volume. Got error: %(e)s") % {'e': e}
            for line in msg.split('\n'):
                LOG.debug(line)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")

        return volume_meta

    def query(self, req, volume_id, body=None):
        """
        Returns detailed information for all available volumes with id
        <volume_id>

        :param req: The WSGI/Webob Request object
        :param id: The volume id of the query
        :retval The response body is a mapping of the following form::

            {'volumes': [
                {'host': <HOST>,
                 'ip': <IP>,
                 'iqn': <IQN>,
                 'lun': <LUN>}, ...
            ]}

        """
        #self._enforce(req, 'get_volumes')
        params = self._get_query_params(body)
        #host = params.get('host', None)
        host = req.environ['REMOTE_ADDR']
        peer_id = params.get('peer_id', None)
        if self.scanning_thread.status == 'init':
            self.scanning_thread.start()
            self.scanning_thread.status = 'running'
        try:
            target = self.executor.get_volume_parents(volume_id=volume_id,
                                                      peer_id=peer_id,
                                                      host=host)
        except exception.NotFound as e:
            msg = _("this volume is not found in tracker.")
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.InvalidParameterValue:
            raise HTTPBadRequest()
        except exception.Duplicate:
            raise HTTPConflict()

        return target

def create_resource():
    """Volumes resource factory method"""
    return wsgi.Resource(Controller())


text:
'use strict';

/**
 * SKU details
 *
 */
class Sku {
  /**
   * Create a Sku.
   * @member {string} name SKU name to specify whether the key vault is a
   * standard vault or a premium vault. Possible values include: 'standard',
   * 'premium'
   */
  constructor() {
  }

  /**
   * Defines the metadata of Sku
   *
   * @returns {object} metadata of Sku
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'Sku',
      type: {
        name: 'Composite',
        className: 'Sku',
        modelProperties: {
          family: {
            required: true,
            isConstant: true,
            serializedName: 'family',
            defaultValue: 'A',
            type: {
              name: 'String'
            }
          },
          name: {
            required: true,
            serializedName: 'name',
            type: {
              name: 'Enum',
              allowedValues: [ 'standard', 'premium' ]
            }
          }
        }
      }
    };
  }
}

module.exports = Sku;


text:
/// <reference path="../../scripts/typings/angularjs/angular.d.ts" />
/// <reference path="controllers/maincontroller.ts" />
/// <reference path="services/configuploadservice.ts" />
/// <reference path="directives/filemodeldirective.ts" />

module ThirstModule {
    angular.module("ThirstModule", [])
        .controller("MainController", MainController)
        .service("configUploadService", ConfigUploadService)
        .directive("fileModel", FileModelDirective.factory());
}