text:
namespace blink {
class WebMediaConstraints;
}

namespace content {

// RTCMediaConstraints acts as a glue layer between WebKits MediaConstraints and
// libjingle webrtc::MediaConstraintsInterface.
// Constraints are used by PeerConnection and getUserMedia API calls.
class CONTENT_EXPORT RTCMediaConstraints
    : public NON_EXPORTED_BASE(webrtc::MediaConstraintsInterface) {
 public:
  RTCMediaConstraints();
  explicit RTCMediaConstraints(
      const blink::WebMediaConstraints& constraints);
  virtual ~RTCMediaConstraints();
  virtual const Constraints& GetMandatory() const OVERRIDE;
  virtual const Constraints& GetOptional() const OVERRIDE;
  // Adds a mandatory constraint, optionally overriding an existing one.
  // If the constraint is already set and |override_if_exists| is false,
  // the function will return false, otherwise true.
  bool AddMandatory(const std::string& key, const std::string& value,
                    bool override_if_exists);
  // As above, but against the optional constraints.
  bool AddOptional(const std::string& key, const std::string& value,
                   bool override_if_exists);

 protected:
  bool AddConstraint(Constraints* constraints,
                     const std::string& key,
                     const std::string& value,
                     bool override_if_exists);
  Constraints mandatory_;
  Constraints optional_;
};

}  // namespace content

#endif  // CONTENT_RENDERER_MEDIA_RTC_MEDIA_CONSTRAINTS_H_


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.apache.hadoop.conf (Apache Hadoop Common 2.3.0 API)
</TITLE>

<META NAME="date" CONTENT="2015-03-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

org.apache.hadoop.conf

Interfaces

Configurable

Reconfigurable

Classes

Configuration

Configuration.DeprecationDelta

Configuration.IntegerRanges

Configured

ReconfigurableBase

ReconfigurationServlet

ReconfigurationUtil

ReconfigurationUtil.PropertyChange

Exceptions

ConfServlet.BadFormatException

ReconfigurationException

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var grunt = require('grunt');

exports.protractor_cucumber_html_report = {
  setUp: function(done) {
    // setup here if necessary
    done();
  },
  default_options: function(test) {
    test.expect(1);
    var actual = grunt.file.read('tmp/report.html');
    var expected = grunt.file.read('test/expected/default_options');
    test.equal(actual, expected, 'should describe what the default behavior is.');
    test.done();
  }
};


text:
package com.corosus.game.ai.btree;

import com.badlogic.gdx.ai.btree.LeafTask;
import com.badlogic.gdx.ai.btree.Task;
import com.corosus.game.Logger;
import com.corosus.game.ai.Blackboard;

public class RandomTest extends LeafTask<Blackboard> {

	private float randChance = 0.2F;
	private String debug = "";

	public RandomTest() {

	}

	public RandomTest setDebug(String debug) {
		this.debug = debug;
		return this;
	}

	@Override
	public void run() {
		if (Math.random() < randChance) {
			Logger.dbg("hit success chance, dbg: " + debug);
			success();
		} else {
			Logger.dbg("still executing RandomChance, dbg: " + debug);
		}

	}

	@Override
	protected Task<Blackboard> copyTo(Task<Blackboard> task) {
		RandomTest test = (RandomTest) task;
		test.randChance = randChance;
		return task;
	}

}


text:
from django.contrib.auth.models import AnonymousUser
from django.template import Context, Template
from django.test import TestCase
from django.test.client import RequestFactory
from django.urls import reverse

from wagtail.models import PAGE_TEMPLATE_VAR, Page
from wagtail.test.testapp.models import BusinessChild, BusinessIndex
from wagtail.test.utils import WagtailTestUtils

class TestUserbarTag(TestCase, WagtailTestUtils):
    def setUp(self):
        self.user = self.create_superuser(
            username="test", email="test@email.com", password="password"
        )
        self.homepage = Page.objects.get(id=2)

    def dummy_request(
        self, user=None, *, is_preview=False, in_preview_panel=False, revision_id=None
    ):
        request = RequestFactory().get("/")
        request.user = user or AnonymousUser()
        request.is_preview = is_preview
        request.in_preview_panel = in_preview_panel
        if revision_id:
            request.revision_id = revision_id
        return request

    def test_userbar_tag(self):
        template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
        context = Context(
            {
                PAGE_TEMPLATE_VAR: self.homepage,
                "request": self.dummy_request(self.user),
            }
        )
        with self.assertNumQueries(5):
            content = template.render(context)

        self.assertIn("", content)

    def test_userbar_tag_revision(self):
        self.homepage.save_revision(user=self.user, submitted_for_moderation=True)
        revision = self.homepage.get_latest_revision()
        template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
        context = Context(
            {
                PAGE_TEMPLATE_VAR: self.homepage,
                "request": self.dummy_request(self.user, revision_id=revision.id),
            }
        )
        with self.assertNumQueries(7):
            content = template.render(context)

        self.assertIn("", content)
        self.assertIn("Approve", content)

    def test_userbar_does_not_break_without_request(self):
        template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}boom")
        content = template.render(Context({}))

        self.assertEqual("boom", content)

    def test_userbar_tag_self(self):
        """
        Ensure the userbar renders with `self` instead of `PAGE_TEMPLATE_VAR`
        """
        template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
        content = template.render(
            Context(
                {
                    "self": self.homepage,
                    "request": self.dummy_request(self.user),
                }
            )
        )

        self.assertIn("", content)

    def test_userbar_tag_anonymous_user(self):
        template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
        content = template.render(
            Context(
                {
                    PAGE_TEMPLATE_VAR: self.homepage,
                    "request": self.dummy_request(),
                }
            )
        )

        # Make sure nothing was rendered
        self.assertEqual(content, "")

    def test_userbar_tag_no_page(self):
        template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
        content = template.render(
            Context(
                {
                    "request": self.dummy_request(self.user),
                }
            )
        )

        self.assertIn("", content)

    def test_edit_link(self):
        template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
        content = template.render(
            Context(
                {
                    PAGE_TEMPLATE_VAR: self.homepage,
                    "request": self.dummy_request(self.user, is_preview=False),
                }
            )
        )
        self.assertIn("", content)
        self.assertIn("Edit this page", content)

    def test_userbar_edit_menu_not_in_preview(self):
        template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
        content = template.render(
            Context(
                {
                    PAGE_TEMPLATE_VAR: self.homepage,
                    "request": self.dummy_request(self.user, is_preview=True),
                }
            )
        )
        self.assertIn("", content)
        self.assertNotIn("Edit this page", content)

    def test_userbar_not_in_preview_panel(self):
        template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
        content = template.render(
            Context(
                {
                    PAGE_TEMPLATE_VAR: self.homepage,
                    "request": self.dummy_request(
                        self.user, is_preview=True, in_preview_panel=True
                    ),
                }
            )
        )

        # Make sure nothing was rendered
        self.assertEqual(content, "")

class TestUserbarFrontend(TestCase, WagtailTestUtils):
    def setUp(self):
        self.login()
        self.homepage = Page.objects.get(id=2)

    def test_userbar_frontend(self):
        response = self.client.get(
            reverse("wagtailadmin_userbar_frontend", args=(self.homepage.id,))
        )

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "wagtailadmin/userbar/base.html")

    def test_userbar_frontend_anonymous_user_cannot_see(self):
        # Logout
        self.client.logout()

        response = self.client.get(
            reverse("wagtailadmin_userbar_frontend", args=(self.homepage.id,))
        )

        # Check that the user received a forbidden message
        self.assertEqual(response.status_code, 403)

class TestUserbarAddLink(TestCase, WagtailTestUtils):
    fixtures = ["test.json"]

    def setUp(self):
        self.login()
        self.homepage = Page.objects.get(url_path="/home/")
        self.event_index = Page.objects.get(url_path="/home/events/")

        self.business_index = BusinessIndex(title="Business", live=True)
        self.homepage.add_child(instance=self.business_index)

        self.business_child = BusinessChild(title="Business Child", live=True)
        self.business_index.add_child(instance=self.business_child)

    def test_page_allowing_subpages(self):
        response = self.client.get(
            reverse("wagtailadmin_userbar_frontend", args=(self.event_index.id,))
        )

        # page allows subpages, so the 'add page' button should show
        expected_url = reverse(
            "wagtailadmin_pages:add_subpage", args=(self.event_index.id,)
        )
        needle = f"""

                <svg class="icon icon-plus wagtail-action-icon" aria-hidden="true">
                    <use href="#icon-plus"></use>
                </svg>
                Add a child page

            """
        self.assertTagInHTML(needle, str(response.content))

    def test_page_disallowing_subpages(self):
        response = self.client.get(
            reverse("wagtailadmin_userbar_frontend", args=(self.business_child.id,))
        )

        # page disallows subpages, so the 'add page' button shouldn't show
        expected_url = reverse(
            "wagtailadmin_pages:add_subpage", args=(self.business_index.id,)
        )
        expected_link = (
            'Add a child page' % expected_url
        )
        self.assertNotContains(response, expected_link)

class TestUserbarModeration(TestCase, WagtailTestUtils):
    def setUp(self):
        self.login()
        self.homepage = Page.objects.get(id=2)
        self.homepage.save_revision(submitted_for_moderation=True)
        self.revision = self.homepage.get_latest_revision()

    def test_userbar_moderation(self):
        response = self.client.get(
            reverse("wagtailadmin_userbar_moderation", args=(self.revision.id,))
        )

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "wagtailadmin/userbar/base.html")

        expected_approve_html = """
            <form action="/admin/pages/moderation/{}/approve/" target="_parent" method="post">
                <input type="hidden" name="csrfmiddlewaretoken">

                    <input type="submit" value="Approve" class="button" />

            </form>
        """.format(
            self.revision.id
        )
        self.assertTagInHTML(expected_approve_html, str(response.content))

        expected_reject_html = """
            <form action="/admin/pages/moderation/{}/reject/" target="_parent" method="post">
                <input type="hidden" name="csrfmiddlewaretoken">

                    <input type="submit" value="Reject" class="button" />

            </form>
        """.format(
            self.revision.id
        )
        self.assertTagInHTML(expected_reject_html, str(response.content))

    def test_userbar_moderation_anonymous_user_cannot_see(self):
        # Logout
        self.client.logout()

        response = self.client.get(
            reverse("wagtailadmin_userbar_moderation", args=(self.revision.id,))
        )

        # Check that the user received a forbidden message
        self.assertEqual(response.status_code, 403)


text:
import os

from setuptools import setup, find_packages

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name='ant',
    version='develop',
    url='http://www.github.com/mvillalba/python-ant',
    license='MIT',
    description='Python implementation of the ANT, ANT+, and ANT-FS ' \
                'protocols (http://www.thisisant.com/).',
    author=u'Mart\u00EDn Ra\u00FAl Villalba',
    author_email='martin@martinvillalba.com',
    long_description=read('README.md'),
    classifiers=[
        "Development Status :: 2 - Pre-Alpha",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2.6",
        "Programming Language :: Python :: 2.7",
        "Topic :: Communications",
        "Topic :: Communications :: File Sharing",
        "Topic :: Software Development :: Libraries :: Python Modules",
    ],
    packages=find_packages('src'),
    package_dir={'': 'src'},
    install_requires=[
        'distribute',
        'pyserial',
        'pyusb',
        'msgpack-python'
    ],
)


text:
var util = require('util');
var PassThrough = require('stream').PassThrough;

/*
Combine multiple streams into one pipeline

Example:

  var stream3 = new StreamCombiner(stream1, stream2);
  process.stdin.pipe(stream3).pipe(process.stdout);

  OR

  var stream3 = new StreamCombiner([stream1, stream2]);
  process.stdin.pipe(stream3).pipe(process.stdout);
*/
var StreamCombiner = function() {
  if (arguments.length === 1 && util.isArray(arguments[0])) {
    this.streams = Array.prototype.slice.apply(arguments[0]);
  } else {
    this.streams = Array.prototype.slice.apply(arguments);
  }

  this.on('pipe', function(source) {
    source.unpipe(this);
    this.streams.forEach(function(stream) {
      source = source.pipe(stream);
    });
    this.transformStream = source;
  });
};

util.inherits(StreamCombiner, PassThrough);

StreamCombiner.prototype.pipe = function(dest, options) {
  return this.transformStream.pipe(dest, options);
};

module.exports = function () {
  var args = Array.prototype.slice.call(arguments, 0);
  return new StreamCombiner(args);
};


text:
    #define BLUETOOTH_SUPPORT

    #define BLUETOOTH_ENABLE_SUPPORT

    #define BLUETOOTH_ENABLE_PIN_POLARITY 1 // drive high == power on
    #define BLUETOOTH_ENABLE_PORT 0
    #define BLUETOOTH_ENABLE_PIN 17

#elif defined(CROSSCHASM_C5_BT)

    #define BLUETOOTH_SUPPORT

    #define BLUETOOTH_ENABLE_SUPPORT
    // no other PIC32 boards supported right now have an enable pin for
    // Bluetooth - using the Sparkfun BlueSMiRF module, you can't control the
    // status via GPIO.

    #define BLUETOOTH_ENABLE_PIN_POLARITY 1
    #define BLUETOOTH_ENABLE_PORT 0
    #define BLUETOOTH_ENABLE_PIN 32 // PORTE BIT5 (RE5)

#elif defined(CROSSCHASM_C5_CELLULAR)

#elif defined(CHIPKIT)

    #define BLUETOOTH_SUPPORT

#endif


text:
package net.ros.common.network;

import com.elytradev.concrete.network.Message;
import com.elytradev.concrete.network.NetworkContext;
import com.elytradev.concrete.network.annotation.field.MarshalledAs;
import com.elytradev.concrete.network.annotation.type.ReceivedOn;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.relauncher.Side;
import net.ros.common.ROSConstants;
import net.ros.common.network.action.ActionManager;

import java.util.concurrent.atomic.AtomicInteger;

@ReceivedOn(Side.CLIENT)
public class ClientActionHolderPacket extends Message
{
    public static AtomicInteger previousActionID;

    private NBTTagCompound actionPayload;

    @MarshalledAs("short")
    private int replyID;

    public ClientActionHolderPacket(NetworkContext ctx)
    {
        super(ctx);
    }

    public ClientActionHolderPacket(int replyID, NBTTagCompound payload)
    {
        this(ROSConstants.network);

        this.actionPayload = payload;
        this.replyID = replyID;
    }

    @Override
    protected void handle(EntityPlayer receiver)
    {
        ActionManager.getInstance().triggerCallback(replyID, actionPayload);
    }
}


text:
package cherry.admin.secure.userman;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mobile.device.site.SitePreference;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;

import cherry.admin.PathDef;
import cherry.common.db.gen.dto.User;
import cherry.foundation.bizdtm.BizDateTime;
import cherry.foundation.download.DownloadAction;
import cherry.foundation.download.DownloadOperation;
import cherry.goods.paginate.PagedList;

@Controller
public class UsermanSearchControllerImpl implements UsermanSearchController {

	@Value("${admin.app.userman.search.pageSize}")
	private int defaultPageSize;

	@Value("${admin.app.userman.export.contentType}")
	private String contentType;

	@Value("${admin.app.userman.export.filename}")
	private String filename;

	@Autowired
	private UsermanSearchService usermanSearchService;

	@Autowired
	private BizDateTime bizDateTime;

	@Autowired
	private DownloadOperation downloadOperation;

	private Charset charset = StandardCharsets.UTF_8;

	@Override
	public UsermanSearchForm getForm() {
		return new UsermanSearchForm();
	}

	@Override
	public ModelAndView init(Authentication auth, Locale locale, SitePreference sitePref, HttpServletRequest request) {
		ModelAndView mav = new ModelAndView(PathDef.VIEW_USERMAN_SEARCH_INIT);
		return mav;
	}

	@Override
	public ModelAndView execute(UsermanSearchForm form, BindingResult binding, Authentication auth, Locale locale,
			SitePreference sitePref, HttpServletRequest request) {

		if (binding.hasErrors()) {
			ModelAndView mav = new ModelAndView(PathDef.VIEW_USERMAN_SEARCH_INIT);
			return mav;
		}

		if (form.getPsz() <= 0) {
			form.setPsz(defaultPageSize);
		}

		PagedList<User> result = usermanSearchService.searchUsers(form, form.getPno(), form.getPsz());

		ModelAndView mav = new ModelAndView(PathDef.VIEW_USERMAN_SEARCH_INIT);
		mav.addObject(result);
		return mav;
	}

	@Override
	public ModelAndView download(final UsermanSearchForm form, BindingResult binding, Authentication auth,
			Locale locale, SitePreference sitePref, HttpServletRequest request, HttpServletResponse response) {

		if (binding.hasErrors()) {
			ModelAndView mav = new ModelAndView(PathDef.VIEW_USERMAN_SEARCH_INIT);
			return mav;
		}

		DownloadAction action = new DownloadAction() {
			@Override
			public long doDownload(OutputStream stream) throws IOException {
				try (Writer writer = new OutputStreamWriter(stream, charset)) {
					return usermanSearchService.exportUsers(writer, form);
				}
			}
		};
		downloadOperation.download(response, contentType, charset, filename, bizDateTime.now(), action);

		return null;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;

namespace Store.Services.Models
{
    [DataContract]
    public class MonsterModel
    {
        [DataMember(Name = "id")]
        public int MonsterId { get; set; }

        [DataMember(Name = "name")]
        public string Name { get; set; }

        [DataMember(Name = "meleAttack")]
        public int MeleAttack { get; set; }

        [DataMember(Name = "magicAttack")]
        public int MagicAttack { get; set; }

        [DataMember(Name = "magicDefense")]
        public int MagicDefense { get; set; }

        [DataMember(Name = "meleDefense")]
        public int MeleDefense { get; set; }

        [DataMember(Name = "hp")]
        public int HP { get; set; }

        [DataMember(Name = "mp")]
        public int MP { get; set; }
    }

    [DataContract]
    public class CreatedMonsterModel
    {
        [DataMember(Name = "id")]
        public int Monsterid { get; set; }

        [DataMember(Name = "name")]
        public string Name { get; set; }
    }
}


text: int cmd_mesh_adv(const struct shell *sh, size_t argc, char *argv[]);


text:
export default function createCustom (name, data, eventProps) {
  function CustomEvent (event, params) {
    var evt = document.createEvent('CustomEvent')
    evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail)
    return evt
  }
  CustomEvent.prototype = window.Event.prototype
  data = data || {}
  eventProps = eventProps || {}
  var UseEvent = typeof window.CustomEvent === 'function' ? window.CustomEvent : CustomEvent
  var params = {
    detail: data,
    bubbles: typeof eventProps.bubbles === 'boolean' ? eventProps.bubbles : true,
    cancelable: typeof eventProps.cancelable === 'boolean' ? eventProps.cancelable : true
  }
  return new UseEvent(name, params)
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="icon" href="/assets/images/favicon.png">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Rubik:400,400i,500,500i,700,700i" rel="stylesheet">
<link href="/assets/css/theme.css" rel="stylesheet">
<link href="/assets/css/custom.css" rel="stylesheet">

<meta name="description" content="Most of the times I don't know how to pray...">

  <meta property="og:site_name" content="Fellipe Brito">

  <meta property="og:title" content="Never Enough">
  <meta property="og:type" content="article">
  <meta property="og:description" content="Most of the times I don't know how to pray..."/>

  <meta property="og:image" content="http://fellipebrito.com/assets/images/img/showman.jpg" />
  <meta property="article:published_time" content="2018-05-07T00:00:00-05:00">
  <meta property="article:author" content="http://fellipebrito.com/about/">

  <meta property="og:url" content="http://fellipebrito.com/never-enough/" />

  <meta itemprop="keywords" content="culture,movies" />

  <meta property="article:tag" content="culture">

  <meta property="article:tag" content="movies">

    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsWow" aria-controls="navbarsWow" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Fellipe Brito | Crer também é pensar

                Home

                    Sobre

Fellipe Brito

             Fellipe Brito | Crer também é pensar

Conecte-se!

Newsletter

<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">

<form action="https://fellipebrito.us19.list-manage.com/subscribe/post?u=0794ba995c37a5e8a28edf28d&id=8bb58341f2" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

      <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="seuemail@gmail.com" required>

<input type="text" name="b_0794ba995c37a5e8a28edf28d_8bb58341f2" tabindex="-1" value="">

<input type="submit" value="Confirmar!" name="subscribe" id="mc-embedded-subscribe" class="button">

</form>

                         culture

                         movies

Never Enough

Most of the times I don't know how to pray.

How would a mere man like me choose the right words to address the Creator of the Universe?

Despite my limitation to do so, the Christian #FAITH is that, in knowing that we could never build ourselves to His level, God himself chose to be like us.

For thousands of years, The Torah and the Prophets spoke about the day it would happen. The Day when YWHW would break out the limits of the Tabernacle and fill the earth as water fills the ocean.

John believed that Jesus was God moving at our pace so we could walk with Him and see Him face to face.

John, a Jew poet, would use all the beauty of the ancient Hebrew culture blended with Greek reason to say that "The Word became flesh and made his dwelling among us, and we have seen his glory";

Today, he could say: "God became flesh and blood, and moved into the neighborhood. We saw His glory with our own eyes."

Jesus' core message is that the Glory seen by John and his contemporaneous was just a glimpse of the future when Heaven and Earth would finally be one again. Thus, he taught us to pray: for "The Kingdom to Come"

I find myself going back to the Lord's prayer every other day. I pray it slowly; I breathe each of those sentences; I cry out my heart and my despair, calm in the morning or intense at night. And then, sometimes, when I am fortunate, it happens…

For a flash of time, without my outlining, with no model or plan, I can taste it. He listens to me, and if I may dare… He answers me back.

I can't describe it. It goes way beyond my comprehension and my reasoning.  There is no other experience like that, and I can't share that with you, even if I used all my vocabulary.

In times like that music saves me.
Through music, I may join the prayer of someone else so we can pray together;
Music communicates feelings;
Music makes it possible for me to pray in movement.

Today I prayed this song; I wept this song; I danced this song; I bowed down during the song; I found the words and the rhythm to explain the lament of my heart.

If you, like me, can't find the right words to pray or find yourself unworthy of addressing the Almighty, close your eyes and join me and all those that for two thousand years have been praying for his Kingdom to Come.

And if you want to sing it, you may read John's words, be amazed about everything he saw and testified to us, then, turn your radio on and sing:

I'm trying to hold my breath

Let it stay this way

Can't let this moment end

You set off a dream with me

Getting louder now

Can you hear it echoing?

Take my hand

Will you share this with me?

'Cause darling without you

All the shine of a thousand spotlights

All the stars we steal from the night sky

Will never be enough

Towers of gold are still too little

These hands could hold the world but it'll

Never be enough

For me

                <time class="post-date" datetime="2018-05-07">07 May 2018</time>

                    « Eu não sou de direita

                    Por que eu devo ler Marcos? »

    Please enable JavaScript to view the comments powered by Disqus.
    comments powered by Disqus

                Copyright © 2018 Fellipe Brito.

                "Affiliates Theme" - Design & Code by WowThemes.net


text:
<!--
It has a schema, where one field has indexed, searchable = false
and 2nd field has indexed, refining = false;
-->

<config>
    <srch2Home>./multicore/</srch2Home>
        <!-- Make sure to specify the home of your SRCH2 installation.  Example:
          <srch2Home>/home/joe/srch2</srch2Home>
        -->

    <licenseFile>../../conf/srch2_license_key.txt</licenseFile>

    <listeningHostname>0.0.0.0</listeningHostname>
    <listeningPort>8087</listeningPort>

    <!-- moved from <query> which is now per core -->
    <maxSearchThreads>2</maxSearchThreads>

    <!-- Testing multiple cores here -->
    <cores defaultCoreName="core1">
        <core name="core1">
            <dataFile>movie-data.json</dataFile>
            <dataDir>core1</dataDir>
            <dataSourceType>1</dataSourceType>
            <indexConfig>
                <indexType>0</indexType>
                <supportSwapInEditDistance>true</supportSwapInEditDistance>
                <defaultQueryTermBoost>1</defaultQueryTermBoost>
                <enablePositionIndex>1</enablePositionIndex>
            </indexConfig>
	    <query>
	        <rankingAlgorithm>
		    <recordScoreExpression>idf_score*doc_boost</recordScoreExpression>
	        </rankingAlgorithm>
		<fuzzyMatchPenalty>0.9</fuzzyMatchPenalty>
		<queryTermSimilarityThreshold>0.75</queryTermSimilarityThreshold>
		<prefixMatchPenalty>0.95</prefixMatchPenalty>
		<cacheSize>65536000</cacheSize>
		<rows>10</rows>
		<fieldBasedSearch>1</fieldBasedSearch>
		<searcherType>0</searcherType>

		<!-- 0: exact match; 1: fuzzy match.-->
		<queryTermFuzzyType>0</queryTermFuzzyType>

		<!-- 0: prefix match; 1: complete match -->
		<queryTermPrefixType>1</queryTermPrefixType>

		<queryResponseWriter>
		    <responseFormat>1</responseFormat>
		</queryResponseWriter>
	    </query>
            <schema>
                <fields>
                    <field name="title" type="text" indexed="false" searchable="false" />
                    <field name="director" type="text" indexed="false" refining="false"/>
                    <field name="genre" type="text" indexed="true"
                           default="HORROR" required="false"/>
                    <field name="year" type="integer" indexed="false" refining="true"
                           default="2000" required="false"/>
                    <field name="id" type="text" refining="true" indexed="false"/>
                </fields>

                <uniqueKey>id</uniqueKey>

                <facetEnabled>true</facetEnabled>
                <facetFields>
                    <facetField name="genre" facetType="categorical"/>
                    <facetField name="year"  facetType="range" facetStart="1990" facetEnd="2050"
                                facetGap="10"/>
                </facetFields>

                <types>
                    <fieldType name="text_standard">
                        <analyzer>
                            <filter name="PorterStemFilter" dictionary="" />
                            <filter name="StopFilter" words="stop-words.txt" />
                        </analyzer>
                    </fieldType>
                </types>
            </schema>
	    <updatehandler>
	        <maxDocs>15000000</maxDocs>
		<maxMemory>10000000</maxMemory>
		<mergePolicy>
		    <mergeEveryNSeconds>10</mergeEveryNSeconds>
		    <mergeEveryMWrites>10</mergeEveryMWrites>
		</mergePolicy>
	    </updatehandler>
        </core>

    </cores>

    	<updateLog>
		    <logLevel>3</logLevel>
		    <accessLogFile>srch2-log.txt</accessLogFile>
		</updateLog>

</config>


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

<title>org.maltparser.core.feature.system (MaltParser 1.8.1)</title>
<meta name="date" content="2014-12-02">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.maltparser.core.feature.system

Classes

FeatureEngine

FunctionDescription


text:
/* @flow */

'use strict';

var _Object$defineProperty = require('babel-runtime/core-js/object/define-property')['default'];

var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];

_Object$defineProperty(exports, '__esModule', {
    value: true
});

exports['default'] = translateFunctionType;

var _rx = require('rx');

var _rx2 = _interopRequireDefault(_rx);

var _type = require('./type');

var _type2 = _interopRequireDefault(_type);

var _arguments = require('./arguments');

var _arguments2 = _interopRequireDefault(_arguments);

// import notImplemented from './notImplemented';

var literal = _rx2['default'].Observable.of;

function translateFunctionType(node) {
    return _rx2['default'].Observable.concat((0, _arguments2['default'])(node.arguments, '()'), literal(' => '), (0, _type2['default'])(node.idlType));
}

module.exports = exports['default'];
//# sourceMappingURL=functionType.js.map


text:
Ext.define('Metadata.controller.AttributiRelation', {
    extend: 'Admin.controller.BaseCrudController',

    stores:
    [
    'Metadata.store.Fieldxtype'
    ],

    config: {
        owner: false,
        ownerModel: false,
        relatedModel: false,
        relationModel: false,
        relationType: 'one',
        setRelationFunction: false,
        getRelationFunction: false,
        setRelationToConfigFunction: false,
        getRelationToConfigFunction: false
    },

    getExtraParams: function ()
    {
        owner = this.getOwner ();
        extraParams = {};

        if (owner)
        {
           extraParams = {
               ownerModel: this.getOwnerModel(),
               ownerId: owner.get('id'),
               relatedModel: this.getRelatedModel(),
               relationModel: this.getRelationModel(),
               relationType: this.getRelationType(),
               setRelationFunction: this.getSetRelationFunction(),
               getRelationFunction: this.getGetRelationFunction(),
               setRelationToConfigFunction: this.getSetRelationToConfigFunction(),
               getRelationToConfigFunction: this.getGetRelationToConfigFunction()

           }
        }
        return extraParams;
    },

    resizeWindow: function (window)
    {
        this.application.resizeWindow(window, 50, 1.7);
    },

    buildToolbar : function ()
    {
      var toolbar = Ext.create('Ext.toolbar.Toolbar', {
                    dock: 'top',
                    id: 'mainToolbar'+this.getControllerName(),
                    items: [
                                {
                                    text: 'Aggiungi relazione',
                                    scope: this,
                                    tooltip: 'Relaziona '+this.getRelatedName()+' a '+this.getOwnerName(),
                                    icon: '/bundles/fdtadmin/images/icons/add.png',
                                    cls: 'x-btn-text-icon',
                                    id: 'aggiungi'+this.getControllerName(),
                                    handler: function (button){
                                        this.searchRelatedObject()
                                    }
                                },
                                '-',
                                {
                                    text: 'Elimina',
                                    scope: this,
                                    icon: '/bundles/fdtadmin/images/icons/delete.png',
                                    cls: 'x-btn-text-icon',
                                    id: 'removeRelation'+this.getControllerName(),
                                    handler: function (button){
                                        this.removeRelation(button)
                                    }
                                },
                                '-'
                            ]
                    });

      return toolbar;

    },

    buildSearchWindowCenterToolbar : function ()
    {
      var toolbar = Ext.create('Ext.toolbar.Toolbar', {
                    dock: 'top',
                    id: 'searchToolbar'+this.getControllerName(),
                    items: [
                                {
                                    text: 'Scegli',
                                    tooltip: 'Relaziona il '+this.getRelatedName()+' selezionato a '+this.getOwnerName(),
                                    scope: this,
                                    icon: '/bundles/fdtadmin/images/icons/add.png',
                                    cls: 'x-btn-text-icon',
                                    id: 'scegliFromSearch'+this.getControllerName(),
                                    handler: function (button){
                                        this.creaAssociazione(button);
                                    }
                                }
                            ]
                    });

      return toolbar;

    },

    getGridStore : function ()
    {
        var grid = Ext.ComponentQuery.query('#'+this.getPanelId())[0];
        return grid.getStore();
    },

    getGridView : function ()
    {
        var grid = Ext.ComponentQuery.query('#'+this.getPanelId())[0];
        return grid.getView();
    },

    removeRelation : function (button)
    {
        var gridPanel = button.up('panel');

        var selectedRow = this.getSelectedRow (gridPanel);

        this.getGridStore().remove(selectedRow);
        this.getGridView().refresh();
        this.getGridStore().sync();

    },

    creaAssociazione : function (button)
    {
        var searchResultPanel = button.up('panel');

        var selectedRow = this.getSelectedRow (searchResultPanel);

        if (selectedRow && this.getRelationType() == 'one')
        {

            selectedRow.setDirty();
            this.getGridStore().insert(0, selectedRow);
            this.getGridView().refresh();

            this.getGridStore().sync();

        }

        if (selectedRow && this.getRelationType() == 'manyWithConfig')
        {
            var form = this.aggiungi(button);
            var record = form.getRecord();

            record.set ('relatedId', selectedRow.get ('id'));

        }

    },

    addSearchWindowCenterToolbar : function (panel)
    {

        var tootlbarSearch = this.buildSearchWindowCenterToolbar ();

        panel.addDocked(tootlbarSearch);

    },

    searchRelatedObject: function ()
    {

            var controller = Ext.create('Metadata.controller.Search', {
                                                            namespace: 'searchWindow',
                                                            ownerModel: this.getRelatedModel(),
                                                            ownerModelString: this.getRelatedModel(),
                                                            application: this.getApplication(),
                                                            baseFilter: [{}],
                                                            callerController: this
                                                          });
            controller.init();
    },

    getControllerName: function ()
    {
        var relatedModelOj = new String(this.getRelationModel());

        arrayRelatedModel = relatedModelOj.split ('__');
        return arrayRelatedModel[1];

    },

    getOwnerName: function ()
    {
        var ownerModelOj = new String(this.getOwnerModel());

        arrayOwnerModel = ownerModelOj.split ('__');
        return arrayOwnerModel[1];

    },

    getRelatedName: function ()
    {
        var modelOj = new String(this.getRelatedModel());

        arrayModel = modelOj.split ('__');
        return arrayModel[1];

    },

    getRestUrl: function ()
    {
        return 'metadata/manageRelations';
    },

    getTitle: function (title)
    {

        return 'Relazioni: '+this.getOwner().get('uniqueName')+' > '+this.getRelatedName();

    }

});


text:
import { createRequestTypes } from './creator';

export default createRequestTypes('<%= upper %>', ['GET_LIST', 'UPDATE', 'ADD', 'REMOVE']);


text:
PKG_NAME = ejabberd
PKG_VERS = 2.1.13
PKG_EXT = tgz
PKG_DIST_NAME = $(PKG_NAME)-$(PKG_VERS).$(PKG_EXT)
PKG_DIST_SITE = http://www.process-one.net/downloads/ejabberd/$(PKG_VERS)/
PKG_DIR = $(PKG_NAME)-$(PKG_VERS)/src

DEPENDS = cross/expat cross/zlib cross/openssl native/erlang

HOMEPAGE = http://www.ejabberd.im
COMMENT  = ejabberd is high-performace enterprise Jabber/XMPP instant messaging server written in Erlang/OTP. It's cross-platform, fault-tolerant, clusterable and modular.
LICENSE  = GPLv2

GNU_CONFIGURE = 1
CONFIGURE_ARGS += --with-erlang=$(WORK_DIR)/../../../native/erlang/work-native/install/usr/local/bin

PRE_CONFIGURE_TARGET = myPreConfigure
POST_INSTALL_TARGET = myPostInstall

include ../../mk/spksrc.cross-cc.mk

.PHONY: myPreConfigure
myPreConfigure:
	@$(RUN) sed -e "s#-I\$$ERLANG_EI_DIR#-I$(INSTALL_DIR)/$(INSTALL_PREFIX)/lib/erlang/lib/erl_interface-3.7.15#g" -i configure
	@$(RUN) sed -e "s#-L\$$ERLANG_EI_LIB#-L$(INSTALL_DIR)/$(INSTALL_PREFIX)/lib/erlang/lib/erl_interface-3.7.15/lib#g" -i configure

.PHONY: myPostInstall
myPostInstall:
	sed -e "s#$(INSTALL_DIR)##g" -i $(STAGING_INSTALL_PREFIX)/sbin/ejabberdctl
	sed -e "s#^INSTALLUSER=#INSTALLUSER=ejabberd#g" -i $(STAGING_INSTALL_PREFIX)/sbin/ejabberdctl
	sed -e "s#ERL=$(WORK_DIR)/../../../native/erlang/work-native/install/usr/local/bin/erl#ERL=$(INSTALL_PREFIX)/bin/erl#g" -i $(STAGING_INSTALL_PREFIX)/sbin/ejabberdctl
	sed -e "s#! -x \"\$$FLOCK\"#\"1\"#g" -i $(STAGING_INSTALL_PREFIX)/sbin/ejabberdctl
	sed -e "s|^#EJABBERD_PID_PATH=/var/run/ejabberd/ejabberd.pid|EJABBERD_PID_PATH=/usr/local/ejabberd/var/ejabberd.pid|g" -i $(STAGING_INSTALL_PREFIX)/etc/ejabberd/ejabberdctl.cfg


text:
Emmy is a library for building protocols/applications based on zero-knowledge proofs, for example anonymous credentials.
Zero-knowledge proofs are **client-server protocols** (in crypto terms also *prover-verifier*, where the prover takes on
the role of the client, and the verifier takes on the role of the server) where the client proves a knowledge
of a secret without actually revealing the secret.

Emmy also implements a communication layer supporting the execution of these protocols.
Communication between clients and the server is based on [Protobuffers](https://developers.google.com/protocol-buffers/) and [gRPC](http://www.grpc.io/).
Emmy server is capable of serving (verifying) thousands of clients (provers) concurrently. Currently, the communication
is implemented for the two anonymous credential schemes (see [Currently offered cryptographic schemes](#currently-offered-cryptograhpic-schemes)).

In addition, emmy is built with **mobile clients** in mind, as it comes with *compatibility*
package providing client wrappers and types that can be used for generating language bindings for
Android or iOS mobile platforms.

To get some more information about the theory behind zero knowledge proofs or developing
various parts of emmy library, please refer to additional documentation in the *docs* folder.

#### What does emmy stand for?
Emmy library is named after a German mathematician [Emmy Noether](https://en.wikipedia.org/wiki/Emmy_Noether), recognised as one of the most important 20th century mathematicians. Emmy Noether's groundbreaking work in the field of abstract algebra earned her a nickname *the mother of modern algebra*. We named our library after her, since modern cryptography generally relies heavily on abstract algebraic structures and concepts.

- [Currently offered cryptographic primitives](#currently-offered-cryptographic-primitives)
- [Currently offered cryptographic schemes](#currently-offered-cryptograhpic-schemes)
- [Installation](#installation)
- [emmy CLI tool](#using-the-emmy-cli-tool)
  * [emmy server](#emmy-server)
  * [emmy clients](#emmy-clients)
  * [TLS support](#tls-support)
- [Further documentation](#documentation)

# emmy - anonymous credentials showcase

Let's say you would like to travel to some country which requires proof of vaccination for certain diseases.
You go to the clinic named South Loop Clinic, you get vaccinated and receive a proof that you are vaccinated. In fact, South Loop Clinic issues an anonymous credential which contains a proof that you have been vaccinated for certain diseases.

The credential would contain something like:

```
Name: Andrew
Surname: McCain
Age: 45
Gender: M
Vaccinated for yellow fever: true
```

Note that the credential does not contain attributes as plaintext - the credential is received from the
issuer by a zero-knowledge proof. When credential needs to be shown, another zero-knowledge proof
is executed. These protocols are unlinkable - issuer and verifier cannot determine
whether it is going on about the same credential (unless you reveal some unique attributes like address).
In fact, even when user connects two times using the same credential, the verifier cannot know that the same
credential has been used (that the same user is connecting).

Let's assume there is a smart phone app which offers a UI to the emmy protocols.

To obtain a credential, user first need to create a master secret key. An app runs:

```
masterSecret := pubKey.GenerateUserMasterSecret()
```

Here, pubKey is the public key of a clinic (clinic instantiates an `Org` from `crypto/cl/org.go` and
uses it for issuing a credential).

The communication between user and clinic go for example over NFC - between user's phone and
some clinic terminal.

User obtains a credential structure from a clinic (see `client/cl_test.go`):

```
rc, err := client.GetCredentialStructure()
```

Credential structure for `Org` is defined in `config/defaults.yml`.
User then fills the credential using an app and starts a protocol to obtain a credential:

```
name, _ := rc.GetAttr("Name")
name.UpdateValue("Andrew")

surname, _ := rc.GetAttr("Surname")
surnname.UpdateValue("McCain")

age, _ := rc.GetAttr("Age")
age.UpdateValue(45)

gender, _ := rc.GetAttr("Gender")
gender.UpdateValue("M")

vaccinated, _ := rc.GetAttr("Vaccinated")
vaccinated.UpdateValue("true") // vaccinated for yellow fever

cm, err := cl.NewCredManager(params, pubKey, masterSecret, rc)
cred, err := client.IssueCredential(cm, "testRegKey5")
```

The clinic verifies the validity of attributes and issues a credential. The verification in this case
is manual - an authorized person needs to verify the attributes and trigger the issuance of a credential.
User now possesses a credential on his phone.

When user arrives to a foreign country and a proof of vaccination is needed, he opens an app
which runs:

```
acceptableCreds, err := client.GetAcceptableCreds()
```

The server returns a list of organizations whose credentials it accepts. Additionally, the attributes
that need to be revealed are specified:

```
revealedAttrs := acceptableCreds["South Loop Clinic"]
```

In our case this might be:

```
revealedAttrs = []string{"Vaccinated}
```

Now, the user can prove he has been vaccinated:

```
_, err := client.ProveCredential(cm, cred, revealedAttrs)
```

Verifier learns nothing about the user except that he was vaccinated for a certain disease.

# Currently offered cryptographic primitives

The library supports building complex cryptographic schemes. To enable this various layers are needed:

 * mathematical groups in which the operations take place
 * utilities for generating safe primes, group generators, for decomposing integers into squares (`crypto/common`)
 * commitments (to commit to a chosen value while keeping it hidden to others)
 * zero-knowledge proofs as building blocks for schemes (protocols which are used as subprotocols in schemes, see `crypto/zkp`)
 * communication layer to enable client-server interaction (for messages exchanged in protocols)

## Groups

The following groups are offered in appropriate subpackages of `crypto` package:

 * ℤn* (`zn.Group`) - group of all integers smaller than _n_ and coprime with _n_. In the special
 case when _n_ is a prime, a specialized group `zn.GroupZp` may be used.
 * Schnorr group (`schnorr.Group`) - cyclic subgroup of ℤp; the order of Schnorr group is _q_ where _p = qr + 1_ for some _r_ (_p_, _q_ are primes);
 the order of Schnorr group is smaller than of ℤp which means faster computations
 * RSA group (`rsa.Group`) - group of all integers smaller than _n_ and coprime with _n_, where _n_ is a product of two distinct large primes
 * QR RSA group (`qr.RSA`) - group of quadratic residues modulo _n_ where _n_ is a product of two primes
 * QR special RSA group (`qr.RSASpecial`) - group of quadratic residues modulo _n_ where _n_ is a product of two safe primes
 * Elliptic curve group (`ec.Group`) - wrapper around Go `elliptic.Curve`

## Commitments

The following commitments are offered in appropriate subpackages of `crypto` package:

 * Pedersen - for commitments in Schnorr group (supported ℤp and EC groups, see packages `pedersen`
 and `ecpedersen`, respectively)
 * Damgard-Fujisaki [12] - for commitments in QR special RSA group (see package `df`)
 * Q-One-Way based [9] (see package `qoneway`). Note that Damgard-Fujisaki commitments should be used instead.

## Zero-knowledge proofs

 * Schnorr proofs for proving the knowledge of dlog [5],
dlog equality [7], dlog equality blinded transcript [4], and partial dlog knowledge [8]. All of these proofs
 work with both ℤp and EC groups (see packages `schnorr` and `ecschnorr`, respectively).
 * Proofs of knowledge of homomorphism preimage and knowledge of partial homomorphism preimage
  (see package `preimage`). These are generalizations of Schnorr proof to general
   groups and one-way homomorphisms.
 * Proof of knowledge of representation (generalized Schnorr for multiple bases) [10]
 * Damgard-Fujisaki proofs (package `df`) [12] - for proving that you can open a commitment,
 that two commitments hide the same value, that a commitment contains a multiplication of two committed values,
 that the committed value is positive, that the committed value is a square, commitment range based on Lipmaa [11]
 * QR special RSA representation proof (like Schnorr but in QR special RSA group, see `qr` package)
 * Quadratic residuosity and nonresiduosity (packages `qr` and `qnr`) [6]
 * Camenisch-Shoup verifiable encryption [1]

## Communication

Client-server communication code (based on gRPC) which enables execution of protocols over the internet is in
`client` and `server` packages. The messages and services are defined in `proto` folder. Translations between
gRPC and native emmy messages are in `proto/translations.go`.

# Currently offered cryptographic schemes

Currently two anonymous credentials schemes are offered:

 * Pseudonym system [4] (see `crypto/zkp/schemes/pseudonymsys`) (offered in ℤp and EC groups)
 * Camenisch-Lysyanskaya anonymous credentials [2][15] (see `crypto/cl`) - work in progress

Pseudonym system [4] was the first anonymous credential scheme and was superseded by Camenisch-Lysyanskaya scheme [2].

## Camenisch-Lysyanskaya anonymous credentials

What are anonymous credentials:

 * user gets a certificate which contains personal data (name, gender, nationality, age ... )
 * the same certificate can be used to connect to different services (even if the databases are joined service providers
 cannot map/link the users)
 * when connecting to a service, user can choose which data to reveal - some services might require only the possession
 of a certificate (e.g. certifying that user paid for something), others might require some subset of data contained in certificate

While anonymity is obviously a MUST in e-voting, it might gradually become more important in other scenarios as well:

 * online subscriptions
 * wearable healthcare (for example sending diabetes data to a research team)
 * vehicle communications - cars sending out data about traffic

### CL scheme - brief overview how it works

There are public parameters _Z_, _S_, _R1_, ... , _Rl_.

Issuer (of a credential) computes _Q_ based on public parameters, user attributes and random _v_:

```
Q = (Z / (R1^attr1 * ... * Rl^attrl * S^v)
```

Issuer then chooses random prime _e_ (which is as public key in RSA algorithm), computes _d_ such that:

```
x^(e*d) = x (mod n)
```

Issuer then computes _A_ (as in RSA signature):

```
A = Q^d
```

The credential in the form of a triplet _(A, e, v)_ is then given to a user.

The organization that checks the validation of a user's credential checks whether:

```
A^e = Q = (Z / (R1^attr1 * ... * Rl^attrl * S^v)
```

If only a subset of attributes are revealed, zero-knowledge proof is applied - on the right side of the equation only
a subset of attributes is known, thus the user needs to prove the knowledge of attributes such that the equation holds.

# Warning
_All components of emmy cryptography library are a work in progress. At this point, the library can be used to build proof of concept implementations for research purposes and **should never be used in production**. Project's code organization and library APIs are **not stable** - they are expected to undergo major changes, and may be changed at any point._

# Installation
To install emmy, run

```
$ go get github.com/xlab-si/emmy
```

This should give you the `emmy` executable in your `$GOBIN`.
You can run the unit tests to see if everything is working properly with:

```
$ go test ./...
```

# Using the emmy CLI tool

Below we provide some isntructions for using the `emmy` CLI tool. You can type `emmy` in the terminal to get a list of available commands and subcommands, and to get additional help.

Emmy CLI offers two commands:
* `emmy server` (with a `start` subcommand, e.g. `emmy server start`) and
* `emmy client` (with subcommand `info`).
> **Note:** emmy client command is currently going through a major revision. Running clients for
    demo interactive protocols (_pedersen_, _pedersen_ec_, _schnorr_, _schnorr_ec_ _cspaillier_) is
     no longer supported. Instead, clients for running protocols comprising anonymous
     authentication schemes will be added soon.

## emmy server

Emmy server waits for requests from clients (provers) and starts verifying them. Note that emmy server connects to a redis database in order to verify the registration keys, provided in the nym generation process. Redis is expected to run at localhost:6379 (or as defined in [defaults.yml](config/defaults.yml)).

```bash
$ emmy server              # prints available subcommands
$ emmy server start --help # prints subcommand flags, their meaning and default values
```

To start emmy server with the default options, run

```bash
$ emmy server start        # starts emmy server with default settings
```

Alternatively, you can control emmy server's behavior with the following options (specified as command line flags):
1. **Port**: flag *--port* (shorthand *-p*), defaults to 7007.

    Emmy server will listen for client connections on this port. Example:
    ```bash
    $ emmy server start --port 2323   # starts emmy server that listens on port 2323
    $ emmy server start -p 2323       # equivalently
    ```
2. **Logging level**: flag *--loglevel* (shorthand *-l*), which must be one of `debug|info|notice|error|critical`. Defaults to `ìnfo`.

    For development or debugging purposes, we might prefer more fine-grained logs, in which case we would run:
    ```bash
    $ emmy server start --loglevel debug # or shorthand '-l debug'
    ```
3. **Log file**: flag *--logfile*, whose value is a path to the file where emmy server will output logs in addition to standard output. If the file does not exist, one is created. If it exists, logs will be appended to the file. It defaults to empty string, meaning that the server will not write output to any file.

    Example:
    ```bash
    $ emmy server start --loglevel debug --logfile ~/emmy-server.log
    ```

4. **Certificate and private key**: flags *--cert* and *--key*, whose value is a path to a valid certificate and private key in PEM format. These will be used to secure communication channel with clients. Please refer to [explanation of TLS support in emmy](#tls-support) for explanation.

5. **Address of the redis database**: flag *--db* of the form *redisHost:redisPort*, which points
 to a running instance of redis database that holds [registration keys](#registration-keys).
 Defaults to *localhost:6379*.

Starting the server should produce an output similar to the one below:

```
(1) [server][Mon 25.Sep 2017,14:11:041] NewProtocolServer ▶ INFO  Instantiating new protocol server
(2) [server][Mon 25.Sep 2017,14:11:041] NewProtocolServer ▶ INFO  Successfully read certificate [test/testdata/server.pem] and key [test/testdata/server.key]
(3) [server][Mon 25.Sep 2017,14:11:041] NewProtocolServer ▶ NOTI  gRPC Services registered
(4) [server][Mon 25.Sep 2017,14:11:041] EnableTracing ▶ NOTI  Enabled gRPC tracing
(5) [server][Mon 25.Sep 2017,14:11:041] Start ▶ NOTI  emmy server listening for connections on port 7007
```

Line 1 indicates that the emmy server is being instantiated. Line 2 informs us about the server's certificate and private key paths to be used for secure communication with clients. Line 3 indicates that gRPC service for execution of crypto protocols is ready, and Line 4 tells us that gRPC tracing (used to oversee RPC calls) has been enabled. Finaly, line 5 indicates that emmy server is ready to serve clients.

When a client establishes a connection to emmy server and starts communicating with it, the server will log additional information. How much gets logged depends on the desired log level.

You can stop emmy server by hitting `Ctrl+C` in the same terminal window.

#### Registration keys

Emmy server verifies registration keys provided by clients when initiating the nym generation procedure. A separate server is expected to provide registration keys to clients via another channel (e.g. QR codes on physical person identification) and save the generated keys to a registration database, read by the emmy server.

## emmy clients (DEPRECATED)

Running a client requires an instance of emmy server. First, spin up emmy server according to instructions in the previous section. You can then start one or more emmy clients in another terminal.

We use commands of the following form to start emmy clients:

```bash
$ emmy client <commonClientFlags> protocolSubcommand <protocolFlags>
```

where *commonClientFlags* control the following aspects:

1. **How many clients to start**: flag *--nclients* (shorthand *-n*), defaults to 1.
2. **Whether to run clients concurrently or not**: flag *--concurrent*. Include this flag if you want to run the specified number of clients consurrently. The absence of this flag means that clients will be run sequentially.
3. **Logging level**: flag *--loglevel* (shorthand *-l*), which must be one of `debug|info|notice|error|critical`. Defaults to `ìnfo`.
4. **URI of the emmy server**: flag *--server*, defaults to *localhost:7007*.
5. **CA certificate**: flag *--cacert*, points to a path to a certificate of the CA that issued emmy server's certificate, in PEM format. This will be used to secure communication channel with the server. Please refer to [explanation of TLS support in emmy](#tls-support) for explanation.
6. **Server name override**: flag *--servername*. This will instruct clients to check server
certificate's common name (CN) against the value of the provided flag, instead of server's
hostname. Allows certificate validation to pass even when server's hostname does not
match the CN specified in server's certificate.

    > This should only be used for connecting clients to emmy development server, for instance
    where self-signed certificate is used, or when the CN in server's certificate is not resolvable.
7. **Whether to use system's certificate pool**: flag *--syscertpool*. When present, the
values of `--cacert` and `--servername` will be ignored.
8. **Connection timeout**: flag *--timeout* (shorthand *-t*), indicating a timeout (in milliseconds)
 for establishing connection with emmy server. Client fails if connection cannot be established before
 the timeout. Defaults to *5000 milliseconds*.

Moreover, the *protocolSubcommand* corresponds to a concrete protocol that we want to demonstrate between emmy client and emmy server. You can list valid *protocolSubcommand* values by running

```bash
$ emmy client --help
```

To get more info on *protocolFlags* that the chosen *protocolCommand* supports, run `emmy client <protocolCommand> --help`, for instance

```bash
$ emmy client pedersen --help
```

and you will se additional flags that you can provide as input to bootstrap appropriate protocol. Usually, you can provide some sort of a secret value via the flag *--secret*, and the protocol variant to execute via the flag *--variant* (shorthand *-v*), denoting whether to execute sigma protocol, zero-knowledge proof or zero-knowledge proof of knowledge (`sigma|zkp|zkpok`, defaults to `sigma`).

Below we give some examples that run emmy client in order to demonstrate Schnorr protocol:
```
$ emmy client schnorr #Runs sigma protocol with the default values
$ emmy client --loglevel debug schnorr
$ emmy client -l debug schnorr --variant zkp --secret 32432
$ emmy client -l debug schnorr -v zkp --secret 32432
```

Here are some more fun examples:
```
$ emmy client --nclients 5 schnorr -v zkpok
$ emmy client -n 5 schnorr -v zkpok # this one is equivalent to the one above
$ emmy client -n 5 --concurrent schnorr -v zkpok
```

And here is some example output of the `emmy client` command:
```
$ emmy client --server localhost:7007 pedersen
(1) GetConnection ▶ INFO  Getting the connection
(2) GetConnection ▶ NOTICE  Established connection to gRPC server
(3) ***Running client #1***
(4) send ▶ INFO  [Client 1257061046] Successfully sent request of type *protobuf.Message_Empty
(5) receive ▶ INFO  [Client 1257061046] Received response of type *protobuf.Message_PedersenFirst from the stream
(6) send ▶ INFO  [Client 1257061046] Successfully sent request of type *protobuf.Message_Bigint
(7) receive ▶ INFO  [Client 1257061046] Received response of type *protobuf.Message_Empty from the stream
(8) send ▶ INFO  [Client 1257061046] Successfully sent request of type *protobuf.Message_PedersenDecommitment
(9) receive ▶ INFO  [Client 1257061046] Received response of type *protobuf.Message_Status from the stream
(10) ***Time: 0.003153414 seconds***
```

Lines 1-2 tell us about the procedure of initializing, and eventually, establishing a connection to emmy server at the given URI. Line 3 comes from the emmy CLI, and notifies us that the protocol client is about to start. Lines 4-9 indicate the communication taking place between the client and the server (e.g. here they are executing the chosen crypto protocol). The last line reports the total time required to execute the protocol - if we run several clients (either sequentially or concurrently), it prints the total time required for all the clients to finish.

## TLS support
Communication channel between emmy clients and emmy server is secure, as it enforces the usage of TLS. TLS is used to encrypt communication and to ensure emmy server's authenticity.

By default, the server will attempt to use the private key and certificate in `test/testdata` directory. The provided certificate is self-signed, and therefore the clients can use it as the CA certificate (e.g. certificate of the entity that issued server's certificate) which they have to provide in order to authenticate the server.
 >**Important note:** You should never use the private key and certificate that comes with this repository when running emmy in production. These are meant *for testing and development purposes only*.

In a real world setting, the client needs to keep a copy of the CA certificate which issued server's certificate. When the server presents its certificate to the client, the client uses CA's certificate to check the validity of server's certifiacate.

To control keys and certificates used for TLS, emmy CLI programs use several flags. In addition to those already presented in this document, `emmy server` supports the following flags:

* `--cert` which expects the path to server's certificate in PEM format,
* `--key` which expects the path to server's private key file.

On the other hand, we can provide `emmy client` with the following flags:
* `--cacert`, which expects the path to certificate of the CA that issued emmy server's certificate
(in PEM format). Again, if this flag is omitted, the certificate in `test/testdata` directory is used.
* `--servername`, which instructs the client to skip validation of the server's hostname. In the
absence of this flag, client will always check whether the server's hostname matches
the common name (CN) specified in the server's certificate as a part of certificate validation. For
development purposes, hostname and server's CN will likely not match, and thus it is convenient to
provide a `--servername` flag with the value matching the CN specified in the server's certificate.
* `--syscertpool`, which tells the client to look for the CA certificate in the host system's
certificate pool. If this flag is provided, the presence of `--cacert` or `--servername` flags
will be ignored. In addition, the CA certificate needs to be put in the system's default
certificate store location beforehand.

  To give you an example, let's try to run an emmy client against an instance of emmy server that uses the self-signed certificate shipped with this repository. The hostname in the certificate is *localhost*, but the server is deployed on a host other than localhost (for instance, *10.12.13.45*). When we try to contact the server withour the *--insecure* flag, here's what happens:

  ```bash
  $ emmy client --server 10.12.13.45:7007 schnorr

  2017/09/13 12:48:47 [client] 12:48:47.232 GetConnection ▶ INFO 001 Getting the connection
  Cannot connect to gRPC server: Could not connect to server 10.12.13.45:7007 (x509: cannot validate certificate for 10.12.13.45 because it doesnt contain any IP SANs)
  ```

  Now let's include the *--insecure* flag, and the (insecure) connection to the server is now successfully established.

  ```bash
  $ emmy client --server 10.10.43.45:7007 --insecure schnorr

  2017/09/14 09:02:01 [client] 09:02:01.153 GetConnection ▶ INFO 001 Getting the connection
  2017/09/14 09:02:01 [client] 09:02:01.153 GetConnection ▶ WARN 002 ######## You requested an **insecure** channel! ########
  2017/09/14 09:02:01 [client] 09:02:01.153 GetConnection ▶ WARN 003 As a consequence, server's identity will *NOT* be validated!
  2017/09/14 09:02:01 [client] 09:02:01.153 GetConnection ▶ WARN 004 Please consider using a secure connection instead
  2017/09/14 09:02:01 [client] 09:02:01.162 GetConnection ▶ NOTI 005 Established connection to gRPC server
  ```

# Documentation
* [A short overview of the theory emmy is based on](./docs/theory.md)
* [Developing emmy (draft)](./docs/develop.md)

# Roadmap

 * Improve the database layer supporting persistence of cryptographic material (credentials, pseudonyms, ...)
 * Refactor Camenisch-Lysyanskaya scheme (database records, challenge generation ... )
 * Additional proofs for Camenisch-Lysyanskaya scheme (range proof for attributes ... )
 * Revocation for Camenisch-Lysyanskaya scheme
 * Attribute types in Camenisch-Lysyanskaya scheme (string, int, date, enum)
 * Performance optimization (find bottlenecks and fix them)
 * Efficient attributes for anonymous credentials [15]
 * Camenisch-Lysyanskaya scheme based on pairings [14]
 * Fix Camenisch-Shoup verifiable encryption (it was implemented before many of the primitives were available)

# References

[1] J. Camenisch and V. Shoup, Practical verifiable encryption and decryption of discrete logarithms, http://eprint.iacr.org/2002/161, 2002.

[2] J. Camenisch and A. Lysyanskaya. A signature scheme with efficient protocols. In S. Cimato, C. Galdi, and G. Persiano, editors, Security in Communication Networks, Third International Conference, SCN 2002, volume 2576 of LNCS, pages 268–289. Springer Verlag, 2003.

[3] D. Chaum and T. P. Pedersen, Wallet databases with observers, Advances in Cryptology — CRYPTO '92 (E. F. Brickell, ed.), LNCS, vol. 740, Springer-Verlag, 1993, pp. 89– 105.

[4] A. Lysyanskaya, R. Rivest, A. Sahai, and S. Wolf. Pseudonym systems. In Selected Areas in Cryptography, vol. 1758 of LNCS. Springer Verlag, 1999.

[5] C. P. Schnorr. Efficient Identification and Signatures for Smart Cards. In Crypto '89, LNCS 435, pages 235–251. Springer-Verlag, Berlin, 1990.

[6] Goldwasser, Shafi, Silvio Micali, and Charles Rackoff. "The knowledge complexity of interactive proof systems." SIAM Journal on computing 18.1 (1989): 186-208.

[7] D. Chaum and T. P. Pedersen, Wallet databases with observers, Advances in Cryptology — CRYPTO '92 (E. F. Brickell, ed.), LNCS, vol. 740, Springer-Verlag, 1993, pp. 89– 105.

[8] Cramer, Ronald, Ivan Damgård, and Berry Schoenmakers. "Proofs of partial knowledge and simplified design of witness hiding protocols." Advances in Cryptology—CRYPTO'94. Springer Berlin/Heidelberg, 1994.

[9] Cramer, Ronald, and Ivan Damgård. "Zero-knowledge proofs for finite field arithmetic, or: Can zero-knowledge be for free?." Advances in Cryptology—CRYPTO'98. Springer Berlin/Heidelberg, 1998.

[10] Brands, Stefan A. "An efficient off-line electronic cash system based on the representation problem." (1993): 01-16.

[11] Helger Lipmaa. On diophantine complexity and statistical zero-knowledge arguments. In ASIACRYPT, volume 2894 of Lecture Notes in Computer Science, pages 398–415. Springer, 2003.

[12] I. Damgård and E. Fujisaki. An integer commitment scheme based on groups with hidden order. http://eprint.iacr.org/2001, 2001.

[13] I. Damgård. Efficient concurrent zero-knowledge in the auxiliary string model. In B. Preneel, editor, Advances in Cryptology — EUROCRYPT 2000, volume 1807 of Lecture Notes in Computer Science, pages 431–444. Springer Verlag, 2000.

[14] Camenisch, Jan, and Anna Lysyanskaya. "Signature schemes and anonymous credentials from bilinear maps." Annual International Cryptology Conference. Springer, Berlin, Heidelberg, 2004.

[15] Camenisch, Jan, and Thomas Groß. "Efficient attributes for anonymous credentials." Proceedings of the 15th ACM conference on Computer and communications security. ACM, 2008.


text:
<?php

namespace Jax\Server;

/**
 * Server response class
 *
 * @author Shay Anderson 03.15 <http://www.shayanderson.com/contact>
 */
class Response
{
	/**
	 * Response data
	 *
	 * @var array
	 */
	private static $__data = [];

	/**
	 * JSON only response data
	 *
	 * @var array
	 */
	private static $__data_response;

	/**
	 * Current response ID
	 *
	 * @var int
	 */
	public static $__response_id__ = 0;

	/**
	 * Function data setter (ex: ->alert(x))
	 *
	 * @param string $name
	 * @param array $arguments
	 * @return \Jax\Server\Response
	 */
	public function &__call($name, array $arguments)
	{
		foreach($arguments as $k => &$v)
		{
			$v = json_encode($v);
		}

		// set function call: func(arg1, ...)
		self::$__data[self::$__response_id__][] = $name . '(' . implode(',', $arguments) . ')';

		return $this;
	}

	/**
	 * Data property setter (ex: ->document...)
	 *
	 * @param string $name
	 * @return \Jax\Server\Response
	 */
	public function &__get($name)
	{
		self::$__data[self::$__response_id__][] = $name;
		return $this;
	}

	/**
	 * Response data getter
	 *
	 * @param boolean $format_data
	 * @return mixed (array when not formatting, else string)
	 */
	final public static function __getData__($format_data = false)
	{
		if(self::$__data_response !== null) // data only response
		{
			return $format_data ? json_encode(self::$__data_response) : self::$__data_response;
		}
		else // script response
		{
			if(!$format_data)
			{
				return self::$__data;
			}

			$res = '';

			foreach(self::$__data as $k => $v)
			{
				$res .= implode('.', $v) . ';';
			}

			return $res;
		}
	}

	/**
	 * Name/value pair data setter (ex: ->innerHTML = 'x')
	 *
	 * @param string $name
	 * @param mixed $value
	 * @return void
	 */
	public function __set($name, $value)
	{
		self::$__data[self::$__response_id__][] = $name . '=' . json_encode($value);
	}

	/**
	 * Response data setter (when JSON response only)
	 *
	 * @param array $data
	 * @return void
	 */
	final public static function __setData__(array $data)
	{
		self::$__data_response = $data;
	}

	/**
	 * Script string setter
	 *
	 * @param string $script (ex: 'alert("test")')
	 * @return void
	 */
	final public static function script($script)
	{
		// rm ';', script is auto closed
		self::$__data[self::$__response_id__][] = rtrim($script, ';');
		self::$__response_id__++;
	}
}


text:
fatcontroller
=============

**js pub sub, with post bindings & stack tracing**

### Install

`bower install --save fatcontroller`

### Dependencies

- Lodash/Underscore

### Basic Usage

```javascript
fc.on('some:event', function() {
  // ...
});

fc.trigger('some:event');
```

### Documentation by example

```javascript
// Single use bindings are available

fc.once('some:event', someFunction);

// Post bindings can be bound and triggered after an event occurred.
// This is useful when asynchronous modules depend on state changes.

// Something denotes a state change
fc.trigger('some:event');

// The binding will immediately be called as the event has occurred
fc.after('some:event', someFunction);

// Post bindings can also defer the callback until multiple events have
// all occurred
fc.afterAll(['some:event', 'another:event', 'yet:another:event'], someFunction);

// Debug tracing will trace and log all the actions that are
// being sent through fatcontroller

fc.debug = true;

// Logs a stack trace indicating where the binding originated from
fc.on('some:event', someFunction);

// Logs a stack trace indicating where the event was triggered
fc.trigger('some:event');

// Bindings can be removed by event name and callback
fc.off('some:event');
fc.off('some:event', someFunction);
```


text:
//
// Copyright (C) 2016 OpenSim Ltd.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, see http://www.gnu.org/licenses/.
//

#include "inet/linklayer/ieee80211/mac/contract/IRecipientQoSAckPolicy.h"
#include "inet/linklayer/ieee80211/mac/contract/IRecipientBlockAckAgreementHandler.h"
#include "inet/linklayer/ieee80211/mac/contract/IProcedureCallback.h"
#include "inet/linklayer/ieee80211/mac/Ieee80211Frame_m.h"

#ifndef __INET_IRECIPIENTBLOCKACKPROCEDURE_H
#define __INET_IRECIPIENTBLOCKACKPROCEDURE_H

namespace inet {
namespace ieee80211 {

class INET_API IRecipientBlockAckProcedure
{
    public:
        virtual ~IRecipientBlockAckProcedure() { };

        virtual void processReceivedBlockAckReq(Ieee80211BlockAckReq *blockAckReq, IRecipientQoSAckPolicy *ackPolicy, IRecipientBlockAckAgreementHandler* blockAckAgreementHandler, IProcedureCallback *callback) = 0;
        virtual void processTransmittedBlockAck(Ieee80211BlockAck *blockAck) = 0;
};

} /* namespace ieee80211 */
} /* namespace inet */

#endif // ifndef __INET_IRECIPIENTBLOCKACKPROCEDURE_H


text:
package pointclass;

import pointclass.NamedPoint;
import pointclass.Point;

class Main {
    public static void main(String[] args) {
        Point point = new Point(1, 2);

        System.out.println(point.x);
        System.out.println(point.y);

        NamedPoint named = new NamedPoint(3, 4, "My Point");

        System.out.println(named.getLabel());
    }
}


text:
namespace ash {

namespace internal {
class RootWindowEventFilter;
}

// WindowResizer is used by ToplevelWindowEventFilter to handle dragging, moving
// or resizing a window. All coordinates passed to this are in the parent
// windows coordiantes.
class ASH_EXPORT DefaultWindowResizer : public WindowResizer {
 public:
  virtual ~DefaultWindowResizer();

  // Creates a new DefaultWindowResizer. The caller takes ownership of the
  // returned object. Returns NULL if not resizable.
  static DefaultWindowResizer* Create(aura::Window* window,
                                      const gfx::Point& location,
                                      int window_component);

  // Returns true if the drag will result in changing the window in anyway.
  bool is_resizable() const { return details_.is_resizable; }

  bool changed_size() const {
    return !(details_.bounds_change & kBoundsChange_Repositions);
  }
  aura::Window* target_window() const { return details_.window; }

  // WindowResizer overides:
  virtual void Drag(const gfx::Point& location, int event_flags) OVERRIDE;
  virtual void CompleteDrag(int event_flags) OVERRIDE;
  virtual void RevertDrag() OVERRIDE;

 private:
  explicit DefaultWindowResizer(const Details& details);

  const Details details_;

  // Set to true once Drag() is invoked and the bounds of the window change.
  bool did_move_or_resize_;

  internal::RootWindowEventFilter* root_filter_;

  DISALLOW_COPY_AND_ASSIGN(DefaultWindowResizer);
};

}  // namespace aura

#endif  // ASH_WM_DEFAULT_WINDOW_RESIZER_H_


text:
module Elasticsearch
  module API
    module Actions

      # Update a document without sending the whole document in the request ("partial update").
      #
      # Send either a partial document (`doc` ) which will be deeply merged into an existing document,
      # or a `script`, which will update the document content, in the `:body` argument.
      #
      # The partial update operation allows you to limit the amount of data you send over the wire and
      # reduces the chance of failed updates due to conflict.
      #
      # Specify the `:version` and `:retry_on_conflict` arguments to balance convenience and consistency.
      #
      # @example Update document _title_ using partial `doc`-ument
      #
      #     client.update index: 'myindex', type: 'mytype', id: '1',
      #                   body: { doc: { title: 'Updated' } }
      #
      # @example Add a tag to document `tags` property using a `script`
      #
      #     client.update index: 'myindex', type: 'mytype', id: '1',
      #                   body: { script: 'ctx._source.tags += tag', params: { tag: 'x' } }
      #
      # @example Increment a document counter by 1 _or_ initialize it, when the document does not exist
      #
      #     client.update index: 'myindex', type: 'mytype', id: '666',
      #                   body: { script: 'ctx._source.counter += 1', upsert: { counter: 1 } }
      #
      # @example Delete a document if it's tagged "to-delete"
      #
      #     client.update index: 'myindex', type: 'mytype', id: '1',
      #                   body: { script: 'ctx._source.tags.contains(tag) ? ctx.op = "delete" : ctx.op = "none"',
      #                           params: { tag: 'to-delete' } }
      #
      # @option arguments [String] :id Document ID (*Required*)
      # @option arguments [Number,List] :ignore The list of HTTP errors to ignore; only `404` supported at the moment
      # @option arguments [String] :index The name of the index (*Required*)
      # @option arguments [String] :type The type of the document (*Required*)
      # @option arguments [Hash] :body The request definition using either `script` or partial `doc` (*Required*)
      # @option arguments [String] :consistency Explicit write consistency setting for the operation
      #                                         (options: one, quorum, all)
      # @option arguments [List] :fields A comma-separated list of fields to return in the response
      # @option arguments [String] :lang The script language (default: mvel)
      # @option arguments [String] :parent ID of the parent document
      # @option arguments [String] :percolate Perform percolation during the operation;
      #                                       use specific registered query name, attribute, or wildcard
      # @option arguments [Boolean] :refresh Refresh the index after performing the operation
      # @option arguments [String] :replication Specific replication type (options: sync, async)
      # @option arguments [Number] :retry_on_conflict Specify how many times should the operation be retried
      #                                               when a conflict occurs (default: 0)
      # @option arguments [String] :routing Specific routing value
      # @option arguments [String] :script The URL-encoded script definition (instead of using request body)
      # @option arguments [Time] :timeout Explicit operation timeout
      # @option arguments [Time] :timestamp Explicit timestamp for the document
      # @option arguments [Duration] :ttl Expiration time for the document
      # @option arguments [Number] :version Explicit version number for concurrency control
      # @option arguments [Number] :version_type Explicit version number for concurrency control
      #
      # @since 0.20
      #
      # @see http://elasticsearch.org/guide/reference/api/update/
      #
      def update(arguments={})
        raise ArgumentError, "Required argument 'index' missing" unless arguments[:index]
        raise ArgumentError, "Required argument 'type' missing"  unless arguments[:type]
        raise ArgumentError, "Required argument 'id' missing"    unless arguments[:id]

        valid_params = [
          :consistency,
          :fields,
          :lang,
          :parent,
          :percolate,
          :refresh,
          :replication,
          :retry_on_conflict,
          :routing,
          :script,
          :timeout,
          :timestamp,
          :ttl,
          :version,
          :version_type ]

        method = HTTP_POST
        path   = Utils.__pathify Utils.__escape(arguments[:index]),
                                 Utils.__escape(arguments[:type]),
                                 Utils.__escape(arguments[:id]),
                                 '_update'

        params = Utils.__validate_and_extract_params arguments, valid_params
        body   = arguments[:body]

        params[:fields] = Utils.__listify(params[:fields]) if params[:fields]

        perform_request(method, path, params, body).body

      rescue Exception => e
        # NOTE: Use exception name, not full class in Elasticsearch::Client to allow client plugability
        if Array(arguments[:ignore]).include?(404) && e.class.to_s =~ /NotFound/; false
        else raise(e)
        end
      end
    end
  end
end