text:
"""passlib.handlers.cisco - Cisco password hashes"""
#=============================================================================
# imports
#=============================================================================
# core
from binascii import hexlify, unhexlify
from hashlib import md5
import logging; log = logging.getLogger(__name__)
from warnings import warn
# site
# pkg
from passlib.utils import h64, right_pad_string, to_unicode
from passlib.utils.compat import b, bascii_to_str, bytes, unicode, u, join_byte_values, \
             join_byte_elems, byte_elem_value, iter_byte_values, uascii_to_str, str_to_uascii
import passlib.utils.handlers as uh
# local
__all__ = [
    "cisco_pix",
    "cisco_type7",
]

#=============================================================================
# cisco pix firewall hash
#=============================================================================
class cisco_pix(uh.HasUserContext, uh.StaticHandler):
    """This class implements the password hash used by Cisco PIX firewalls,
    and follows the :ref:`password-hash-api`.
    It does a single round of hashing, and relies on the username
    as the salt.

    The :meth:`~passlib.ifc.PasswordHash.encrypt`, :meth:`~passlib.ifc.PasswordHash.genhash`, and :meth:`~passlib.ifc.PasswordHash.verify` methods
    have the following extra keyword:

    :type user: str
    :param user:
        String containing name of user account this password is associated with.

        This is *required* in order to correctly hash passwords associated
        with a user account on the Cisco device, as it is used to salt
        the hash.

        Conversely, this *must* be omitted or set to ``""`` in order to correctly
        hash passwords which don't have an associated user account
        (such as the "enable" password).
    """
    #===================================================================
    # class attrs
    #===================================================================
    name = "cisco_pix"
    checksum_size = 16
    checksum_chars = uh.HASH64_CHARS

    #===================================================================
    # methods
    #===================================================================
    def _calc_checksum(self, secret):
        if isinstance(secret, unicode):
            # XXX: no idea what unicode policy is, but all examples are
            # 7-bit ascii compatible, so using UTF-8
            secret = secret.encode("utf-8")

        user = self.user
        if user:
            # not positive about this, but it looks like per-user
            # accounts use the first 4 chars of the username as the salt,
            # whereas global "enable" passwords don't have any salt at all.
            if isinstance(user, unicode):
                user = user.encode("utf-8")
            secret += user[:4]

        # null-pad or truncate to 16 bytes
        secret = right_pad_string(secret, 16)

        # md5 digest
        hash = md5(secret).digest()

        # drop every 4th byte
        hash = join_byte_elems(c for i,c in enumerate(hash) if i & 3 < 3)

        # encode using Hash64
        return h64.encode_bytes(hash).decode("ascii")

    #===================================================================
    # eoc
    #===================================================================

#=============================================================================
# type 7
#=============================================================================
class cisco_type7(uh.GenericHandler):
    """This class implements the Type 7 password encoding used by Cisco IOS,
    and follows the :ref:`password-hash-api`.
    It has a simple 4-5 bit salt, but is nonetheless a reversible encoding
    instead of a real hash.

    The :meth:`~passlib.ifc.PasswordHash.encrypt` and :meth:`~passlib.ifc.PasswordHash.genhash` methods
    have the following optional keywords:

    :type salt: int
    :param salt:
        This may be an optional salt integer drawn from ``range(0,16)``.
        If omitted, one will be chosen at random.

    :type relaxed: bool
    :param relaxed:
        By default, providing an invalid value for one of the other
        keywords will result in a :exc:`ValueError`. If ``relaxed=True``,
        and the error can be corrected, a :exc:`~passlib.exc.PasslibHashWarning`
        will be issued instead. Correctable errors include
        ``salt`` values that are out of range.

    Note that while this class outputs digests in upper-case hexadecimal,
    it will accept lower-case as well.

    This class also provides the following additional method:

    .. automethod:: decode
    """
    #===================================================================
    # class attrs
    #===================================================================
    name = "cisco_type7"
    setting_kwds = ("salt",)
    checksum_chars = uh.UPPER_HEX_CHARS

    # NOTE: encoding could handle max_salt_value=99, but since key is only 52
    #       chars in size, not sure what appropriate behavior is for that edge case.
    min_salt_value = 0
    max_salt_value = 52

    #===================================================================
    # methods
    #===================================================================
    @classmethod
    def genconfig(cls):
        return None

    @classmethod
    def genhash(cls, secret, config):
        # special case to handle ``config=None`` in same style as StaticHandler
        if config is None:
            return cls.encrypt(secret)
        else:
            return super(cisco_type7, cls).genhash(secret, config)

    @classmethod
    def from_string(cls, hash):
        hash = to_unicode(hash, "ascii", "hash")
        if len(hash) < 2:
            raise uh.exc.InvalidHashError(cls)
        salt = int(hash[:2]) # may throw ValueError
        return cls(salt=salt, checksum=hash[2:].upper())

    def __init__(self, salt=None, **kwds):
        super(cisco_type7, self).__init__(**kwds)
        self.salt = self._norm_salt(salt)

    def _norm_salt(self, salt):
        """the salt for this algorithm is an integer 0-52, not a string"""
        # XXX: not entirely sure that values >15 are valid, so for
        # compatibility we don't output those values, but we do accept them.
        if salt is None:
            if self.use_defaults:
                salt = self._generate_salt()
            else:
                raise TypeError("no salt specified")
        if not isinstance(salt, int):
            raise uh.exc.ExpectedTypeError(salt, "integer", "salt")
        if salt < 0 or salt > self.max_salt_value:
            msg = "salt/offset must be in 0..52 range"
            if self.relaxed:
                warn(msg, uh.PasslibHashWarning)
                salt = 0 if salt < 0 else self.max_salt_value
            else:
                raise ValueError(msg)
        return salt

    def _generate_salt(self):
        return uh.rng.randint(0, 15)

    def to_string(self):
        return "%02d%s" % (self.salt, uascii_to_str(self.checksum))

    def _calc_checksum(self, secret):
        # XXX: no idea what unicode policy is, but all examples are
        # 7-bit ascii compatible, so using UTF-8
        if isinstance(secret, unicode):
            secret = secret.encode("utf-8")
        return hexlify(self._cipher(secret, self.salt)).decode("ascii").upper()

    @classmethod
    def decode(cls, hash, encoding="utf-8"):
        """decode hash, returning original password.

        :arg hash: encoded password
        :param encoding: optional encoding to use (defaults to ``UTF-8``).
        :returns: password as unicode
        """
        self = cls.from_string(hash)
        tmp = unhexlify(self.checksum.encode("ascii"))
        raw = self._cipher(tmp, self.salt)
        return raw.decode(encoding) if encoding else raw

    # type7 uses a xor-based vingere variant, using the following secret key:
    _key = u("dsfd;kfoA,.iyewrkldJKDHSUBsgvca69834ncxv9873254k;fg87")

    @classmethod
    def _cipher(cls, data, salt):
        """xor static key against data - encrypts & decrypts"""
        key = cls._key
        key_size = len(key)
        return join_byte_values(
            value ^ ord(key[(salt + idx) % key_size])
            for idx, value in enumerate(iter_byte_values(data))
        )

#=============================================================================
# eof
#=============================================================================


text:
'use strict';

const Action = require('./Action');
const { Events } = require('../../util/Constants');

class GuildIntegrationsUpdate extends Action {
  handle(data) {
    const client = this.client;
    const guild = client.guilds.get(data.guild_id);
    /**
     * Emitted whenever a guild integration is updated
     * @event Client#guildIntegrationsUpdate
     * @param {Guild} guild The guild whose integrations were updated
     */
    if (guild) client.emit(Events.GUILD_INTEGRATIONS_UPDATE, guild);
  }
}

module.exports = GuildIntegrationsUpdate;

redpajama_set_name: RedPajamaGithub


text:
/** @jsx React.DOM */

var React = require('react');
var TweetsApp = require('./components/TweetsApp.react');

var initialState = JSON.parse(document.getElementById('initial-state').innerHTML);

// Render the app (picking up where React left off on the server)
React.renderComponent(
  <TweetsApp tweets={initialState} />,
  document.getElementById('react-app')
);


text:
if defined?($paned2_demo) && $paned2_demo
  $paned2_demo.destroy
  $paned2_demo = nil
end

$paned2_demo = TkToplevel.new {|w|
  title("Vertical Paned Window Demonstration")
  iconname("paned2")
  positionWindow(w)
}

base_frame = TkFrame.new($paned2_demo).pack(:fill=>:both, :expand=>true)

TkLabel.new(base_frame,
            :font=>$font, :wraplength=>'4i', :justify=>:left,
            :text=><<EOL).pack(:side=>:top)
The sash between the two scrolled windows below can be used to divide the area between them.  Use the left mouse button to resize without redrawing by just moving the sash, and use the middle mouse button to resize opaquely (always redrawing the windows in each position.)
If your Tk library linked to Ruby doesn't include a 'panedwindow', this demo doesn't work. Please use later version of Tk which supports a 'panedwindow'.
EOL

# The bottom buttons
TkFrame.new(base_frame){|f|
  pack(:side=>:bottom, :fill=>:x, :pady=>'2m')

  TkButton.new(f, :text=>'Dismiss', :width=>15, :command=>proc{
                 $paned2_demo.destroy
                 $paned2_demo = nil
               }).pack(:side=>:left, :expand=>true)

  TkButton.new(f, :text=>'See Code', :width=>15, :command=>proc{
                 showCode 'paned2'
               }).pack(:side=>:left, :expand=>true)
}

paneList = TkVariable.new  # define as normal variable (not array)
paneList.value = [         # ruby's array --> tcl's list
    'List of Ruby/Tk Widgets',
    'TkButton',
    'TkCanvas',
    'TkCheckbutton',
    'TkEntry',
    'TkFrame',
    'TkLabel',
    'TkLabelframe',
    'TkListbox',
    'TkMenu',
    'TkMenubutton',
    'TkMessage',
    'TkPanedwindow',
    'TkRadiobutton',
    'TkScale',
    'TkScrollbar',
    'TkSpinbox',
    'TkText',
    'TkToplevel'
]

# Create the pane itself
TkPanedwindow.new(base_frame, :orient=>:vertical){|f|
  pack(:side=>:top, :expand=>true, :fill=>:both, :pady=>2, :padx=>'2m')

  add(TkFrame.new(f){|paned2_top|
        TkListbox.new(paned2_top, :listvariable=>paneList) {
          # Invert the first item to highlight it
          itemconfigure(0, :background=>self.cget(:foreground),
                           :foreground=>self.cget(:background) )
          yscrollbar(TkScrollbar.new(paned2_top).pack(:side=>:right,
                                                      :fill=>:y))
          pack(:fill=>:both, :expand=>true)
        }
      },

      TkFrame.new(f, :height=>120) {|paned2_bottom|
        # The bottom window is a text widget with scrollbar
        paned2_xscr = TkScrollbar.new(paned2_bottom)
        paned2_yscr = TkScrollbar.new(paned2_bottom)
        paned2_text = TkText.new(paned2_bottom, :width=>30, :wrap=>:non) {
          insert('1.0', "This is just a normal text widget")
          xscrollbar(paned2_xscr)
          yscrollbar(paned2_yscr)
        }
        Tk.grid(paned2_text, paned2_yscr, :sticky=>'nsew')
        Tk.grid(paned2_xscr, :sticky=>'nsew')
        TkGrid.columnconfigure(paned2_bottom, 0, :weight=>1)
        TkGrid.rowconfigure(paned2_bottom, 0, :weight=>1)
      } )
}


text:
namespace Sitecore.FakeDb.Links
{
  using Sitecore.Common;
  using Sitecore.Links;

  public class LinkProviderSwitcher : Switcher<LinkProvider>
  {
#if SC80 || SC81
    private readonly Sitecore.Links.LinkProviderSwitcher providerSwitcher;
#endif

    public LinkProviderSwitcher(LinkProvider linkProviderToSwitchTo)
      : base(linkProviderToSwitchTo)
    {
#if SC80 || SC81
      this.providerSwitcher = new Sitecore.Links.LinkProviderSwitcher("switcher");
#endif
    }

    public override void Dispose()
    {
#if SC80 || SC81
      this.providerSwitcher.Dispose();
#endif
      base.Dispose();
    }
  }
}


text:
require 'spec_helper'
require 'sunspot/rails/spec_helper'

describe ManifestationCheckoutStatsController do
  fixtures :all
  disconnect_sunspot

  describe "GET index" do
    before(:each) do
      FactoryGirl.create(:manifestation_checkout_stat)
    end

    describe "When logged in as Administrator" do
      before(:each) do
        sign_in FactoryGirl.create(:admin)
      end

      it "assigns all manifestation_checkout_stats as @manifestation_checkout_stats" do
        get :index
        assigns(:manifestation_checkout_stats).should eq(ManifestationCheckoutStat.all)
      end
    end

    describe "When logged in as Librarian" do
      before(:each) do
        sign_in FactoryGirl.create(:librarian)
      end

      it "assigns all manifestation_checkout_stats as @manifestation_checkout_stats" do
        get :index
        assigns(:manifestation_checkout_stats).should eq(ManifestationCheckoutStat.all)
      end
    end

    describe "When logged in as User" do
      before(:each) do
        sign_in FactoryGirl.create(:user)
      end

      it "assigns all manifestation_checkout_stats as @manifestation_checkout_stats" do
        get :index
        assigns(:manifestation_checkout_stats).should eq(ManifestationCheckoutStat.all)
      end
    end

    describe "When not logged in" do
      it "should not assign manifestation_checkout_stats as @manifestation_checkout_stats" do
        get :index
        assigns(:manifestation_checkout_stats).should eq(ManifestationCheckoutStat.all)
      end
    end
  end

  describe "GET show" do
    describe "When logged in as Administrator" do
      before(:each) do
        sign_in FactoryGirl.create(:admin)
      end

      it "assigns the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
        manifestation_checkout_stat = FactoryGirl.create(:manifestation_checkout_stat)
        get :show, :id => manifestation_checkout_stat.id
        assigns(:manifestation_checkout_stat).should eq(manifestation_checkout_stat)
      end
    end

    describe "When logged in as Librarian" do
      before(:each) do
        sign_in FactoryGirl.create(:librarian)
      end

      it "assigns the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
        manifestation_checkout_stat = FactoryGirl.create(:manifestation_checkout_stat)
        get :show, :id => manifestation_checkout_stat.id
        assigns(:manifestation_checkout_stat).should eq(manifestation_checkout_stat)
      end
    end

    describe "When logged in as User" do
      before(:each) do
        sign_in FactoryGirl.create(:user)
      end

      it "assigns the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
        manifestation_checkout_stat = FactoryGirl.create(:manifestation_checkout_stat)
        get :show, :id => manifestation_checkout_stat.id
        assigns(:manifestation_checkout_stat).should eq(manifestation_checkout_stat)
      end
    end

    describe "When not logged in" do
      it "assigns the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
        manifestation_checkout_stat = FactoryGirl.create(:manifestation_checkout_stat)
        get :show, :id => manifestation_checkout_stat.id
        assigns(:manifestation_checkout_stat).should eq(manifestation_checkout_stat)
      end
    end
  end

  describe "GET new" do
    describe "When logged in as Administrator" do
      before(:each) do
        sign_in FactoryGirl.create(:admin)
      end

      it "assigns the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
        get :new
        assigns(:manifestation_checkout_stat).should_not be_valid
      end
    end

    describe "When logged in as Librarian" do
      before(:each) do
        sign_in FactoryGirl.create(:librarian)
      end

      it "assigns the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
        get :new
        assigns(:manifestation_checkout_stat).should_not be_valid
      end
    end

    describe "When logged in as User" do
      before(:each) do
        sign_in FactoryGirl.create(:user)
      end

      it "should not assign the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
        get :new
        assigns(:manifestation_checkout_stat).should_not be_valid
        response.should be_forbidden
      end
    end

    describe "When not logged in" do
      it "should not assign the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
        get :new
        assigns(:manifestation_checkout_stat).should_not be_valid
        response.should redirect_to(new_user_session_url)
      end
    end
  end

  describe "GET edit" do
    describe "When logged in as Administrator" do
      before(:each) do
        sign_in FactoryGirl.create(:admin)
      end

      it "assigns the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
        manifestation_checkout_stat = FactoryGirl.create(:manifestation_checkout_stat)
        get :edit, :id => manifestation_checkout_stat.id
        assigns(:manifestation_checkout_stat).should eq(manifestation_checkout_stat)
      end
    end

    describe "When logged in as Librarian" do
      before(:each) do
        sign_in FactoryGirl.create(:librarian)
      end

      it "assigns the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
        manifestation_checkout_stat = FactoryGirl.create(:manifestation_checkout_stat)
        get :edit, :id => manifestation_checkout_stat.id
        assigns(:manifestation_checkout_stat).should eq(manifestation_checkout_stat)
      end
    end

    describe "When logged in as User" do
      before(:each) do
        sign_in FactoryGirl.create(:user)
      end

      it "assigns the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
        manifestation_checkout_stat = FactoryGirl.create(:manifestation_checkout_stat)
        get :edit, :id => manifestation_checkout_stat.id
        response.should be_forbidden
      end
    end

    describe "When not logged in" do
      it "should not assign the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
        manifestation_checkout_stat = FactoryGirl.create(:manifestation_checkout_stat)
        get :edit, :id => manifestation_checkout_stat.id
        response.should redirect_to(new_user_session_url)
      end
    end
  end

  describe "POST create" do
    before(:each) do
      @attrs = FactoryGirl.attributes_for(:manifestation_checkout_stat)
      @invalid_attrs = {:start_date => ''}
    end

    describe "When logged in as Administrator" do
      before(:each) do
        sign_in FactoryGirl.create(:admin)
      end

      describe "with valid params" do
        it "assigns a newly created manifestation_checkout_stat as @manifestation_checkout_stat" do
          post :create, :manifestation_checkout_stat => @attrs
          assigns(:manifestation_checkout_stat).should be_valid
        end

        it "redirects to the created manifestation_checkout_stat" do
          post :create, :manifestation_checkout_stat => @attrs
          response.should redirect_to(manifestation_checkout_stat_url(assigns(:manifestation_checkout_stat)))
        end
      end

      describe "with invalid params" do
        it "assigns a newly created but unsaved manifestation_checkout_stat as @manifestation_checkout_stat" do
          post :create, :manifestation_checkout_stat => @invalid_attrs
          assigns(:manifestation_checkout_stat).should_not be_valid
        end

        it "re-renders the 'new' template" do
          post :create, :manifestation_checkout_stat => @invalid_attrs
          response.should render_template("new")
        end
      end
    end

    describe "When logged in as Librarian" do
      before(:each) do
        sign_in FactoryGirl.create(:librarian)
      end

      describe "with valid params" do
        it "assigns a newly created manifestation_checkout_stat as @manifestation_checkout_stat" do
          post :create, :manifestation_checkout_stat => @attrs
          assigns(:manifestation_checkout_stat).should be_valid
        end

        it "redirects to the created manifestation_checkout_stat" do
          post :create, :manifestation_checkout_stat => @attrs
          response.should redirect_to(manifestation_checkout_stat_url(assigns(:manifestation_checkout_stat)))
        end
      end

      describe "with invalid params" do
        it "assigns a newly created but unsaved manifestation_checkout_stat as @manifestation_checkout_stat" do
          post :create, :manifestation_checkout_stat => @invalid_attrs
          assigns(:manifestation_checkout_stat).should_not be_valid
        end

        it "re-renders the 'new' template" do
          post :create, :manifestation_checkout_stat => @invalid_attrs
          response.should render_template("new")
        end
      end
    end

    describe "When logged in as User" do
      before(:each) do
        sign_in FactoryGirl.create(:user)
      end

      describe "with valid params" do
        it "assigns a newly created manifestation_checkout_stat as @manifestation_checkout_stat" do
          post :create, :manifestation_checkout_stat => @attrs
          assigns(:manifestation_checkout_stat).should be_valid
        end

        it "should be forbidden" do
          post :create, :manifestation_checkout_stat => @attrs
          response.should be_forbidden
        end
      end

      describe "with invalid params" do
        it "assigns a newly created but unsaved manifestation_checkout_stat as @manifestation_checkout_stat" do
          post :create, :manifestation_checkout_stat => @invalid_attrs
          assigns(:manifestation_checkout_stat).should_not be_valid
        end

        it "should be forbidden" do
          post :create, :manifestation_checkout_stat => @invalid_attrs
          response.should be_forbidden
        end
      end
    end

    describe "When not logged in" do
      describe "with valid params" do
        it "assigns a newly created manifestation_checkout_stat as @manifestation_checkout_stat" do
          post :create, :manifestation_checkout_stat => @attrs
          assigns(:manifestation_checkout_stat).should be_valid
        end

        it "should be forbidden" do
          post :create, :manifestation_checkout_stat => @attrs
          response.should redirect_to(new_user_session_url)
        end
      end

      describe "with invalid params" do
        it "assigns a newly created but unsaved manifestation_checkout_stat as @manifestation_checkout_stat" do
          post :create, :manifestation_checkout_stat => @invalid_attrs
          assigns(:manifestation_checkout_stat).should_not be_valid
        end

        it "should be forbidden" do
          post :create, :manifestation_checkout_stat => @invalid_attrs
          response.should redirect_to(new_user_session_url)
        end
      end
    end
  end

  describe "PUT update" do
    before(:each) do
      @manifestation_checkout_stat = FactoryGirl.create(:manifestation_checkout_stat)
      @attrs = FactoryGirl.attributes_for(:manifestation_checkout_stat)
      @invalid_attrs = {:start_date => ''}
    end

    describe "When logged in as Administrator" do
      before(:each) do
        sign_in FactoryGirl.create(:admin)
      end

      describe "with valid params" do
        it "updates the requested manifestation_checkout_stat" do
          put :update, :id => @manifestation_checkout_stat.id, :manifestation_checkout_stat => @attrs
        end

        it "assigns the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
          put :update, :id => @manifestation_checkout_stat.id, :manifestation_checkout_stat => @attrs
          assigns(:manifestation_checkout_stat).should eq(@manifestation_checkout_stat)
        end
      end

      describe "with invalid params" do
        it "assigns the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
          put :update, :id => @manifestation_checkout_stat.id, :manifestation_checkout_stat => @invalid_attrs
          response.should render_template("edit")
        end
      end
    end

    describe "When logged in as Librarian" do
      before(:each) do
        sign_in FactoryGirl.create(:librarian)
      end

      describe "with valid params" do
        it "updates the requested manifestation_checkout_stat" do
          put :update, :id => @manifestation_checkout_stat.id, :manifestation_checkout_stat => @attrs
        end

        it "assigns the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
          put :update, :id => @manifestation_checkout_stat.id, :manifestation_checkout_stat => @attrs
          assigns(:manifestation_checkout_stat).should eq(@manifestation_checkout_stat)
          response.should redirect_to(@manifestation_checkout_stat)
        end
      end

      describe "with invalid params" do
        it "assigns the manifestation_checkout_stat as @manifestation_checkout_stat" do
          put :update, :id => @manifestation_checkout_stat, :manifestation_checkout_stat => @invalid_attrs
          assigns(:manifestation_checkout_stat).should_not be_valid
        end

        it "re-renders the 'edit' template" do
          put :update, :id => @manifestation_checkout_stat, :manifestation_checkout_stat => @invalid_attrs
          response.should render_template("edit")
        end
      end
    end

    describe "When logged in as User" do
      before(:each) do
        sign_in FactoryGirl.create(:user)
      end

      describe "with valid params" do
        it "updates the requested manifestation_checkout_stat" do
          put :update, :id => @manifestation_checkout_stat.id, :manifestation_checkout_stat => @attrs
        end

        it "assigns the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
          put :update, :id => @manifestation_checkout_stat.id, :manifestation_checkout_stat => @attrs
          assigns(:manifestation_checkout_stat).should eq(@manifestation_checkout_stat)
          response.should be_forbidden
        end
      end

      describe "with invalid params" do
        it "assigns the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
          put :update, :id => @manifestation_checkout_stat.id, :manifestation_checkout_stat => @invalid_attrs
          response.should be_forbidden
        end
      end
    end

    describe "When not logged in" do
      describe "with valid params" do
        it "updates the requested manifestation_checkout_stat" do
          put :update, :id => @manifestation_checkout_stat.id, :manifestation_checkout_stat => @attrs
        end

        it "should be forbidden" do
          put :update, :id => @manifestation_checkout_stat.id, :manifestation_checkout_stat => @attrs
          response.should redirect_to(new_user_session_url)
        end
      end

      describe "with invalid params" do
        it "assigns the requested manifestation_checkout_stat as @manifestation_checkout_stat" do
          put :update, :id => @manifestation_checkout_stat.id, :manifestation_checkout_stat => @invalid_attrs
          response.should redirect_to(new_user_session_url)
        end
      end
    end
  end

  describe "DELETE destroy" do
    before(:each) do
      @manifestation_checkout_stat = FactoryGirl.create(:manifestation_checkout_stat)
    end

    describe "When logged in as Administrator" do
      before(:each) do
        sign_in FactoryGirl.create(:admin)
      end

      it "destroys the requested manifestation_checkout_stat" do
        delete :destroy, :id => @manifestation_checkout_stat.id
      end

      it "redirects to the manifestation_checkout_stats list" do
        delete :destroy, :id => @manifestation_checkout_stat.id
        response.should redirect_to(manifestation_checkout_stats_url)
      end
    end

    describe "When logged in as Librarian" do
      before(:each) do
        sign_in FactoryGirl.create(:librarian)
      end

      it "destroys the requested manifestation_checkout_stat" do
        delete :destroy, :id => @manifestation_checkout_stat.id
      end

      it "redirects to the manifestation_checkout_stats list" do
        delete :destroy, :id => @manifestation_checkout_stat.id
        response.should redirect_to(manifestation_checkout_stats_url)
      end
    end

    describe "When logged in as User" do
      before(:each) do
        sign_in FactoryGirl.create(:user)
      end

      it "destroys the requested manifestation_checkout_stat" do
        delete :destroy, :id => @manifestation_checkout_stat.id
      end

      it "should be forbidden" do
        delete :destroy, :id => @manifestation_checkout_stat.id
        response.should be_forbidden
      end
    end

    describe "When not logged in" do
      it "destroys the requested manifestation_checkout_stat" do
        delete :destroy, :id => @manifestation_checkout_stat.id
      end

      it "should be forbidden" do
        delete :destroy, :id => @manifestation_checkout_stat.id
        response.should redirect_to(new_user_session_url)
      end
    end
  end
end


text:
import { VNode } from '@cycle/dom';

export function getGameCard(vtree: VNode): VNode | undefined {
  return (vtree.children as VNode[] | undefined)?.[0];
}


text:
#include <vnl/vnl_cross.h>
#include <vnl/vnl_quaternion.h>

template< class ScalarType >
AstroStickModel< ScalarType >::AstroStickModel()
    : m_Diffusivity(0.001)
    , m_BValue(1000)
    , m_NumSticks(42)
    , m_RandomizeSticks(false)
{
    m_RandGen = ItkRandGenType::New();

    vnl_matrix_fixed<ScalarType,3,42>* sticks = itk::PointShell<42, vnl_matrix_fixed<ScalarType, 3, 42> >::DistributePointShell();
    for (int i=0; i<m_NumSticks; i++)
    {
        GradientType stick;
        stick[0] = sticks->get(0,i); stick[1] = sticks->get(1,i); stick[2] = sticks->get(2,i);
        stick.Normalize();
        m_Sticks.push_back(stick);
    }
}

template< class ScalarType >
AstroStickModel< ScalarType >::~AstroStickModel()
{

}

template< class ScalarType >
void AstroStickModel< ScalarType >::SetSeed(int s)
{
    m_RandGen->SetSeed(s);
}

template< class ScalarType >
ScalarType AstroStickModel< ScalarType >::SimulateMeasurement(int dir)
{
    ScalarType signal = 0;

    if (dir>=this->m_GradientList.size())
        return signal;

    ScalarType b = -m_BValue*m_Diffusivity;

    if (m_RandomizeSticks)
        m_NumSticks = 30 + m_RandGen->GetIntegerVariate()%31;

    GradientType g = this->m_GradientList[dir];
    ScalarType bVal = g.GetNorm(); bVal *= bVal;

    if (bVal>0.0001)
    {
        for (int j=0; j<m_NumSticks; j++)
        {
            ScalarType dot = 0;
            if(m_RandomizeSticks)
                dot = GetRandomDirection()*g;
            else
                dot = m_Sticks[j]*g;
            signal += exp( b*bVal*dot*dot );
        }
        signal /= m_NumSticks;
    }
    else
        signal = 1;

    return signal;
}

template< class ScalarType >
typename AstroStickModel< ScalarType >::GradientType AstroStickModel< ScalarType >::GetRandomDirection()
{
    GradientType vec;
    vec[0] = m_RandGen->GetNormalVariate();
    vec[1] = m_RandGen->GetNormalVariate();
    vec[2] = m_RandGen->GetNormalVariate();
    vec.Normalize();
    return vec;
}

template< class ScalarType >
typename AstroStickModel< ScalarType >::PixelType AstroStickModel< ScalarType >::SimulateMeasurement()
{
    PixelType signal;
    signal.SetSize(this->m_GradientList.size());
    ScalarType b = -m_BValue*m_Diffusivity;

    if (m_RandomizeSticks)
        m_NumSticks = 30 + m_RandGen->GetIntegerVariate()%31;

    for( unsigned int i=0; i<this->m_GradientList.size(); i++)
    {
        GradientType g = this->m_GradientList[i];
        ScalarType bVal = g.GetNorm(); bVal *= bVal;

        if (bVal>0.0001)
        {
            for (int j=0; j<m_NumSticks; j++)
            {
                ScalarType dot = 0;
                if(m_RandomizeSticks)
                    dot = GetRandomDirection()*g;
                else
                    dot = m_Sticks[j]*g;
                signal[i] += exp( b*bVal*dot*dot );
            }
            signal[i] /= m_NumSticks;
        }
        else
            signal[i] = 1;
    }

    return signal;
}


text:
This provider uses the [terraform-provider-xenorchestra](https://github.com/ddelnano/terraform-provider-xenorchestra). The terraformer provider was built by [Dom Del Nano](https://github.com/ddelnano) on behalf of [Vates SAS](https://vates.fr/) who is sponsoring Dom to work on the project.

Example:

```
## Warning! You should not expose your xenorchestra creds through your bash history. Export them to your shell in a safe way when doing this for real!

XOA_URL=ws://your-xenorchestra-domain XOA_USER=username XOA_PASSWORD=password terraformer import xenorchestra -r=acl
```

List of supported xenorchestra resources:

* `xenorchestra_acl`
* `xenorchestra_resource_set`


text:
0. Make sure you are on correct branch (for new micro (1.0.0 -> 1.1.0) versions create separate branch like 1.0.x)
0. Assuming SNAPSHOT version in pom.xml
0. Run "mvn release:clean release:prepare"
0. If successful run "mvn release:perform"
0. If build is successful, your new build should be available in maven central


text:
"use strict";

describeComponent('app/component_data/mail_items', function() {
  beforeEach(function() {
    this.setupComponent(
      {
        dataStore: {
          contacts: [
            {"id": "contact_3"},
            {"id": "contact_5"}
          ],
          mail: [
            {id: "mail_1", contact_id: "contact_3", subject:"blah", message: "blugh", folders: ['inbox']},
            {id: "mail_2", contact_id: "contact_5", subject:"blee", message: "blooo", folders: ['later']}
          ]
        }
      }
    );
  });

  it('serves mail items when requested', function() {
    spyOnEvent(document, 'dataMailItemsServed');
    this.component.trigger('uiMailItemsRequested', {folder: 'inbox'});
    expect('dataMailItemsServed').toHaveBeenTriggeredOn(document);
  });

  it('should collate items for given folder when assembleItems is invoked with folder', function() {
    var items = this.component.assembleItems('inbox');
    expect(items.length).toBe(1);
    items = this.component.assembleItems('sent');
    expect(items.length).toBe(0);
    items = this.component.assembleItems('later');
    expect(items.length).toBe(1);
  });

  it('serves mail items after refresh', function() {
    spyOnEvent(document, 'dataMailItemsServed');
    this.component.trigger('dataMailItemsRefreshRequested', {});
    expect('dataMailItemsServed').toHaveBeenTriggeredOn(document);
  });

});


text:
package com.dhian.customview;

import android.support.v7.widget.SwitchCompat;
import android.content.*;
import android.util.*;
import android.graphics.drawable.*;
import android.content.res.Resources;
import android.graphics.*;
import android.os.*;
import com.dhian.Utils;

public class CustomSwitchCompat extends SwitchCompat
{
	private int colorThumb;
	private SharedPreferences prefs;
	private String prefName = "custom_tema";

    public CustomSwitchCompat(final Context context, AttributeSet attrs) {
		super(context, attrs);

		prefs = getContext().getSharedPreferences(prefName, getContext().MODE_PRIVATE);
		colorThumb = prefs.getInt("warnaSwitch",Utils.setColor());
		context.registerReceiver((BroadcastReceiver) new BroadcastReceiver() {

										  public void onReceive(Context context2, Intent intent) {
											  colorThumb = intent.getIntExtra("warnaTema", Utils.setColor());
                                              setChecked(isChecked());
											  prefs = getContext().getSharedPreferences(prefName, getContext().MODE_PRIVATE);
											  SharedPreferences.Editor editor = prefs.edit();
											  editor.putInt("warnaSwitch", colorThumb);
											  editor.commit();
										  }
									  }, new IntentFilter("GANTI_TEMA"));

		setChecked(isChecked());

			}

	@Override
	public void setChecked(boolean checked) {
		super.setChecked(checked);
		changeColor(checked);
	}

	private void changeColor(boolean isChecked) {
		if (Build.VERSION.SDK_INT >= 16) {
			int thumbColor;
			int trackColor;

			if(isChecked) {
				thumbColor = colorThumb;
				trackColor = 80 * 0x01000000;
			} else {
				thumbColor = Color.argb(255, 236, 236, 236);
				trackColor = 0xff9e9e9e;
							}

			try {
				getThumbDrawable().setColorFilter(thumbColor, PorterDuff.Mode.MULTIPLY);
				getTrackDrawable().setColorFilter(trackColor+thumbColor, PorterDuff.Mode.MULTIPLY);

			}
			catch (NullPointerException e) {
				e.printStackTrace();
			}
		}
	}

}


text:
require 'test_helper'

module Shipit
  class RefreshStatusesJobTest < ActiveSupport::TestCase
    setup do
      @stack = shipit_stacks(:shipit)
      @job = RefreshStatusesJob.new
    end

    test "#perform call #refresh_statuses! on the last 30 commits of the stack" do
      Commit.any_instance.expects(:refresh_statuses!).times(@stack.commits.count)

      @job.perform(stack_id: @stack.id)
    end

    test "if :commit_id param is present only this commit is refreshed" do
      Commit.any_instance.expects(:refresh_statuses!).once

      @job.perform(stack_id: @stack.id, commit_id: shipit_commits(:first).id)
    end
  end
end


text:
package ru.job4j.dao;

import ru.job4j.dao.postgres.PostgresFactory;
import ru.job4j.dao.ram.RAMFactory;

/**
 * DAOFactory.
 *
 * @author Stanislav (376825@mail.ru)
 * @since 04.12.2017
 */
public abstract class DAOFactory {
    /**
     */
    public static final int RAM = 1;

    /**
     */
    public static final int POSTGRES = 2;

    /**
     * getDAOFactory.
     */
    public static DAOFactory getDAOFactory(int whichFactory) {
        switch (whichFactory) {
            case RAM:
                return new RAMFactory();
            case POSTGRES:
                return PostgresFactory.getInstance();
            default:
                return new RAMFactory();
        }
    }

    /**
     * getOrderDAO.
     */
    public abstract Order getOrderDAO();
}


text:
<!--
Description: item author maps to author_detail email if both name and email are given
Expect:      not bozo and entries[0]['author_detail']['email'] == 'me@example.com'
-->
<rss version="2.0">
<channel>
<item>
<author>me@example.com (Example editor)</author>
</item>
</channel>
</rss>


text:
import { Cursor } from 'ansi.js'
import { placeholder } from './constants'
import { RGB } from './types'

export function toFixed(value: number, precision: number) {
  const power = 10 ** precision
  return (Math.round(value * power) / power).toFixed(precision)
}

export function formatTime(ms: number) {
  return Number.isNaN(ms) || !Number.isFinite(ms)
    ? '0.0'
    : toFixed(ms / 1000, 1)
}

function lcFirst(str: string) {
  return str.charAt(0).toLowerCase() + str.substring(1)
}

export function ucFirst(str: string) {
  return str.charAt(0).toUpperCase() + str.substring(1)
}

export function repeatChar(char: string, count: number) {
  return new Array(count + 1).join(char)
}

export function parseMethod(cursor: Cursor, str: string) {
  const input = str.substring(1)
  return (
    parseColor(cursor, input) ||
    parseFont(cursor, input) ||
    parseGradient(input)
  )
}

export type BgMethod = { isBg: boolean; method: string; suffix: string }
export type FontMethod = { isFont: boolean; method: string; suffix: string }
export type GradientMethod = { method: 'gradient'; color1: RGB; color2: RGB }

function parseColor(cursor: Cursor, str: string): BgMethod | undefined {
  const match =
    str.match(/^(bgR|r)ed/) ||
    str.match(/^(bgB|b)lue/) ||
    str.match(/^(bgC|c)yan/) ||
    str.match(/^(bgG|g)rey/) ||
    str.match(/^(bgW|w)hite/) ||
    str.match(/^(bgB|b)lack/) ||
    str.match(/^(bgG|g)reen/) ||
    str.match(/^(bgY|y)ellow/) ||
    str.match(/^(bgM|m)agenta/) ||
    str.match(/^(bgB|b)right(Black|Red|Green|Yellow|Blue|Magenta|Cyan|White)/)

  if (match) {
    let method = match[0]
    const suffix = str.substring(method.length)
    const isBg = method.startsWith('bg')

    if (isBg) {
      method = lcFirst(method.substring(2))
    }

    if (typeof cursor[method as keyof Cursor] === 'function') {
      return {
        isBg,
        method,
        suffix,
      }
    }
  }
}

function parseFont(cursor: Cursor, str: string): FontMethod | undefined {
  const match = str.match(/^bold|italic|underline|inverse/)
  if (match) {
    const method = match[0]
    const suffix = str.substring(method.length)
    if (typeof cursor[method as keyof Cursor] === 'function') {
      return {
        isFont: true,
        method,
        suffix,
      }
    }
  }
}

export function parseGradient(str: string): GradientMethod | undefined {
  const match = str.match(/^\((.+),(.+)\)/)
  if (match) {
    const m1 = match[1].trim()
    const m2 = match[2].trim()

    const color1 = m1.startsWith('#') ? hex2rgb(m1) : name2rgb(m1)
    const color2 = m2.startsWith('#') ? hex2rgb(m2) : name2rgb(m2)

    if (color1 && color2) {
      return {
        method: 'gradient',
        color1,
        color2,
      }
    }
  }
}

export function interpolate(color1: RGB, color2: RGB, percent: number) {
  return {
    r: atPercent(color1.r, color2.r, percent),
    g: atPercent(color1.g, color2.g, percent),
    b: atPercent(color1.b, color2.b, percent),
  }
}

function atPercent(a: number, b: number, percent: number) {
  return a + Math.round((b - a) * percent)
}

function hex2rgb(color: string): RGB {
  const c = color.substring(1)
  const r = c.substring(0, 2)
  const g = c.substring(2, 4)
  const b = c.substring(4, 6)

  return {
    r: parseInt(r, 16),
    g: parseInt(g, 16),
    b: parseInt(b, 16),
  }
}

function name2rgb(name: string) {
  const hex = {
    red: '#ff0000',
    blue: '#0000ff',
    cyan: '#00ffff',
    grey: '#808080',
    white: '#ffffff',
    black: '#000000',
    green: '#008000',
    yellow: '#ffff00',
    magenta: '#ff00ff',
  }[name]

  return hex ? hex2rgb(hex) : null
}

export function bleach(output: string) {
  return (
    output
      .replace(/\.(bgR|r)ed/g, '')
      .replace(/\.(bgB|b)lue/g, '')
      .replace(/\.(bgC|c)yan/g, '')
      .replace(/\.(bgG|g)rey/g, '')
      .replace(/\.(bgW|w)hite/g, '')
      .replace(/\.(bgB|b)lack/g, '')
      .replace(/\.(bgG|g)reen/g, '')
      .replace(/\.(bgY|y)ellow/g, '')
      .replace(/\.(bgM|m)agenta/g, '')
      // bright
      .replace(
        /\.(bgB|b)right(Black|Red|Green|Yellow|Blue|Magenta|Cyan|White)/g,
        '',
      )
      // font style
      .replace(/\.bold|italic|underline|inverse/g, '')
      // gradient
      .replace(/\.gradient\((.+),(.+)\)/g, '')
  )
}

export function combine(
  output: string,
  filled: string,
  blank: string,
  bare: boolean,
) {
  let bar = filled + blank
  if (!bare) {
    bar = bar || placeholder
    // eslint-disable-next-line no-param-reassign
    blank = blank || placeholder
    // eslint-disable-next-line no-param-reassign
    filled = filled || placeholder
  }

  return output
    .replace(/:filled/g, filled)
    .replace(/:blank/g, blank)
    .replace(/:bar/g, bar)
}

export function bareLength(output: string) {
  const str = output
    .replace(/:filled/g, '')
    .replace(/:blank/g, '')
    .replace(/:bar/g, '')

  return str.length
}


text:
struct animevent_t;
struct studiohdr_t;
class CStudioHdr;
struct mstudioseqdesc_t;

int ExtractBbox( CStudioHdr *pstudiohdr, int sequence, Vector& mins, Vector& maxs );

void IndexModelSequences( CStudioHdr *pstudiohdr );
void ResetActivityIndexes( CStudioHdr *pstudiohdr );
void VerifySequenceIndex( CStudioHdr *pstudiohdr );
int SelectWeightedSequence( CStudioHdr *pstudiohdr, int activity, int curSequence = -1 );
int SelectHeaviestSequence( CStudioHdr *pstudiohdr, int activity );
void SetEventIndexForSequence( mstudioseqdesc_t &seqdesc );
void BuildAllAnimationEventIndexes( CStudioHdr *pstudiohdr );
void ResetEventIndexes( CStudioHdr *pstudiohdr );

void GetEyePosition( CStudioHdr *pstudiohdr, Vector &vecEyePosition );

int LookupActivity( CStudioHdr *pstudiohdr, const char *label );
int LookupSequence( CStudioHdr *pstudiohdr, const char *label );

#define NOMOTION 99999
void GetSequenceLinearMotion( CStudioHdr *pstudiohdr, int iSequence, const float poseParameter[], Vector *pVec );

const char *GetSequenceName( CStudioHdr *pstudiohdr, int sequence );
const char *GetSequenceActivityName( CStudioHdr *pstudiohdr, int iSequence );

int GetSequenceFlags( CStudioHdr *pstudiohdr, int sequence );
int GetAnimationEvent( CStudioHdr *pstudiohdr, int sequence, animevent_t *pNPCEvent, float flStart, float flEnd, int index );
bool HasAnimationEventOfType( CStudioHdr *pstudiohdr, int sequence, int type );

int FindTransitionSequence( CStudioHdr *pstudiohdr, int iCurrentSequence, int iGoalSequence, int *piDir );

void SetBodygroup( CStudioHdr *pstudiohdr, int& body, int iGroup, int iValue );
int GetBodygroup( CStudioHdr *pstudiohdr, int body, int iGroup );

const char *GetBodygroupName( CStudioHdr *pstudiohdr, int iGroup );
int FindBodygroupByName( CStudioHdr *pstudiohdr, const char *name );
int GetBodygroupCount( CStudioHdr *pstudiohdr, int iGroup );
int GetNumBodyGroups( CStudioHdr *pstudiohdr );

int GetSequenceActivity( CStudioHdr *pstudiohdr, int sequence, int *pweight = NULL );

void GetAttachmentLocalSpace( CStudioHdr *pstudiohdr, int attachIndex, matrix3x4_t &pLocalToWorld );

float SetBlending( CStudioHdr *pstudiohdr, int sequence, int *pblendings, int iBlender, float flValue );

int FindHitboxSetByName( CStudioHdr *pstudiohdr, const char *name );
const char *GetHitboxSetName( CStudioHdr *pstudiohdr, int setnumber );
int GetHitboxSetCount( CStudioHdr *pstudiohdr );

#endif	//ANIMATION_H


text:
namespace ssf { namespace services { namespace admin {

template <typename Demux>
class CreateServiceRequest {
private:
  typedef std::map<std::string, std::string> Parameters;
public:
  CreateServiceRequest() {}

  CreateServiceRequest(uint32_t service_id)
    : service_id_(service_id) {}

  CreateServiceRequest(uint32_t service_id, Parameters parameters)
    : service_id_(service_id), parameters_(parameters) {}

  enum {
    command_id = 1,
    reply_id = 2
  };

  static void RegisterToCommandFactory() {
    CommandFactory<Demux>::RegisterOnReceiveCommand(command_id,
                                                    &CreateServiceRequest::OnReceive);
    CommandFactory<Demux>::RegisterOnReplyCommand(command_id,
                                                  &CreateServiceRequest::OnReply);
    CommandFactory<Demux>::RegisterReplyCommandIndex(command_id, reply_id);
  }

  static std::string OnReceive(boost::archive::text_iarchive& ar,
                        Demux* p_demux,
                        boost::system::error_code& ec) {
    CreateServiceRequest<Demux> request;

    try {
      ar >> request;
    } catch (const std::exception&) {
      return std::string();
    }

    auto p_service_factory =
      ServiceFactoryManager<Demux>::GetServiceFactory(p_demux);

    auto id = p_service_factory->CreateRunNewService(request.service_id(),
                                           request.parameters(),
                                           ec);

    BOOST_LOG_TRIVIAL(debug) << "service status: create "
      << "service unique id " << id
      << " - error_code " << ec.value();

    std::stringstream ss;
    std::string result;

    ss << id;
    ss >> result;

    return result;
  }

  static std::string OnReply(boost::archive::text_iarchive& ar,
                             Demux* p_demux,
                             const boost::system::error_code& ec,
                             std::string serialized_result) {
    CreateServiceRequest<Demux> request;

    try {
    ar >> request;
    } catch (const std::exception&) {
      return std::string();
    }

    ServiceStatus<Demux> reply(std::stoul(serialized_result),
                               request.service_id(),
                               ec.value(),
                               request.parameters());

    return reply.OnSending();
  }

  std::string OnSending() const {
    std::ostringstream ostrs;
    boost::archive::text_oarchive ar(ostrs);

    ar << *this;

    return ostrs.str();
  }

  uint32_t service_id() {
    return service_id_;
  }

  Parameters parameters() {
    return parameters_;
  }

  void add_parameter(const std::string& key, const std::string& value) {
    parameters_[key] = value;
  }

private:
  friend class boost::serialization::access;

  template <typename Archive>
  void serialize(Archive& ar, const unsigned int version) {
    ar & service_id_;
    ar & BOOST_SERIALIZATION_NVP(parameters_);
  }

private:
  uint32_t service_id_;
  Parameters parameters_;
};

}  // admin
}  // services
}  // ssf

#endif  // SSF_SERVICES_ADMIN_REQUESTS_CREATE_SERVICE_REQUEST_H_


text:
namespace spvtools {
namespace fuzz {
namespace {

TEST(TransformationAddEarlyTerminatorWrapperTest, NoVoidType) {
  std::string shader = R"(
               OpCapability Shader
               OpCapability Linkage
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpSource ESSL 320
  )";

  const auto env = SPV_ENV_UNIVERSAL_1_4;
  const auto consumer = nullptr;
  const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption);
  spvtools::ValidatorOptions validator_options;
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));
  TransformationContext transformation_context(
      MakeUnique<FactManager>(context.get()), validator_options);

  ASSERT_FALSE(
      TransformationAddEarlyTerminatorWrapper(100, 101, spv::Op::OpKill)
          .IsApplicable(context.get(), transformation_context));
}

TEST(TransformationAddEarlyTerminatorWrapperTest, NoVoidFunctionType) {
  std::string shader = R"(
               OpCapability Shader
               OpCapability Linkage
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpSource ESSL 320
          %2 = OpTypeVoid
  )";

  const auto env = SPV_ENV_UNIVERSAL_1_4;
  const auto consumer = nullptr;
  const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption);
  spvtools::ValidatorOptions validator_options;
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));
  TransformationContext transformation_context(
      MakeUnique<FactManager>(context.get()), validator_options);

  ASSERT_FALSE(
      TransformationAddEarlyTerminatorWrapper(100, 101, spv::Op::OpKill)
          .IsApplicable(context.get(), transformation_context));
}

TEST(TransformationAddEarlyTerminatorWrapperTest, BasicTest) {
  std::string shader = R"(
               OpCapability Shader
               OpExtension "SPV_KHR_terminate_invocation"
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Fragment %4 "main"
               OpExecutionMode %4 OriginUpperLeft
               OpSource ESSL 320
          %2 = OpTypeVoid
          %3 = OpTypeFunction %2
          %4 = OpFunction %2 None %3
          %5 = OpLabel
               OpReturn
               OpFunctionEnd
  )";

  const auto env = SPV_ENV_UNIVERSAL_1_5;
  const auto consumer = nullptr;
  const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption);
  spvtools::ValidatorOptions validator_options;
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));
  TransformationContext transformation_context(
      MakeUnique<FactManager>(context.get()), validator_options);

  ASSERT_FALSE(TransformationAddEarlyTerminatorWrapper(2, 101, spv::Op::OpKill)
                   .IsApplicable(context.get(), transformation_context));
  ASSERT_FALSE(TransformationAddEarlyTerminatorWrapper(100, 4, spv::Op::OpKill)
                   .IsApplicable(context.get(), transformation_context));
  ASSERT_FALSE(
      TransformationAddEarlyTerminatorWrapper(100, 100, spv::Op::OpKill)
          .IsApplicable(context.get(), transformation_context));

#ifndef NDEBUG
  ASSERT_DEATH(
      TransformationAddEarlyTerminatorWrapper(100, 101, spv::Op::OpReturn)
          .IsApplicable(context.get(), transformation_context),
      "Invalid opcode.");
#endif

  auto transformation1 =
      TransformationAddEarlyTerminatorWrapper(100, 101, spv::Op::OpKill);
  auto transformation2 =
      TransformationAddEarlyTerminatorWrapper(102, 103, spv::Op::OpUnreachable);
  auto transformation3 = TransformationAddEarlyTerminatorWrapper(
      104, 105, spv::Op::OpTerminateInvocation);

  ASSERT_TRUE(
      transformation1.IsApplicable(context.get(), transformation_context));
  ApplyAndCheckFreshIds(transformation1, context.get(),
                        &transformation_context);
  ASSERT_TRUE(
      transformation2.IsApplicable(context.get(), transformation_context));
  ApplyAndCheckFreshIds(transformation2, context.get(),
                        &transformation_context);
  ASSERT_TRUE(
      transformation3.IsApplicable(context.get(), transformation_context));
  ApplyAndCheckFreshIds(transformation3, context.get(),
                        &transformation_context);
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));

  std::string after_transformation = R"(
               OpCapability Shader
               OpExtension "SPV_KHR_terminate_invocation"
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Fragment %4 "main"
               OpExecutionMode %4 OriginUpperLeft
               OpSource ESSL 320
          %2 = OpTypeVoid
          %3 = OpTypeFunction %2
          %4 = OpFunction %2 None %3
          %5 = OpLabel
               OpReturn
               OpFunctionEnd
        %100 = OpFunction %2 None %3
        %101 = OpLabel
               OpKill
               OpFunctionEnd
        %102 = OpFunction %2 None %3
        %103 = OpLabel
               OpUnreachable
               OpFunctionEnd
        %104 = OpFunction %2 None %3
        %105 = OpLabel
               OpTerminateInvocation
               OpFunctionEnd
  )";
  ASSERT_TRUE(IsEqual(env, after_transformation, context.get()));
}

}  // namespace
}  // namespace fuzz
}  // namespace spvtools


text:
#pragma once

#include <pcl/pcl_config.h>
#ifdef HAVE_OPENNI2

#include <vector>
#include <limits>

namespace openni_wrapper
{
  /** \brief This class provides conversion of the openni 11-bit shift data to depth;
    */
  class PCL_EXPORTS ShiftToDepthConverter
  {
    public:
      /** \brief Constructor. */
      ShiftToDepthConverter () : init_(false) {}

      /** \brief Destructor. */
      virtual ~ShiftToDepthConverter () {};

      /** \brief This method generates a look-up table to convert openni shift values to depth
        */
      void
      generateLookupTable ()
      {
        // lookup of 11 bit shift values
        constexpr size_t table_size = 1<<10;

        lookupTable_.clear();
        lookupTable_.resize(table_size);

        // constants taken from openni driver
        constexpr int16_t nConstShift = 800;
        constexpr double nParamCoeff = 4.000000;
        constexpr double dPlanePixelSize = 0.104200;
        constexpr double nShiftScale = 10.000000;
        constexpr double dPlaneDsr = 120.000000;
        constexpr double dPlaneDcl = 7.500000;

        for (size_t i=0; i<table_size; ++i)
        {
          // shift to depth calculation from opnni
          double dFixedRefX = (static_cast<double>(i - nConstShift) / nParamCoeff)-0.375;
          double dMetric = dFixedRefX * dPlanePixelSize;
          lookupTable_[i] = static_cast<float>((nShiftScale * ((dMetric * dPlaneDsr / (dPlaneDcl - dMetric)) + dPlaneDsr) ) / 1000.0f);
        }

        init_ = true;
      }

      /** \brief Generate a look-up table for converting openni shift values to depth
         */
      inline float
      shiftToDepth (uint16_t shift_val)
      {
        assert (init_);

        static const float bad_point = std::numeric_limits<float>::quiet_NaN ();

        float ret = bad_point;

        // lookup depth value in shift lookup table
        if (shift_val<lookupTable_.size())
          ret = lookupTable_[shift_val];

        return ret;
      }

      inline bool isInitialized() const
      {
        return init_;
      }

    protected:
      std::vector<float> lookupTable_;
      bool init_;
  } ;
}
#endif


text:
var testosterone = require('testosterone')({title: 'models/facebook'})
  , assert = testosterone.assert
  , querystring = require('querystring')
  , facebook_client = require('../')
  , _access_token = '2227470867|2.AQCFxOjuFBkTnTM0.3600.1307314800.0-758964068|VAwjSdyKcGET3LwLWUBdAjwgZnA'
  , _id = '167896963275275'
  , _callback = 'example.com/done';

testosterone

  .add('`getAuthorizeUrl`', function (done) {
    var url = facebook_client.getAuthorizeUrl({ client_id: _id
                                              , redirect_uri: _callback
                                              , scope: 'offline_access,publish_stream'
                                              });

    assert.equal(url, 'https://graph.facebook.com/oauth/authorize?client_id='
                    + _id + '&redirect_uri=' + querystring.escape(_callback)
                    + '&scope=' + querystring.escape('offline_access,publish_stream')
    );
    done();
  })

  .add('`apiCall` error', function (done) {
    facebook_client.apiCall(
      'GET'
    , '/search'
    , { access_token: _access_token
      , type: 'place'
      , center: '35.6869444,-105.9372222'
      , distance: 5
      }
    , function (error, response, body) {
        assert.equal(error, null);
        assert.equal(response.statusCode, 400);
        done();
      }
    );
  })

  .add('`apiCall` ok', function (done) {
    facebook_client.apiCall(
      'GET'
    , '/2439131959'
    , {}
    , function (error, response, body) {
        assert.equal(error, null);
        assert.equal(response.statusCode, 200);
        assert.equal(body.name, 'Graffiti');
        done();
      }
    );
  })

  .run();


text:
package hex.genmodel.algos.deepwater;

import deepwater.backends.BackendParams;
import deepwater.backends.RuntimeOptions;
import deepwater.datasets.ImageDataSet;
import hex.genmodel.ModelMojoReader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 */
public class DeepwaterMojoReader extends ModelMojoReader<DeepwaterMojoModel> {

  @Override
  public String getModelName() {
    return "Deep Water";
  }

  @Override
  protected void readModelData() throws IOException {
    try {
      _model._network = readblob("model_network");
      _model._parameters = readblob("model_params");
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    _model._backend = DeepwaterMojoModel.createDeepWaterBackend((String) readkv("backend")); // new ImageTrain(_width, _height, _channels, _deviceID, (int)parameters.getOrMakeRealSeed(), _gpu);
    if (_model._backend == null) {
      throw new IllegalArgumentException("Couldn't instantiate the Deep Water backend.");
    }
    _model._problem_type = readkv("problem_type");
    _model._mini_batch_size = readkv("mini_batch_size");
    _model._height = readkv("height");
    _model._width = readkv("width");
    _model._channels = readkv("channels");
    _model._nums = readkv("nums");
    _model._cats = readkv("cats");
    _model._catOffsets = readkv("cat_offsets");
    _model._normMul = readkv("norm_mul");
    _model._normSub = readkv("norm_sub");
    _model._normRespMul = readkv("norm_resp_mul");
    _model._normRespSub = readkv("norm_resp_sub");
    _model._useAllFactorLevels = readkv("use_all_factor_levels");

    _model._imageDataSet = new ImageDataSet(_model._width, _model._height, _model._channels, _model._nclasses);

    _model._opts = new RuntimeOptions();
    _model._opts.setSeed(0); // ignored - not needed during scoring
    _model._opts.setUseGPU((boolean)readkv("gpu"));
    _model._opts.setDeviceID((int[])readkv("device_id"));

    _model._backendParams = new BackendParams();
    _model._backendParams.set("mini_batch_size", 1);

    File file = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString() + ".json");
    try {
      FileOutputStream os = new FileOutputStream(file.toString());
      os.write(_model._network);
      os.close();
      _model._model = _model._backend.buildNet(_model._imageDataSet, _model._opts, _model._backendParams, _model._nclasses, file.toString());
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (file!=null)
        _model._backend.deleteSavedModel(file.toString());
    }
    // 1) read the raw bytes of the mean image file from the MOJO
    byte[] meanBlob;
    try {
      meanBlob = readblob("mean_image_file"); //throws exception if not found
      // 2) write the mean image file
      File meanFile = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString() + ".mean");
      try {
        FileOutputStream os = new FileOutputStream(meanFile.toString());
        os.write(meanBlob);
        os.close();
        // 3) tell the backend to use that mean image file (just in case it needs it)
        _model._imageDataSet.setMeanData(_model._backend.loadMeanImage(_model._model, meanFile.toString()));
        // 4) keep a float[] version of the mean array to be used during image processing
        _model._meanImageData = _model._imageDataSet.getMeanData();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (meanFile!=null)
          meanFile.delete();
      }
    } catch (IOException e) {
      // e.printStackTrace();
    }

    file = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    try {
      _model._backend.writeBytes(file, _model._parameters);
      _model._backend.loadParam(_model._model, file.toString());
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (file!=null)
        _model._backend.deleteSavedParam(file.toString());
    }
  }

  @Override
  protected DeepwaterMojoModel makeModel(String[] columns, String[][] domains) {
    return new DeepwaterMojoModel(columns, domains);
  }
}


text:
require("chai")
  .use(require("chai-as-promised"))
  .should()

const { assert, expect } = require("chai")

// Contracts
const RequestFactory = artifacts.require("./RequestFactory.sol")
const RequestLib = artifacts.require("./RequestLib.sol")
const TransactionRequestCore = artifacts.require("./TransactionRequestCore.sol")

// Brings in config.web3 (v1.0.0)
const ethUtil = require("ethereumjs-util")
const config = require("../../config")
const { parseRequestData, calculateBlockBucket } = require("../dataHelpers.js")

const NULL_ADDR = "0x0000000000000000000000000000000000000000"

// Note - these tests were checked very well and should never be wrong.
// If they start failing - look in the contracts.
contract("Request factory", async (accounts) => {
  let requestLib
  let transactionRequestCore
  let requestFactory

  const transactionRequest = {
    claimWindowSize: 255,
    fee: 12345,
    bounty: 54321,
    freezePeriod: 10,
    windowSize: 511,
    reservedWindowSize: 16,
    temporalUnit: 1,
    callValue: 123456789,
    callGas: 1000000,
    gasPrice: 1000000,
    requiredDeposit: 1000000,
    testCallData: "this-is-call-data",
    endowment: 10 ** 18
  }

  const getWindowStart = async () => (await config.web3.eth.getBlockNumber()) + 20

  const createValidationParams = async (properties = {}) => {
    const request = Object.assign(
      {},
      transactionRequest,
      { windowStart: await getWindowStart() },
      properties
    )

    return [
      request.fee,
      request.bounty,
      request.claimWindowSize,
      request.freezePeriod,
      request.reservedWindowSize,
      request.temporalUnit,
      request.windowSize,
      request.windowStart,
      request.callGas,
      request.callValue,
    ]
  }

  const validate = async ({
    endowment = transactionRequest.endowment,
    properties,
    to = accounts[2]
  } = {}) => {
    const paramsForValidation = await createValidationParams(properties)
    const isValid = await requestLib.validate(
      [accounts[0], accounts[0], accounts[1], to],
      paramsForValidation,
      endowment
    )

    return { paramsForValidation, isValid }
  }

  before(async () => {
    requestLib = await RequestLib.deployed()
    expect(requestLib.address).to.exist

    transactionRequestCore = await TransactionRequestCore.deployed()
    expect(transactionRequestCore.address).to.exist

    requestFactory = await RequestFactory.new(transactionRequestCore.address)
    expect(requestFactory.address).to.exist
  })

  it("should create a request with provided properties", async () => {
    const windowStart = await getWindowStart()
    const { paramsForValidation, isValid } = await validate({ properties: { windowStart } })

    isValid.forEach(bool => expect(bool).to.be.true)

    const params = paramsForValidation
    params.push(transactionRequest.gasPrice)
    params.push(transactionRequest.requiredDeposit)

    // Create a request with the same args we validated
    const createTx = await requestFactory.createRequest(
      [
        accounts[0],
        accounts[1], // fee recipient
        accounts[2], // to
      ],
      params,
      transactionRequest.testCallData
    )

    expect(createTx.receipt).to.exist

    const logRequestCreated = createTx.logs.find(e => e.event === "RequestCreated")

    expect(logRequestCreated.args.request).to.exist
    expect(logRequestCreated.args.params.length).to.equal(12)

    logRequestCreated.args.params.forEach((el, idx) => expect(el.toNumber()).to.equal(params[idx]))

    const bucket = calculateBlockBucket(windowStart)
    expect(logRequestCreated.args.bucket.toNumber()).to.equal(bucket.toNumber())

    // Now let's create a transactionRequest instance
    const txRequest = await TransactionRequestCore.at(logRequestCreated.args.request)
    const requestData = await parseRequestData(txRequest)

    expect(requestData.meta.owner).to.equal(accounts[0])

    expect(requestData.meta.createdBy).to.equal(accounts[0])

    expect(requestData.meta.isCancelled).to.be.false

    expect(requestData.meta.wasCalled).to.be.false

    expect(requestData.meta.wasSuccessful).to.be.false

    expect(requestData.claimData.claimedBy).to.equal(NULL_ADDR)

    expect(requestData.claimData.claimDeposit).to.equal(0)

    expect(requestData.claimData.paymentModifier).to.equal(0)

    expect(requestData.paymentData.fee).to.equal(transactionRequest.fee)

    expect(requestData.paymentData.feeRecipient).to.equal(accounts[1])

    expect(requestData.paymentData.feeOwed).to.equal(0)

    expect(requestData.paymentData.bounty).to.equal(transactionRequest.bounty)

    expect(requestData.paymentData.bountyBenefactor).to.equal(NULL_ADDR)

    expect(requestData.paymentData.bountyOwed).to.equal(0)

    expect(requestData.schedule.claimWindowSize).to.equal(transactionRequest.claimWindowSize)

    expect(requestData.schedule.freezePeriod).to.equal(transactionRequest.freezePeriod)

    expect(requestData.schedule.windowStart).to.equal(windowStart)

    expect(requestData.schedule.reservedWindowSize).to.equal(transactionRequest.reservedWindowSize)

    expect(requestData.schedule.temporalUnit).to.equal(1)

    expect(requestData.txData.toAddress).to.equal(accounts[2])

    const expectedCallData = ethUtil.bufferToHex(Buffer.from(transactionRequest.testCallData))
    const callData = await txRequest.callData()
    expect(callData).to.equal(expectedCallData)

    expect(requestData.txData.callValue).to.equal(transactionRequest.callValue)

    expect(requestData.txData.callGas).to.equal(transactionRequest.callGas)

    // Lastly, we just make sure that the transaction request
    // address is a known request for the factory.
    expect(await requestFactory.isKnownRequest(NULL_ADDR)).to.be.false // sanity check
    expect(await requestFactory.isKnownRequest(txRequest.address)).to.be.true
  })

  it("should test request factory insufficient endowment validation error", async () => {
    // Validate the data with the RequestLib
    const { isValid } = await validate({ endowment: 1 })

    expect(isValid[0]).to.be.false
    isValid.slice(1).forEach(bool => expect(bool).to.be.true)
  })

  it("should test request factory throws validation error on too large of a reserve window", async () => {
    const reservedWindowSize = transactionRequest.windowSize + 2
    const { isValid } = await validate({ properties: { reservedWindowSize } })

    expect(isValid[1]).to.be.false
    expect(isValid[0]).to.be.true
    isValid.slice(2).forEach(bool => expect(bool).to.be.true)
  })

  it("should test request factory throws invalid temporal unit validation error", async () => {
    const temporalUnit = 100
    const { isValid } = await validate({ properties: { temporalUnit } })

    expect(isValid[2]).to.be.false
    expect(isValid[3]).to.be.false
    isValid.slice(0, 2).forEach(bool => expect(bool).to.be.true)
    isValid.slice(4).forEach(bool => expect(bool).to.be.true)
  })

  it("should test request factory too soon execution window validation error", async () => {
    const windowStart = await getWindowStart()
    const freezePeriod = windowStart + 1
    const { isValid } = await validate({ properties: { windowStart, freezePeriod } })

    expect(isValid[3]).to.be.false
    isValid.slice(0, 3).forEach(bool => expect(bool).to.be.true)
    isValid.slice(4).forEach(bool => expect(bool).to.be.true)
  })

  it("should test request factory has too high call gas validation error", async () => {
    const callGas = 8.8e8 // cannot be over gas limit
    const { isValid } = await validate({ properties: { callGas } })

    expect(isValid[4]).to.be.false
    isValid.slice(0, 4).forEach(bool => expect(bool).to.be.true)
    isValid.slice(5).forEach(bool => expect(bool).to.be.true)
  })

  it("should test null to address validation error", async () => {
    const to = NULL_ADDR // cannot be over gas limit
    const { isValid } = await validate({ to })

    expect(isValid[5]).to.be.false
    isValid.slice(0, 5).forEach(bool => expect(bool).to.be.true)
  })

  it("should not allow to reinitialize the scheduled transaction", async () => {
    const { paramsForValidation } = await validate()

    const params = paramsForValidation
    params.push(transactionRequest.gasPrice)
    params.push(transactionRequest.requiredDeposit)

    // Create a request with the same args we validated
    const createTx = await requestFactory.createRequest(
      [
        accounts[0],
        accounts[1], // fee recipient
        accounts[2], // to
      ],
      params,
      transactionRequest.testCallData
    )

    const logRequestCreated = createTx.logs.find(e => e.event === "RequestCreated")
    const txRequest = await TransactionRequestCore.at(logRequestCreated.args.request)

    let requestData = await parseRequestData(txRequest)
    expect(requestData.txData.toAddress).to.equal(accounts[2])

    await txRequest.initialize(
      [
        accounts[0],
        accounts[0],
        accounts[1], // fee recipient
        accounts[3], // hijacking recipient
      ],
      params,
      transactionRequest.testCallData
    ).should.be.rejectedWith("VM Exception while processing transaction: revert")

    requestData = await parseRequestData(txRequest)
    expect(requestData.txData.toAddress).to.equal(accounts[2])
  })

  it("should not allow the deployment of new requests when paused", async () => {
    await requestFactory.pause();
    const isPaused = await requestFactory.paused();
    assert(isPaused, "RequestFactory should be paused now.");

    const windowStart = await getWindowStart()
    const { paramsForValidation, isValid } = await validate({ properties: { windowStart } })

    isValid.forEach(bool => expect(bool).to.be.true)

    const params = paramsForValidation
    params.push(transactionRequest.gasPrice)
    params.push(transactionRequest.requiredDeposit)

    // Create a request with the same args we validated
    let res;
    try {
      res = await requestFactory.createRequest(
        [
          accounts[0],
          accounts[1], // fee recipient
          accounts[2], // to
        ],
        params,
        transactionRequest.testCallData
      )
    } catch (e) {
      const wasReverted = e.toString().indexOf("VM Exception while processing transaction: revert");
      assert(wasReverted !== -1);
    }
    expect(res).to.be.undefined;
  })
})


text:
'use strict';

import once from 'lodash/once';
import noop from 'lodash/noop';

import keyIterator from './internal/keyIterator';
import onlyOnce from './internal/onlyOnce';

export default function eachOf(object, iterator, callback) {
    callback = once(callback || noop);
    object = object || [];

    var iter = keyIterator(object);
    var key, completed = 0;

    while ((key = iter()) != null) {
        completed += 1;
        iterator(object[key], key, onlyOnce(done));
    }

    if (completed === 0) callback(null);

    function done(err) {
        completed--;
        if (err) {
            callback(err);
        }
        // Check key is null in case iterator isn't exhausted
        // and done resolved synchronously.
        else if (key === null && completed <= 0) {
            callback(null);
        }
    }
}


text:
.class Lcom/android/calendarcommon/EventRecurrence$ParseUntil;
.super Lcom/android/calendarcommon/EventRecurrence$PartParser;
.source "EventRecurrence.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/calendarcommon/EventRecurrence;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "ParseUntil"
.end annotation

# direct methods
.method private constructor <init>()V
    .locals 0

    .prologue
    .line 733
    invoke-direct {p0}, Lcom/android/calendarcommon/EventRecurrence$PartParser;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Lcom/android/calendarcommon/EventRecurrence$1;)V
    .locals 0
    .parameter "x0"

    .prologue
    .line 733
    invoke-direct {p0}, Lcom/android/calendarcommon/EventRecurrence$ParseUntil;-><init>()V

    return-void
.end method

# virtual methods
.method public parsePart(Ljava/lang/String;Lcom/android/calendarcommon/EventRecurrence;)I
    .locals 1
    .parameter "value"
    .parameter "er"

    .prologue
    .line 744
    iput-object p1, p2, Lcom/android/calendarcommon/EventRecurrence;->until:Ljava/lang/String;

    .line 745
    const/4 v0, 0x2

    return v0
.end method


text:
Personal website and Blog, built on https://ghost.org/.

www.danielrothenberg.com


text:
/*****************************************************************************
 OSSLDH.cpp

 OpenSSL Diffie-Hellman asymmetric algorithm implementation
 *****************************************************************************/

#include "config.h"
#include "log.h"
#include "OSSLDH.h"
#include "CryptoFactory.h"
#include "DHParameters.h"
#include "OSSLDHKeyPair.h"
#include "OSSLUtil.h"
#include <algorithm>
#include <openssl/dh.h>
#include <openssl/pem.h>
#include <openssl/err.h>

// Signing functions
bool OSSLDH::signInit(PrivateKey* /*privateKey*/, const AsymMech::Type /*mechanism*/,
		      const void* /* param = NULL */, const size_t /* paramLen = 0 */)
{
	ERROR_MSG("DH does not support signing");

	return false;
}

bool OSSLDH::signUpdate(const ByteString& /*dataToSign*/)
{
	ERROR_MSG("DH does not support signing");

	return false;
}

bool OSSLDH::signFinal(ByteString& /*signature*/)
{
	ERROR_MSG("DH does not support signing");

	return false;
}

// Verification functions
bool OSSLDH::verifyInit(PublicKey* /*publicKey*/, const AsymMech::Type /*mechanism*/,
			const void* /* param = NULL */, const size_t /* paramLen = 0 */)
{
	ERROR_MSG("DH does not support verifying");

	return false;
}

bool OSSLDH::verifyUpdate(const ByteString& /*originalData*/)
{
	ERROR_MSG("DH does not support verifying");

	return false;
}

bool OSSLDH::verifyFinal(const ByteString& /*signature*/)
{
	ERROR_MSG("DH does not support verifying");

	return false;
}

// Encryption functions
bool OSSLDH::encrypt(PublicKey* /*publicKey*/, const ByteString& /*data*/,
		     ByteString& /*encryptedData*/, const AsymMech::Type /*padding*/)
{
	ERROR_MSG("DH does not support encryption");

	return false;
}

// Decryption functions
bool OSSLDH::decrypt(PrivateKey* /*privateKey*/, const ByteString& /*encryptedData*/,
		     ByteString& /*data*/, const AsymMech::Type /*padding*/)
{
	ERROR_MSG("DH does not support decryption");

	return false;
}

// Key factory
bool OSSLDH::generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* /*rng = NULL */)
{
	// Check parameters
	if ((ppKeyPair == NULL) ||
	    (parameters == NULL))
	{
		return false;
	}

	if (!parameters->areOfType(DHParameters::type))
	{
		ERROR_MSG("Invalid parameters supplied for DH key generation");

		return false;
	}

	DHParameters* params = (DHParameters*) parameters;

	// Generate the key-pair
	DH* dh = DH_new();

	if (dh == NULL)
	{
		ERROR_MSG("Failed to instantiate OpenSSL DH object");

		return false;
	}

	if (dh->p != NULL)
		BN_clear_free(dh->p);
	dh->p = OSSL::byteString2bn(params->getP());
	if (dh->g != NULL)
		BN_clear_free(dh->g);
	dh->g = OSSL::byteString2bn(params->getG());

	// PKCS#3: 2^(l-1) <= x < 2^l
	if (params->getXBitLength() > 0)
	{
		if (dh->priv_key == NULL)
			dh->priv_key = BN_new();

		if (BN_rand(dh->priv_key, params->getXBitLength(), 0, 0) != 1)
		{
			ERROR_MSG("DH private key generation failed (0x%08X)", ERR_get_error());

			DH_free(dh);

			return false;
		}
	}

	if (DH_generate_key(dh) != 1)
	{
		ERROR_MSG("DH key generation failed (0x%08X)", ERR_get_error());

		DH_free(dh);

		return false;
	}

	// Create an asymmetric key-pair object to return
	OSSLDHKeyPair* kp = new OSSLDHKeyPair();

	((OSSLDHPublicKey*) kp->getPublicKey())->setFromOSSL(dh);
	((OSSLDHPrivateKey*) kp->getPrivateKey())->setFromOSSL(dh);

	*ppKeyPair = kp;

	// Release the key
	DH_free(dh);

	return true;
}

bool OSSLDH::deriveKey(SymmetricKey **ppSymmetricKey, PublicKey* publicKey, PrivateKey* privateKey)
{
	// Check parameters
	if ((ppSymmetricKey == NULL) ||
	    (publicKey == NULL) ||
	    (privateKey == NULL))
	{
		return false;
	}

	// Get keys
	DH *pub = ((OSSLDHPublicKey *)publicKey)->getOSSLKey();
	DH *priv = ((OSSLDHPrivateKey *)privateKey)->getOSSLKey();
	if (pub == NULL || pub->pub_key == NULL || priv == NULL)
	{
		ERROR_MSG("Failed to get OpenSSL DH keys");

		return false;
	}

	// Derive the secret
	ByteString secret;
	secret.resize(DH_size(priv));;

	if (DH_compute_key(&secret[0], pub->pub_key, priv) <= 0)
	{
		ERROR_MSG("DH key derivation failed (0x%08X)", ERR_get_error());

		return false;
	}

	*ppSymmetricKey = new SymmetricKey;
	if (*ppSymmetricKey == NULL)
		return false;
	if (!(*ppSymmetricKey)->setKeyBits(secret))
	{
		delete *ppSymmetricKey;
		*ppSymmetricKey = NULL;
		return false;
	}

	return true;
}

unsigned long OSSLDH::getMinKeySize()
{
#ifdef WITH_FIPS
	// OPENSSL_DH_FIPS_MIN_MODULUS_BITS is 1024
	return 1024;
#else
	return 512;
#endif
}

unsigned long OSSLDH::getMaxKeySize()
{
	return OPENSSL_DH_MAX_MODULUS_BITS;
}

bool OSSLDH::generateParameters(AsymmetricParameters** ppParams, void* parameters /* = NULL */, RNG* /*rng = NULL*/)
{
	if ((ppParams == NULL) || (parameters == NULL))
	{
		return false;
	}

	size_t bitLen = (size_t) parameters;

	if (bitLen < getMinKeySize() || bitLen > getMaxKeySize())
	{
		ERROR_MSG("This DH key size is not supported");

		return false;
	}

	DH* dh = DH_generate_parameters(bitLen, 2, NULL, NULL);

	if (dh == NULL)
	{
		ERROR_MSG("Failed to generate %d bit DH parameters", bitLen);

		return false;
	}

	// Store the DH parameters
	DHParameters* params = new DHParameters();

	ByteString p = OSSL::bn2ByteString(dh->p); params->setP(p);
	ByteString g = OSSL::bn2ByteString(dh->g); params->setG(g);

	*ppParams = params;

	DH_free(dh);

	return true;
}

bool OSSLDH::reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData)
{
	// Check input
	if ((ppKeyPair == NULL) ||
	    (serialisedData.size() == 0))
	{
		return false;
	}

	ByteString dPub = ByteString::chainDeserialise(serialisedData);
	ByteString dPriv = ByteString::chainDeserialise(serialisedData);

	OSSLDHKeyPair* kp = new OSSLDHKeyPair();

	bool rv = true;

	if (!((DHPublicKey*) kp->getPublicKey())->deserialise(dPub))
	{
		rv = false;
	}

	if (!((DHPrivateKey*) kp->getPrivateKey())->deserialise(dPriv))
	{
		rv = false;
	}

	if (!rv)
	{
		delete kp;

		return false;
	}

	*ppKeyPair = kp;

	return true;
}

bool OSSLDH::reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData)
{
	// Check input
	if ((ppPublicKey == NULL) ||
	    (serialisedData.size() == 0))
	{
		return false;
	}

	OSSLDHPublicKey* pub = new OSSLDHPublicKey();

	if (!pub->deserialise(serialisedData))
	{
		delete pub;

		return false;
	}

	*ppPublicKey = pub;

	return true;
}

bool OSSLDH::reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData)
{
	// Check input
	if ((ppPrivateKey == NULL) ||
	    (serialisedData.size() == 0))
	{
		return false;
	}

	OSSLDHPrivateKey* priv = new OSSLDHPrivateKey();

	if (!priv->deserialise(serialisedData))
	{
		delete priv;

		return false;
	}

	*ppPrivateKey = priv;

	return true;
}

PublicKey* OSSLDH::newPublicKey()
{
	return (PublicKey*) new OSSLDHPublicKey();
}

PrivateKey* OSSLDH::newPrivateKey()
{
	return (PrivateKey*) new OSSLDHPrivateKey();
}

AsymmetricParameters* OSSLDH::newParameters()
{
	return (AsymmetricParameters*) new DHParameters();
}

bool OSSLDH::reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData)
{
	// Check input parameters
	if ((ppParams == NULL) || (serialisedData.size() == 0))
	{
		return false;
	}

	DHParameters* params = new DHParameters();

	if (!params->deserialise(serialisedData))
	{
		delete params;

		return false;
	}

	*ppParams = params;

	return true;
}


text:
module Fayde.DataVis {
    export class LinearParameterizer implements IParameterizer {
        Minimum: IValueOfable = null;
        Maximum: IValueOfable = null;

        Parameterize (vs: IValueSet, index: number): number {
            var n = <number>(vs.Values[index] || 0).valueOf();
            var min = Parameterize.ValidMinimum(this.Minimum, vs.Min);
            var max = Parameterize.ValidMaximum(this.Maximum, vs.Max);
            return (n - min) / (max - min);
        }
    }
}


text:
This announcement will be emited when removing a category using:
=> SystemOrganizer >> removeCategory:


text:
C $Header$
C $Name$

c#ifdef ALLOW_DOWN_SLOPE

C-    dimension parameters :
C     xSize  :: X-dimension for 1 tile array (overlap included)
C     xySize :: product of X-dim x Y-dim for 1 tile array
      INTEGER xSize, xySize
      PARAMETER (  xSize = Olx+sNx+Olx )
      PARAMETER ( xySize = xSize*(Oly+sNy+Oly) )

C     DWNSLP_size :: size of downsloping-flow arrays ; for each tile,
C            must be > number of bathymetric steps
C            The default value (=tile domain size) can increased (if needed)
C             or reduced (to save memory space).
      INTEGER DWNSLP_size
      PARAMETER ( DWNSLP_size = xSize * (Oly+sNy+Oly) )

c#endif /* ALLOW_DOWN_SLOPE */


text:
package com.dewey.deweyapp.location;

import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.dewey.deweyapp.R;

public class LocationActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_location, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void drawMap(View view){
        System.out.println("Inside Draw Map");
        FragmentTransaction trans = getFragmentManager().beginTransaction();
        LocationActivityFragment fragment = new LocationActivityFragment();
        trans.add(R.id.loc_fragment, fragment).commit();

    }
}