text:
function [A, b] = sllinrega(X, Y, varargin)
%SLLINREGA Performs Augmented Multivariate Linear Regression
%
% $ Syntax $
%   - [A, b] = sllinrega(X, Y, ...)
%
% $ Arguments $
%   - X:        The sample matrix of x
%   - Y:        The sample matrix of y
%   - A:        The solved transform matrix
%   - b:        The solved shift vector
%
% $ Description $
%   - [A, b] = sllinrega(X, Y, ...) solves the regression problem given
%     by the following formula:
%           y = A * x + b
%     in least square error sense. The samples are stored in X and Y
%     in column-wise manner.
%     You can specify properties for regression as in sllinreg.
%
% $ Remarks $
%   - The implementation is based on sllinreg with an augmented
%     formulation as follows:
%           y = [A, b] * [x; 1]
%
% $ History $
%   - Created by Dahua Lin, on Sep 15th, 2006
%

%% parse and verify input arguments

if nargin < 2
    raise_lackinput('sllinrega', 2);
end

if ~isnumeric(X) || ~isnumeric(Y) || ndims(X) ~= 2 || ndims(Y) ~= 2
    error('sltoolbox:invalidarg', ...
        'The X and Y should be both 2D numeric matrices');
end

%% main

% augment formulation
[dx, nx] = size(X);
Xa = [X; ones(1, nx)];

% solve
Aa = sllinreg(Xa, Y, varargin{:});
clear Xa;

% extract
A = Aa(:, 1:dx);
b = Aa(:, dx+1);


text:
package com.hazelcast.cache.jsr;

import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.AfterClass;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class CacheEntryListenerClientServerTest
        extends org.jsr107.tck.event.CacheEntryListenerClientServerTest {

    /*
    These system propreties are necessary if you run jsr tests from IDEA
    static {
        System.setProperty("javax.management.builder.initial", "com.hazelcast.cache.impl.TCKMBeanServerBuilder");
        System.setProperty("org.jsr107.tck.management.agentId", "TCKMbeanServer");
        System.setProperty(Cache.class.getName(), "com.hazelcast.cache.ICache");
        System.setProperty(Cache.Entry.class.getCanonicalName(), "com.hazelcast.cache.impl.CacheEntry");
    }
    */

    @AfterClass
    public static void cleanup() {
        JstTestUtil.cleanup();
    }
}

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://secure.travis-ci.org/erikd/http-proxy.png?branch=master)](http://travis-ci.org/erikd/http-proxy)

A Haskell library for creating HTTP and HTTPS web proxies.

The aim is to make all proxying operations work in constant space (per
connection) so that memory usage scales linearly with the number of concurrent
connections and is completely independent of the size of either the POST
request body or the response body.

This library relies heavily on the following libraries:

* wai : A common protocol between web servers and clients.
* warp : The web servers the proxy application runs in.
* http-conduit / http-client : Perform the upstream requests.

This is still beta quality.


text:
module Fog
    module Compute
        class ProfitBricks
            class Real
                require 'fog/profitbricks/parsers/compute/get_all_nic'

                # Returns all virtual NICs
                #
                # ==== Parameters
                # * N/A
                #
                # ==== Returns
                # * response<~Excon::Response>:
                #   * body<~Hash>:
                #     * getAllNicResponse<~Hash>:
                #       * nicId<~String> - UUID of the network interface
                #       * nicName<~String> - Name of the network interface
                #       * lanId<~Integer> -
                #       * internetAccess<~Boolean> -
                #       * serverId<~String> -
                #       * ips<~String> -
                #       * macAddress<~String> -
                #       * firewall<~Hash>:
                #         * ...
                #       * dhcpActive<~Boolean> -
                #       * gatewayIp<~String> -
                #       * provisioningState<~String> - INACTIVE, INPROCESS, AVAILABLE, DELETED, ERROR
                #
                # {ProfitBricks API Documentation}[http://www.profitbricks.com/apidoc/GetAllNIC.html]
                def get_all_nic
                    soap_envelope = Fog::ProfitBricks.construct_envelope {
                      |xml| xml[:ws].getAllNic
                    }

                    request(
                        :expects => [200],
                        :method  => 'POST',
                        :body    => soap_envelope.to_xml,
                        :parser  =>
                          Fog::Parsers::Compute::ProfitBricks::GetAllNic.new
                    )
                end
            end

            class Mock
                def get_all_nic
                    response        = Excon::Response.new
                    response.status = 200
                    response.body   = { 'getAllNicResponse' => self.data[:interfaces] }
                    response
                end
            end
        end
    end
end


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package clustering.io.tuple;

import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * Writable interface for a tuple of two values.
 *
 * @author edwardlol
 *         Created by edwardlol on 17-4-24.
 */
abstract class TupleWritable<K extends Writable, V extends Writable> implements WritableComparable<TupleWritable> {
    //~ Instance fields --------------------------------------------------------

    K left;
    V right;

    //~ Constructors -----------------------------------------------------------

    TupleWritable() {
    }

    //~ Methods ----------------------------------------------------------------

    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null || this.getClass() != that.getClass()) {
            return false;
        }
        TupleWritable guest = (TupleWritable) that;
        return this.left.equals(guest.left) && this.right.equals(guest.right);
    }

    @Override
    public void readFields(DataInput in) throws IOException {
        this.left.readFields(in);
        this.right.readFields(in);
    }

    @Override
    public void write(DataOutput out) throws IOException {
        this.left.write(out);
        this.right.write(out);
    }

    public Writable getLeft() {
        return this.left;
    }

    public Writable getRight() {
        return this.right;
    }

    /**
     * Omitting braces for perfomance reason.
     */
    @Override
    public String toString() {
        return this.left.toString() + ',' + this.right.toString();
    }

}

// End TupleWritable.java


text:
"use strict";

var curry = require("functional/curry")

var unequal = curry(function assert(expected, actual) {
  /**
  Functions takes `expected` and `actual` values and returns `true` if
  `expected == actual`. Returns curried function if called with less then
  two arguments.

  ## Example

      [ 1, "1", "2", 0 ].filter(unequal(true))

      // => [ "2", 0 ]

  **/
  return actual != expected
})

module.exports = unequal


text:
from django.conf.urls import url, include
from django.contrib.auth import views as v

from . import views

urlpatterns = [
	url(r'^login/$', v.login, name='login'),
	url(r'^logout/$', v.logout, name='logged_out'),
	url(r'^logout-then-login/$', v.logout_then_login, name='logout_then_login'),
	url(r'^password-change/$', v.password_change, name='password_change'),
	url(r'^password-change/done/$',	v.password_change_done,
		name='password_change_done'),
	# restore password urls
	url(r'^password-reset/$', v.password_reset,	name='password_reset'),
	url(r'^password-reset/done/$', v.password_reset_done,
		name='password_reset_done'),
	url(r'^password-reset/confirm/(?P<uidb64>[-\w]+)/(?P<token>[-\w]+)/$',
		v.password_reset_confirm, name='password_reset_confirm'),
	url(r'^password-reset/complete/$', v.password_reset_complete,
		name='password_reset_complete'),
	url(r'^register/$', views.register, name='register'),
	url(r'^terms/$', views.terms, name='terms'),
]


text:
package net.objectlab.kit.util;

/**
 * An object holder just in case one needs to give it as an argement to a method.
 * @author Benoit Xhenseval
 */
public class ObjectHolder<T> {
    private T value;

    /**
     * value is null
     */
    public ObjectHolder() {
    }

    /**
     * with a default value
     */
    public ObjectHolder(final T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }

    public void setValue(final T value) {
        this.value = value;
    }
}


text:
Airplane_AltitudePID = PID.new(AirplanePIDConfig.Altitude, -10, 10)
Airplane_YawPID = PID.new(AirplanePIDConfig.Yaw, -1, 1)
Airplane_PitchPID = PID.new(AirplanePIDConfig.Pitch, -1, 1)
Airplane_RollPID = PID.new(AirplanePIDConfig.Roll, -1, 1)

Airplane_DesiredAltitude = 0
Airplane_DesiredHeading = nil
Airplane_DesiredPosition = nil
Airplane_DesiredThrottle = nil
Airplane_CurrentThrottle = 0

Airplane_LastSpinnerCount = 0
Airplane_SpinnerInfos = {}

Airplane_UsesSpinners = (SpinnerFractions.Yaw > 0 or SpinnerFractions.Pitch > 0 or SpinnerFractions.Roll > 0 or SpinnerFractions.Throttle > 0)

Airplane_MaxPitch = LookupTable.new(MaxPitch[1][1], math.max(Airplane_MaxAltitude, MaxPitch[#MaxPitch][1]), MaxPitch[1][2], MaxPitch[#MaxPitch][2], 100, MaxPitch)

Airplane_Active = false

Airplane = {}

function Airplane.SetAltitude(Alt)
   Airplane_DesiredAltitude = Alt
end

function Airplane.SetHeading(Heading)
   Airplane_DesiredHeading = Heading % 360
end

function Airplane.ResetHeading()
   Airplane_DesiredHeading = nil
end

function Airplane.SetPosition(Pos)
   -- Make copy to be safe
   Airplane_DesiredPosition = Vector3(Pos.x, Pos.y, Pos.z)
end

function Airplane.ResetPosition()
   Airplane_DesiredPosition = nil
end

function Airplane.SetThrottle(Throttle)
   Airplane_DesiredThrottle = Clamp(Throttle, 0, 1)
end

function Airplane.GetThrottle()
   return Airplane_CurrentThrottle
end

function Airplane.ResetThrottle()
   Airplane_DesiredThrottle = nil
end

Airplane_Eps = .001

function Airplane_Classify(Index, BlockInfo, Fractions, Infos)
   local CoMOffset = BlockInfo.LocalPositionRelativeToCom
   -- Always spinners here
   local LocalForwards = BlockInfo.LocalRotation * Vector3.up
   local Info = {
      Index = Index,
      YawSign = 0,
      PitchSign = 0,
      RollSign = 0,
      ForwardSign = 0,
   }
   local UpSign = Sign(LocalForwards.y, 0, Airplane_Eps)
   if UpSign ~= 0 then
      -- Vertical
      Info.PitchSign = Sign(CoMOffset.z) * UpSign * Fractions.Pitch
      Info.RollSign = Sign(CoMOffset.x) * UpSign * Fractions.Roll
   else
      -- Horizontal
      local ForwardSign = Sign(LocalForwards.z, 0, Airplane_Eps)
      local RightSign = Sign(LocalForwards.x, 0, Airplane_Eps)
      Info.YawSign = RightSign * Sign(CoMOffset.z) * Fractions.Yaw
      Info.ForwardSign = ForwardSign * Fractions.Throttle
   end
   if Info.PitchSign ~= 0 or Info.RollSign ~= 0 or Info.YawSign ~= 0 or Info.ForwardSign ~= 0 then
      table.insert(Infos, Info)
   end
end

function Airplane_ClassifySpinners(I)
   -- Only process dediblades for now
   local SpinnerCount = I:GetDedibladeCount()
   if SpinnerCount ~= Airplane_LastSpinnerCount then
      Airplane_LastSpinnerCount = SpinnerCount
      Airplane_SpinnerInfos = {}

      for i = 0,SpinnerCount-1 do
         local BlockInfo = I:GetDedibladeInfo(i)
         Airplane_Classify(i, BlockInfo, SpinnerFractions, Airplane_SpinnerInfos)
      end
   end
end

Airplane_RequestControl = MakeRequestControl()

function Airplane.Update(I)
   local Altitude = C:Altitude()

   -- Determine target vector
   local TargetVector,DesiredHeading
   if Airplane_DesiredPosition then
      TargetVector = (Airplane_DesiredPosition - C:CoM()).normalized
      DesiredHeading = GetVectorAngle(TargetVector)
   else
      DesiredHeading = Airplane_DesiredHeading
      -- Be sure to flip sign and divide by PID scale
      local PitchForAltitude = Airplane_MaxPitch:Lookup(Altitude) * Airplane_AltitudePID:Control(Airplane_DesiredAltitude - Altitude) / -10
      TargetVector = Quaternion.Euler(PitchForAltitude, DesiredHeading or 0, 0) * Vector3.forward
   end

   -- Roll turn logic
   local DesiredRoll = 0
   if AngleBeforeRoll and DesiredHeading then
      local Bearing = NormalizeBearing(DesiredHeading - GetVectorAngle(C:ForwardVector()))
      local AbsBearing = math.abs(Bearing)
      if AbsBearing > AngleBeforeRoll and Altitude >= MinAltitudeForRoll then
         local RollAngle = RollAngleGain and math.min(MaxRollAngle, (AbsBearing - AngleBeforeRoll) * RollAngleGain) or MaxRollAngle
         DesiredRoll = -Sign(Bearing) * RollAngle
      end
   end

   -- Convert TargetVector to local coordinates
   TargetVector = C:ToLocal() * TargetVector

   -- Determine angles
   local z = TargetVector.z
   local Yaw = math.deg(math.atan2(TargetVector.x, z))
   local Pitch = math.deg(math.atan2(TargetVector.y, z))

   -- Run through PIDs
   local YawCV = Airplane_YawPID:Control(Yaw)
   local PitchCV = Airplane_PitchPID:Control(Pitch)
   local RollCV = Airplane_RollPID:Control(DesiredRoll - C:Roll())

   -- And apply to controls
   Airplane_RequestControl(I, 1, YAWRIGHT, YAWLEFT, YawCV * Sign(C:ForwardSpeed(), 1))
   Airplane_RequestControl(I, 1, NOSEUP, NOSEDOWN, PitchCV)
   Airplane_RequestControl(I, 1, ROLLLEFT, ROLLRIGHT, RollCV)
   if Airplane_DesiredThrottle then
      --# Use of Airplane_RequestControl is questionable here, especially
      --# since fraction is always 1 (for now)
      Airplane_RequestControl(I, 1, MAINPROPULSION, MAINPROPULSION, Airplane_DesiredThrottle)
      Airplane_CurrentThrottle = Airplane_DesiredThrottle
   end

   if Airplane_UsesSpinners then
      Airplane_ClassifySpinners(I)

      -- Set spinner speed
      local ForwardCV = Airplane_DesiredThrottle and Airplane_DesiredThrottle or 0
      for _,Info in pairs(Airplane_SpinnerInfos) do
         -- Sum up inputs and constrain
         local Output = Clamp(YawCV * Info.YawSign + PitchCV * Info.PitchSign + RollCV * Info.RollSign + ForwardCV * Info.ForwardSign, -1, 1)
         I:SetDedibladeContinuousSpeed(Info.Index, 30 * Output)
      end
   end

   Airplane_Active = true
end

function Airplane.Disable(I)
   Airplane_RequestControl(I, 1, MAINPROPULSION, MAINPROPULSION, 0)
   Airplane_CurrentThrottle = 0
   if Airplane_UsesSpinners then
      Airplane_ClassifySpinners(I)
      -- And stop spinners as well
      for _,Info in pairs(Airplane_SpinnerInfos) do
         I:SetDedibladeContinuousSpeed(Info.Index, 0)
      end
   end
end

function Airplane.Release(I)
   -- Same thing as Airplane_Disable, but only done
   -- once (until Airplane_Update is called again)
   if Airplane_Active then
      Airplane.Disable(I)
      Airplane_Active = false
   end
end


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import com.google.gson.Gson;
import dataAccessLayer.Repozitorij;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Jurica
 */
public class DetaljiProizvodaServlet extends HttpServlet {

    //Servlet se ponasa kao REST servis, samo vraca json za zadani ID proizvoda
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("application/json;charset=UTF-8");
        int id = Integer.parseInt(request.getParameter("id"));

        Gson json = new Gson();
        String proizvodJson = json.toJson(Repozitorij.getProizvodiDatabaseInstance().getProizvod(id));
        try (PrintWriter out = response.getWriter()) {
            out.println(proizvodJson);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        processRequest(request, response);
    }
}


text:
#ifndef _FIREWIRE_FWSERIAL_H
#define _FIREWIRE_FWSERIAL_H

#include <linux/kernel.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/list.h>
#include <linux/firewire.h>
#include <linux/firewire-constants.h>
#include <linux/spinlock.h>
#include <linux/rcupdate.h>
#include <linux/mutex.h>
#include <linux/serial.h>
#include <linux/serial_reg.h>
#include <linux/module.h>
#include <linux/seq_file.h>
#include <linux/debugfs.h>

#include "dma_fifo.h"

#ifdef FWTTY_PROFILING
#define DISTRIBUTION_MAX_SIZE     8192
#define DISTRIBUTION_MAX_INDEX    (ilog2(DISTRIBUTION_MAX_SIZE) + 1)
static inline void fwtty_profile_data(unsigned stat[], unsigned val)
{
	int n = (val) ? min(ilog2(val) + 1, DISTRIBUTION_MAX_INDEX) : 0;
	++stat[n];
}
#else
#define DISTRIBUTION_MAX_INDEX    0
#define fwtty_profile_data(st, n)
#endif

/* Parameters for both VIRT_CABLE_PLUG & VIRT_CABLE_PLUG_RSP mgmt codes */
struct virt_plug_params {
	__be32  status_hi;
	__be32  status_lo;
	__be32	fifo_hi;
	__be32	fifo_lo;
	__be32	fifo_len;
};

struct peer_work_params {
	union {
		struct virt_plug_params plug_req;
	};
};

/**
 * fwtty_peer: structure representing local & remote unit devices
 * @unit: unit child device of fw_device node
 * @serial: back pointer to associated fw_serial aggregate
 * @guid: unique 64-bit guid for this unit device
 * @generation: most recent bus generation
 * @node_id: most recent node_id
 * @speed: link speed of peer (0 = S100, 2 = S400, ... 5 = S3200)
 * @mgmt_addr: bus addr region to write mgmt packets to
 * @status_addr: bus addr register to write line status to
 * @fifo_addr: bus addr region to write serial output to
 * @fifo_len:  max length for single write to fifo_addr
 * @list: link for insertion into fw_serial's peer_list
 * @rcu: for deferring peer reclamation
 * @lock: spinlock to synchonize changes to state & port fields
 * @work: only one work item can be queued at any one time
 *        Note: pending work is canceled prior to removal, so this
 *        peer is valid for at least the lifetime of the work function
 * @work_params: parameter block for work functions
 * @timer: timer for resetting peer state if remote request times out
 * @state: current state
 * @connect: work item for auto-connecting
 * @connect_retries: # of connections already attempted
 * @port: associated tty_port (usable if state == FWSC_ATTACHED)
 */
struct fwtty_peer {
	struct fw_unit		*unit;
	struct fw_serial	*serial;
	u64			guid;
	int			generation;
	int			node_id;
	unsigned		speed;
	int			max_payload;
	u64			mgmt_addr;

	/* these are usable only if state == FWSC_ATTACHED */
	u64			status_addr;
	u64			fifo_addr;
	int			fifo_len;

	struct list_head	list;
	struct rcu_head		rcu;

	spinlock_t		lock;
	work_func_t		workfn;
	struct work_struct	work;
	struct peer_work_params work_params;
	struct timer_list	timer;
	int			state;
	struct delayed_work	connect;
	int			connect_retries;

	struct fwtty_port	*port;
};

#define to_peer(ptr, field)	(container_of(ptr, struct fwtty_peer, field))

/* state values for fwtty_peer.state field */
enum fwtty_peer_state {
	FWPS_GONE,
	FWPS_NOT_ATTACHED,
	FWPS_ATTACHED,
	FWPS_PLUG_PENDING,
	FWPS_PLUG_RESPONDING,
	FWPS_UNPLUG_PENDING,
	FWPS_UNPLUG_RESPONDING,

	FWPS_NO_MGMT_ADDR = -1,
};

#define CONNECT_RETRY_DELAY	HZ
#define MAX_CONNECT_RETRIES	10

/* must be holding peer lock for these state funclets */
static inline void peer_set_state(struct fwtty_peer *peer, int new)
{
	peer->state = new;
}

static inline struct fwtty_port *peer_revert_state(struct fwtty_peer *peer)
{
	struct fwtty_port *port = peer->port;

	peer->port = NULL;
	peer_set_state(peer, FWPS_NOT_ATTACHED);
	return port;
}

struct fwserial_mgmt_pkt {
	struct {
		__be16		len;
		__be16		code;
	} hdr;
	union {
		struct virt_plug_params plug_req;
		struct virt_plug_params plug_rsp;
	};
} __packed;

/* fwserial_mgmt_packet codes */
#define FWSC_RSP_OK			0x0000
#define FWSC_RSP_NACK			0x8000
#define FWSC_CODE_MASK			0x0fff

#define FWSC_VIRT_CABLE_PLUG		1
#define FWSC_VIRT_CABLE_UNPLUG		2
#define FWSC_VIRT_CABLE_PLUG_RSP	3
#define FWSC_VIRT_CABLE_UNPLUG_RSP	4

/* 1 min. plug timeout -- suitable for userland authorization */
#define VIRT_CABLE_PLUG_TIMEOUT		(60 * HZ)

struct stats {
	unsigned	xchars;
	unsigned	dropped;
	unsigned	tx_stall;
	unsigned	fifo_errs;
	unsigned	sent;
	unsigned	lost;
	unsigned	throttled;
	unsigned	reads[DISTRIBUTION_MAX_INDEX + 1];
	unsigned	writes[DISTRIBUTION_MAX_INDEX + 1];
	unsigned	txns[DISTRIBUTION_MAX_INDEX + 1];
	unsigned	unthrottle[DISTRIBUTION_MAX_INDEX + 1];
};

struct fwconsole_ops {
	void (*notify)(int code, void *data);
	void (*stats)(struct stats *stats, void *data);
	void (*proc_show)(struct seq_file *m, void *data);
};

/* codes for console ops notify */
#define FWCON_NOTIFY_ATTACH		1
#define FWCON_NOTIFY_DETACH		2

/**
 * fwtty_port: structure used to track/represent underlying tty_port
 * @port: underlying tty_port
 * @device: tty device
 * @index: index into port_table for this particular port
 *    note: minor = index + minor_start assigned by tty_alloc_driver()
 * @serial: back pointer to the containing fw_serial
 * @rx_handler: bus address handler for unique addr region used by remotes
 *              to communicate with this port. Every port uses
 *		fwtty_port_handler() for per port transactions.
 * @fwcon_ops: ops for attached fw_console (if any)
 * @con_data: private data for fw_console
 * @wait_tx: waitqueue for sleeping until writer/drain completes tx
 * @emit_breaks: delayed work responsible for generating breaks when the
 *               break line status is active
 * @cps : characters per second computed from the termios settings
 * @break_last: timestamp in jiffies from last emit_breaks
 * @hangup: work responsible for HUPing when carrier is dropped/lost
 * @mstatus: loose virtualization of LSR/MSR
 *         bits 15..0  correspond to TIOCM_* bits
 *         bits 19..16 reserved for mctrl
 *         bit 20      OOB_TX_THROTTLE
 *	   bits 23..21 reserved
 *         bits 31..24 correspond to UART_LSR_* bits
 * @lock: spinlock for protecting concurrent access to fields below it
 * @mctrl: loose virtualization of MCR
 *         bits 15..0  correspond to TIOCM_* bits
 *         bit 16      OOB_RX_THROTTLE
 *         bits 19..17 reserved
 *	   bits 31..20 reserved for mstatus
 * @drain: delayed work scheduled to ensure that writes are flushed.
 *         The work can race with the writer but concurrent sending is
 *         prevented with the IN_TX flag. Scheduled under lock to
 *         limit scheduling when fifo has just been drained.
 * @tx_fifo: fifo used to store & block-up writes for dma to remote
 * @max_payload: max bytes transmissible per dma (based on peer's max_payload)
 * @status_mask: UART_LSR_* bitmask significant to rx (based on termios)
 * @ignore_mask: UART_LSR_* bitmask of states to ignore (also based on termios)
 * @break_ctl: if set, port is 'sending break' to remote
 * @write_only: self-explanatory
 * @overrun: previous rx was lost (partially or completely)
 * @loopback: if set, port is in loopback mode
 * @flags: atomic bit flags
 *         bit 0: IN_TX - gate to allow only one cpu to send from the dma fifo
 *                        at a time.
 *         bit 1: STOP_TX - force tx to exit while sending
 * @peer: rcu-pointer to associated fwtty_peer (if attached)
 *        NULL if no peer attached
 * @icount: predefined statistics reported by the TIOCGICOUNT ioctl
 * @stats: additional statistics reported in /proc/tty/driver/firewire_serial
 */
struct fwtty_port {
	struct tty_port		   port;
	struct device		   *device;
	unsigned		   index;
	struct fw_serial	   *serial;
	struct fw_address_handler  rx_handler;

	struct fwconsole_ops	   *fwcon_ops;
	void			   *con_data;

	wait_queue_head_t	   wait_tx;
	struct delayed_work	   emit_breaks;
	unsigned		   cps;
	unsigned long		   break_last;

	struct work_struct	   hangup;

	unsigned		   mstatus;

	spinlock_t		   lock;
	unsigned		   mctrl;
	struct delayed_work	   drain;
	struct dma_fifo		   tx_fifo;
	int			   max_payload;
	unsigned		   status_mask;
	unsigned		   ignore_mask;
	unsigned		   break_ctl:1,
				   write_only:1,
				   overrun:1,
				   loopback:1;
	unsigned long		   flags;

	struct fwtty_peer __rcu	   *peer;

	struct async_icount	   icount;
	struct stats		   stats;
};

#define to_port(ptr, field)	(container_of(ptr, struct fwtty_port, field))

/* bit #s for flags field */
#define IN_TX                      0
#define STOP_TX                    1

/* bitmasks for special mctrl/mstatus bits */
#define OOB_RX_THROTTLE   0x00010000
#define MCTRL_RSRVD       0x000e0000
#define OOB_TX_THROTTLE   0x00100000
#define MSTATUS_RSRVD     0x00e00000

#define MCTRL_MASK        (TIOCM_DTR | TIOCM_RTS | TIOCM_OUT1 | TIOCM_OUT2 | \
			   TIOCM_LOOP | OOB_RX_THROTTLE | MCTRL_RSRVD)

/* XXX even every 1/50th secs. may be unnecessarily accurate */
/* delay in jiffies between brk emits */
#define FREQ_BREAKS        (HZ / 50)

/* Ports are allocated in blocks of num_ports for each fw_card */
#define MAX_CARD_PORTS           CONFIG_FWTTY_MAX_CARD_PORTS
#define MAX_TOTAL_PORTS          CONFIG_FWTTY_MAX_TOTAL_PORTS

/* tuning parameters */
#define FWTTY_PORT_TXFIFO_LEN	4096
#define FWTTY_PORT_MAX_PEND_DMA    8    /* costs a cache line per pend */
#define DRAIN_THRESHOLD         1024
#define MAX_ASYNC_PAYLOAD       4096    /* ohci-defined limit          */
#define WRITER_MINIMUM           128
/* TODO: how to set watermark to AR context size? see fwtty_rx() */
#define HIGH_WATERMARK         32768	/* AR context is 32K	       */

/*
 * Size of bus addr region above 4GB used per port as the recv addr
 * - must be at least as big as the MAX_ASYNC_PAYLOAD
 */
#define FWTTY_PORT_RXFIFO_LEN	MAX_ASYNC_PAYLOAD

/**
 * fw_serial: aggregate used to associate tty ports with specific fw_card
 * @card: fw_card associated with this fw_serial device (1:1 association)
 * @kref: reference-counted multi-port management allows delayed destroy
 * @self: local unit device as 'peer'. Not valid until local unit device
 *         is enumerated.
 * @list: link for insertion into fwserial_list
 * @peer_list: list of local & remote unit devices attached to this card
 * @ports: fixed array of tty_ports provided by this serial device
 */
struct fw_serial {
	struct fw_card	  *card;
	struct kref	  kref;

	struct dentry	  *debugfs;
	struct fwtty_peer *self;

	struct list_head  list;
	struct list_head  peer_list;

	struct fwtty_port *ports[MAX_CARD_PORTS];
};

#define to_serial(ptr, field)	(container_of(ptr, struct fw_serial, field))

#define TTY_DEV_NAME		    "fwtty"	/* ttyFW was taken           */
static const char tty_dev_name[] =  TTY_DEV_NAME;
static const char loop_dev_name[] = "fwloop";

extern struct tty_driver *fwtty_driver;

struct fwtty_port *fwtty_port_get(unsigned index);
/*
 * Returns the max send async payload size in bytes based on the unit device
 * link speed. Self-limiting asynchronous bandwidth (via reducing the payload)
 * is not necessary and does not work, because
 *   1) asynchronous traffic will absorb all available bandwidth (less that
 *	being used for isochronous traffic)
 *   2) isochronous arbitration always wins.
 */
static inline int link_speed_to_max_payload(unsigned speed)
{
	/* Max async payload is 4096 - see IEEE 1394-2008 tables 6-4, 16-18 */
	return min(512 << speed, 4096);
}

#endif /* _FIREWIRE_FWSERIAL_H */


text:
FaceRecognizer
==============


text:
package treeton.gui.trnedit;

import treeton.core.Treenotation;

public interface TrnStorageEditorListener extends TreenotationStorageProvider {
    void storageChanged();

    void attrEditRequest(Treenotation trn);

    int getSelectedIntervalStart();

    int getSelectedIntervalEnd();

    void resetStorageView();
}


text:
Just as easy as it is to create a SQL database, database tables can also be created with the `CREATE` command.

Before adding a table to our `guitars_collection` schema, there's a couple of concepts we need to clarify.

As we learned in the previous unit, the _relational database model_ consists of _spreadsheet like_ structures where data is organized in rows and columns.

When creating tables, this is exactly what we need to specify:

- The name of our table
- The name of our columns
- What kind of data should the tables store

The aforementioned specifications are important in the way that any data `INSERT` attempt that does not comply with each column configuration will be rejected.

### The _guitars collection_ database table

We will call our table: `catalog`

The `catalog` table columns structure will be the following:

| id | name | manufacture_year | brand |
|----|------|------|-------|
|    |      |      |       |

Let's create the table and its header (column names) in the next section.


text:
package net.tootallnate.websocket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * The <tt>WebSocketClient</tt> is an abstract class that expects a valid
 * "ws://" URI to connect to. When connected, an instance recieves important
 * events related to the life of the connection. A subclass must implement
 * <var>onOpen</var>, <var>onClose</var>, and <var>onMessage</var> to be
 * useful. An instance can send messages to it's connected server via the
 * <var>send</var> method.
 * @author Nathan Rajlich
 */
public abstract class WebSocketClient implements Runnable, WebSocketListener {

  // INSTANCE PROPERTIES /////////////////////////////////////////////////////
  /**
   * The URI this client is supposed to connect to.
   */
  private URI uri = null;
  /**
   * The WebSocket instance this client object wraps.
   */
  private WebSocket conn = null;
  /**
   * The SocketChannel instance this client uses.
   */
  private SocketChannel client = null;
  /**
   * The 'Selector' used to get event keys from the underlying socket.
   */
  private Selector selector = null;
  /**
   * Keeps track of whether or not the client thread should continue running.
   */
  private boolean running = false;
  /**
   * The Draft of the WebSocket protocol the Client is adhering to.
   */
  private WebSocketDraft draft = null;
  /**
   * Number 1 used in handshake
   */
  private int number1 = 0;
  /**
   * Number 2 used in handshake
   */
  private int number2 = 0;
  /**
   * Key3 used in handshake
   */
  private byte[] key3 = null;

  // CONSTRUCTORS ////////////////////////////////////////////////////////////
  public WebSocketClient(URI serverURI) {
    this(serverURI, WebSocketDraft.DRAFT76);
  }

  /**
   * Constructs a WebSocketClient instance and sets it to the connect to the
   * specified URI. The client does not attampt to connect automatically. You
   * must call <var>connect</var> first to initiate the socket connection.
   * @param serverUri The <tt>URI</tt> of the WebSocket server to connect to.
   * @throws IllegalArgumentException If <var>draft</var>
   * is WebSocketDraft.AUTO
   */
  public WebSocketClient(URI serverUri, WebSocketDraft draft) {
    this.uri = serverUri;
    if (draft == WebSocketDraft.AUTO) {
      throw new IllegalArgumentException(draft + " is meant for `WebSocketServer` only!");
    }
    this.draft = draft;
  }

  // PUBLIC INSTANCE METHODS /////////////////////////////////////////////////
  /**
   * Gets the URI that this WebSocketClient is connected to.
   * @return The <tt>URI</tt> for this WebSocketClient.
   */
  public URI getURI() {
    return uri;
  }

  @Override
  public WebSocketDraft getDraft() {
    return draft;
  }

  /**
   * Starts a background thread that attempts and maintains a WebSocket
   * connection to the URI specified in the constructor or via <var>setURI</var>.
   * <var>setURI</var>.
   */
  public void connect() {
    if (!running) {
      this.running = true;
      (new Thread(this)).start();
    }
  }

  /**
   * Calls <var>close</var> on the underlying SocketChannel, which in turn
   * closes the socket connection, and ends the client socket thread.
   * @throws IOException When socket related I/O errors occur.
   */
  public void close() throws IOException
  {
	  if (running)
	  {
		  selector.wakeup();
		  conn.close();
	  }
  }

  /**
   * Sends <var>text</var> to the connected WebSocket server.
   * @param text The String to send to the WebSocket server.
   * @throws IOException When socket related I/O errors occur.
   */
  public void send(String text) throws IOException {
    if (conn != null)
    {
      conn.send(text);
    }
  }

  /**
   * Reinitializes and prepares the class to be used for reconnect.
   * @return
   */
  public void releaseAndInitialize()
  {
	  conn = null;
	  client = null;
	  selector = null;
	  running = false;
	  draft = null;
	  number1 = 0;
	  number2 = 0;
	  key3 = null;
  }

  private boolean tryToConnect(InetSocketAddress remote) {
    // The WebSocket constructor expects a SocketChannel that is
    // non-blocking, and has a Selector attached to it.
    try {
      client = SocketChannel.open();
      client.configureBlocking(false);
      client.connect(remote);

      selector = Selector.open();

      this.conn = new WebSocket(client, new LinkedBlockingQueue<ByteBuffer>(), this);
      // At first, we're only interested in the 'CONNECT' keys.
      client.register(selector, SelectionKey.OP_CONNECT);

    } catch (IOException ex) {
    	onIOError(conn, ex);
      return false;
    }

    return true;
  }

  // Runnable IMPLEMENTATION /////////////////////////////////////////////////
  public void run() {
    running = tryToConnect(new InetSocketAddress(uri.getHost(), getPort()));

    while (this.running) {
      try {
        selector.select();
        Set<SelectionKey> keys = selector.selectedKeys();
        Iterator<SelectionKey> i = keys.iterator();

        while (i.hasNext()) {
          SelectionKey key = i.next();
          i.remove();

          if (key.isConnectable()) {
            finishConnect();
          }

          if (key.isReadable()) {
            conn.handleRead();
          }
        }
      } catch (IOException ex) {
    	  onIOError(conn, ex);
      } catch (NoSuchAlgorithmException ex) {
        ex.printStackTrace();
      }
    }

    //System.err.println("WebSocketClient thread ended!");
  }

  private int getPort() {
    int port = uri.getPort();
    return port == -1 ? WebSocket.DEFAULT_PORT : port;
  }

  private void finishConnect() throws IOException {
    if (client.isConnectionPending()) {
      client.finishConnect();
    }

    // Now that we're connected, re-register for only 'READ' keys.
    client.register(selector, SelectionKey.OP_READ);

    sendHandshake();
  }

  private void sendHandshake() throws IOException {
    String path = uri.getPath();
    if (path.indexOf("/") != 0) {
      path = "/" + path;
    }
    int port = getPort();
    String host = uri.getHost() + (port != WebSocket.DEFAULT_PORT ? ":" + port : "");
    String origin = null; // TODO: Make 'origin' configurable
    String request = "GET " + path + " HTTP/1.1\r\n" +
                      "Upgrade: WebSocket\r\n" +
                      "Connection: Upgrade\r\n" +
                      "Host: " + host + "\r\n" +
                      "Origin: " + origin + "\r\n";

    if (this.draft == WebSocketDraft.DRAFT76) {
      request += "Sec-WebSocket-Key1: " + this.generateKey() + "\r\n";
      request += "Sec-WebSocket-Key2: " + this.generateKey() + "\r\n";
      this.key3 = new byte[8];
      (new Random()).nextBytes(this.key3);
    }

    request += "\r\n";

    if (this.key3 != null) {
      conn.socketChannel().write(new ByteBuffer[] {
        ByteBuffer.wrap(request.getBytes(WebSocket.UTF8_CHARSET)),
        ByteBuffer.wrap(this.key3)
      });
    }
    else
    {
      conn.socketChannel().write(ByteBuffer.wrap(request.getBytes(WebSocket.UTF8_CHARSET)));
    }
  }

  private String generateKey() {
    Random r = new Random();
    long maxNumber = 4294967295L;
    long spaces = r.nextInt(12) + 1;
    int max = new Long(maxNumber / spaces).intValue();
    max = Math.abs(max);
    int number = r.nextInt(max) + 1;
    if (this.number1 == 0) {
      this.number1 = number;
    }
    else {
      this.number2 = number;
    }
    long product = number * spaces;
    String key = Long.toString(product);
    //always insert atleast one random character
    int numChars = r.nextInt(12)+1;
    for (int i=0; i < numChars; i++){
      int position = r.nextInt(key.length());
      position = Math.abs(position);
      char randChar = (char)(r.nextInt(95) + 33);
      //exclude numbers here
      if(randChar >= 48 && randChar <= 57){
        randChar -= 15;
      }
      key = new StringBuilder(key).insert(position, randChar).toString();
    }
    for (int i = 0; i < spaces; i++){
      int position = r.nextInt(key.length() - 1) + 1;
      position = Math.abs(position);
      key = new StringBuilder(key).insert(position,"\u0020").toString();
    }
    return key;
  }

  // WebSocketListener IMPLEMENTATION ////////////////////////////////////////
  /**
   * Parses the server's handshake to verify that it's a valid WebSocket
   * handshake.
   * @param conn The {@link WebSocket} instance who's handshake has been recieved.
   *             In the case of <tt>WebSocketClient</tt>, this.conn == conn.
   * @param handshake The entire UTF-8 decoded handshake from the connection.
   * @return <var>true</var> if <var>handshake</var> is a valid WebSocket server
   *         handshake, <var>false</var> otherwise.
   * @throws IOException When socket related I/O errors occur.
   * @throws NoSuchAlgorithmException
   */
  public boolean onHandshakeRecieved(WebSocket conn, String handshake, byte[] reply) throws IOException, NoSuchAlgorithmException {
    // TODO: Do some parsing of the returned handshake, and close connection
    // (return false) if we recieved anything unexpected.
    if(this.draft == WebSocketDraft.DRAFT76) {
      if (reply == null) {
        return false;
      }
      byte[] challenge = new byte[] {
        (byte)( this.number1 >> 24 ),
        (byte)( (this.number1 << 8) >> 24 ),
        (byte)( (this.number1 << 16) >> 24 ),
        (byte)( (this.number1 << 24) >> 24 ),
        (byte)(  this.number2 >> 24 ),
        (byte)( (this.number2 << 8) >> 24 ),
        (byte)( (this.number2 << 16) >> 24 ),
        (byte)( (this.number2 << 24) >> 24 ),
        this.key3[0],
        this.key3[1],
        this.key3[2],
        this.key3[3],
        this.key3[4],
        this.key3[5],
        this.key3[6],
        this.key3[7]
      };
      MessageDigest md5 = MessageDigest.getInstance("MD5");
      byte[] expected = md5.digest(challenge);
      for (int i = 0; i < reply.length; i++) {
        if (expected[i] != reply[i]) {
          return false;
        }
      }
    }
    return true;
  }

  /**
   * Calls subclass' implementation of <var>onMessage</var>.
   * @param conn
   * @param message
   */
  public void onMessage(WebSocket conn, String message) {
    onMessage(message);
  }

  /**
   * Calls subclass' implementation of <var>onOpen</var>.
   * @param conn
   */
  public void onOpen(WebSocket conn) {
    onOpen();
  }

  /**
   * Calls subclass' implementation of <var>onClose</var>.
   * @param conn
   */
  public void onClose(WebSocket conn)
  {
	  if (running)
	  {
		  onClose();
	  }

	  releaseAndInitialize();
  }

  /**
   * Calls subclass' implementation of <var>onIOError</var>.
   * @param conn
   */
  public void onIOError(WebSocket conn, IOException ex)
  {
	  releaseAndInitialize();
	  onIOError(ex);
  }

  // ABTRACT METHODS /////////////////////////////////////////////////////////
  public abstract void onMessage(String message);
  public abstract void onOpen();
  public abstract void onClose();
  public abstract void onIOError(IOException ex);
}


text:
layout: redirect
newurl: http://pmem.io/pmdk/manpages/linux/v1.2/pmempool/pmempool-info.1.html
---


text:
.droplinebar{
overflow: hidden;
}

.droplinebar ul{
margin: 0;
padding: 0;
float: left;
width: 100%;
font: bold 13px Arial;
background: #004080 url(/s1games/bundles/ceradapp/images/bluedefault.gif) center center repeat-x; /*default background of menu bar*/
}

.droplinebar ul li{
display: inline;
}

.droplinebar ul li a{
float: left;
color: white;
padding: 9px 7px;
text-decoration: none;
}

.droplinebar ul li a:visited{
color: white;
}

.droplinebar ul li a:hover, .droplinebar ul li .current{ /*background of main menu bar links onMouseover*/
color: white;
background: transparent url(/s1games/bundles/ceradapp/images/blueactive.gif) center center repeat-x;
}

/* Sub level menus*/
.droplinebar ul li ul{
position: absolute;
z-index: 100;
left: 0;
top: 0;
background: #0054a8; /*sub menu background color */
visibility: hidden;
}

/* Sub level menu links style */
.droplinebar ul li ul li a{
font: normal 13px Verdana;
padding: 6px 8px;
margin: 0;
border-bottom: 1px solid navy;
}

.droplinebar ul li ul li a:hover{ /*sub menu links' background color onMouseover */
background: #004080;
}

@media print
{
  .droplinebar
  {
    display:none;
  }
}


text:
<?php

final class PhabricatorAuditCommitStatusConstants {

  const NONE                = 0;
  const NEEDS_AUDIT         = 1;
  const CONCERN_RAISED      = 2;
  const PARTIALLY_AUDITED   = 3;
  const FULLY_AUDITED       = 4;

  public static function getStatusNameMap() {
    static $map = array(
      self::NONE                => 'None',
      self::NEEDS_AUDIT         => 'Audit Required',
      self::CONCERN_RAISED      => 'Concern Raised',
      self::PARTIALLY_AUDITED   => 'Partially Audited',
      self::FULLY_AUDITED       => 'Audited',
    );

    return $map;
  }

  public static function getStatusName($code) {
    return idx(self::getStatusNameMap(), $code, 'Unknown');
  }

  public static function getOpenStatusConstants() {
    return array(
      self::CONCERN_RAISED,
      self::NEEDS_AUDIT,
    );
  }

}


text:
<?php namespace App;

class Session extends \Facade
{

	function __construct()
	{
		// ini_set('session.save_handler', 'files');
		// session_set_save_handler($this, true);
		// session_save_path(storage_path() . '/sessions');

		// ini_set('session.use_cookies', 1);
  //       ini_set('session.use_only_cookies', 1);

  //       session_name('mvc_session');

		// session_start();		if ( is_session_started() === FALSE ) session_start();
	}

	public function has($key='')
	{
		return array_has($_SESSION, $key);
	}

	public function put($key, $value)
	{
		return array_set($_SESSION, $key, $value);
	}

	public function all()
	{
		return $_SESSION;
	}

	public function get($key, $default=null)
	{
		return array_has($_SESSION, $key) ? array_get($_SESSION, $key, $default) : $default;
	}

	public function forget($key='')
	{
		unset($_SESSION[$key]);
		return true;
	}

	public function destroy()
	{
		// if (session_id() === '') {
  //           return false;
  //       }

        $_SESSION = [];

		// return session_destroy();
		return true;
	}

	public function refresh()
    {
        return session_regenerate_id(true);
    }

	function __destruct()
	{
		$_SESSION = [];
	}
}


text:
define({
  "enableUndoRedo": "Aktivera Ångra/Upprepa",
  "toolbarVisible": "Verktygsfält synligt",
  "toolbarOptions": "Alternativ för verktygsfält",
  "mergeVisible": "Sammanfoga",
  "cutVisible": "Beskär",
  "reshapeVisible": "Omforma",
  "back": "Bakåt",
  "label": "Lager",
  "edit": "Redigerbar",
  "update": "Inaktivera Uppdatera geometri",
  "fields": "Fält",
  "actions": "Åtgärder",
  "editpageName": "Namn",
  "editpageAlias": "Alias",
  "editpageVisible": "Synlig",
  "editpageEditable": "Redigerbar",
  "noLayers": "Inga redigerbara geoobjektslager är tillgängliga",
  "configureFields": "Konfigurera lagerfält",
  "useFilterEdit": "Använd mallfilter för geoobjekt",
  "display": "Visa",
  "autoApplyEditWhenGeometryIsMoved": "Använd redigeringen automatiskt när geometrin flyttas",
  "snappingTolerance": "Ange snappningstoleransen i pixlar",
  "popupTolerance": "Ange toleransen för attributredigeringspopupen i pixlar",
  "stickyMoveTolerance": "Ange toleransen för klistrig flytt i pixlar",
  "usingSaveButton": "Tillämpa inte redigeringar på attributen förrän du klickar på knappen Spara",
  "generalSettings": "Allmänna inställningar",
  "editableLayersSetting": "Redigerbara lagerinställningar",
  "honorTheWebMapSetting": "Ta hänsyn till inställningar i webbkartan",
  "honorTheWebMapSettingTip1": "Dessa inställningar omfattar:",
  "honorTheWebMapSettingTip2": "Vilka lager som kan redigeras",
  "honorTheWebMapSettingTip3": "De fält du vill visa och redigera",
  "honorTheWebMapSettingTip4": "Alias, ordning och format för fält",
  "customSettings": "Anpassade inställningar"
});


text:
package org.jclouds.openstack.nova.v2_0.compute.functions;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import java.util.Map;

import javax.inject.Inject;

import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.domain.Location;
import org.jclouds.openstack.nova.v2_0.domain.Flavor;
import org.jclouds.openstack.nova.v2_0.domain.regionscoped.FlavorInRegion;

import com.google.common.base.Function;
import com.google.common.base.Supplier;

/**
 * A function for transforming the nova specific FlavorInRegion object to the generic Hardware object.
 */
public class FlavorInRegionToHardware implements Function<FlavorInRegion, Hardware> {

   private final Supplier<Map<String, Location>> locationIndex;

   @Inject
   public FlavorInRegionToHardware(Supplier<Map<String, Location>> locationIndex) {
      this.locationIndex = checkNotNull(locationIndex, "locationIndex");
   }

   @Override
   public Hardware apply(FlavorInRegion flavorInRegion) {
      Location location = locationIndex.get().get(flavorInRegion.getRegion());
      checkState(location != null, "location %s not in locationIndex: %s", flavorInRegion.getRegion(), locationIndex.get());
      Flavor flavor = flavorInRegion.getFlavor();
      return new HardwareBuilder().id(flavorInRegion.slashEncode()).providerId(flavor.getId()).name(flavor.getName())
               .ram(flavor.getRam()).processor(new Processor(flavor.getVcpus(), 1.0)).volume(
                        new VolumeImpl(Float.valueOf(flavor.getDisk()), true, true)).location(location).build();
   }
}


text:
package com.example.androidthings.robocar.companion;

import com.example.androidthings.robocar.shared.NearbyConnection;
import com.example.androidthings.robocar.shared.model.AdvertisingInfo;

/**
 * Handle for a connection to a Robocar, providing convenient methods for both authenticating the
 * connection and transmitting data through it.
 */
public class RobocarConnection extends NearbyConnection {

    private final RobocarDiscoverer mRobocarDiscoverer;
    private final AdvertisingInfo mAdvertisingInfo;

    private final boolean mAutoConnect;

    public RobocarConnection(String endpointId, AdvertisingInfo advertisingInfo,
            RobocarDiscoverer robocarDiscoverer, boolean autoConnect) {
        super(endpointId, robocarDiscoverer);
        if (advertisingInfo == null) {
            throw new IllegalArgumentException("AdvertisingInfo cannot be null");
        }
        mAdvertisingInfo = advertisingInfo;
        mRobocarDiscoverer = robocarDiscoverer;
        mAutoConnect = autoConnect;
    }

    public AdvertisingInfo getAdvertisingInfo() {
        return mAdvertisingInfo;
    }

    public boolean isAutoConnect() {
        return mAutoConnect;
    }

    public void accept() {
        if (getState() == ConnectionState.AUTHENTICATING) {
            mRobocarDiscoverer.acceptConnection();
        }
    }

    public void reject() {
        if (getState() == ConnectionState.AUTHENTICATING) {
            mRobocarDiscoverer.rejectConnection();
        }
    }

    public void disconnect() {
        mRobocarDiscoverer.disconnect();
    }
}


text:
SfnRegistry.register(:base, :provider => :heat) do |*_|
  "heat"
end


text: Fix in-place modification of `FieldInfo` that caused problems with PEP 593 type aliases


text:
The purpose of this program is to further understanding of physics
through simulations.

Simulation          |   What Can Be Learned
----------          |   -------------------
Expanding Gas       |   Entropy, and Adiabatic Heating & Cooling
Gravity             |   Orbits, Gravity Boost, Solar Wobble
Expanding Universe  |   Red Shift, Size of the Universe
Random Walk         |   Expected distance in a random walk.

# ACKNOWLEDGMENTS

[Simple Direct Media Layer](http://www.libsdl.org)

[NASA Planetary Fact Sheets](http://nssdc.gsfc.nasa.gov/planetary/factsheet)

# BUILD LINUX VERSION

I build on Fedora 31.

In addition to Development Tools, the following packages must be installed:

* SDL2-devel
* SDL2_ttf-devel
* SDL2_mixer-devel
* libpng-devel

To build, just run make.

# BUILD ANDROID VERSION

Refer to android-project/README.txt


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>pymatgen.io.lammps.sets — pymatgen 2018.7.23 documentation</title>
    <link rel="stylesheet" href="../../../../_static/proBlue.css" type="text/css" />
    <link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../../../../_static/favicon.ico"/>
    <link rel="index" title="Index" href="../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../search.html" />

Navigation

          index

          modules |

pymatgen 2018.7.23 documentation »

Module code »

pymatgen »

Source code for pymatgen.io.lammps.sets

# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.

from __future__ import division, print_function, unicode_literals, absolute_import

"""
This module implements classes for reading and generating Lammps inputset.

For the ease of management we divide LAMMPS input into 2 files:

    1.Data file: All structure related settings such as the atomic positions,
            bonds, angles, dihedrals, corresponding parametrizations etc are
            set in the data file.

    2. Control/input file: This is the main input file that should be fed to the
            lammps binary. The main input file consists of the path to the
            afore-mentioned data file and the job control parameters such as
            the ensemble type(NVT, NPT etc), max number of iterations etc.
"""

import os
import six

from monty.json import MSONable, MontyDecoder

from pymatgen.io.lammps.data import LammpsData
from pymatgen.io.lammps.input import LammpsInput

__author__ = "Kiran Mathew"
__email__ = "kmathew@lbl.gov"

[docs]class LammpsInputSet(MSONable):

    def __init__(self, name, lammps_input, lammps_data=None,
                 data_filename="in.data", user_lammps_settings=None):
        """
        Implementation of LammpsInputSet that is initialized from a dict
        settings. It is typically used by other LammpsInputSets for
        initialization from json or yaml source files.

        Args:
            name (str): A name for the input set.
            lammps_input (LammpsInput): The config dictionary to use.
            lammps_data (LammpsData): LammpsData object
            data_filename (str): name of the the lammps data file.
                Note: this will override the value for 'data_file' key in lammps_input
            user_lammps_settings (dict): User lammps settings. This allows a user
                to override lammps settings, e.g., setting a different force field
                or bond type.
        """
        self.name = name
        self.lines = []
        self.lammps_input = lammps_input
        self.lammps_data = lammps_data
        self.data_filename = data_filename
        self.lammps_input.settings["data_file"] = data_filename
        self.user_lammps_settings = user_lammps_settings or {}
        self.lammps_input.settings.update(self.user_lammps_settings)

[docs]    def write_input(self, input_filename, data_filename=None):
        """
        Get the string representation of the main input file and write it.
        Also writes the data file if the lammps_data attribute is set.

        Args:
            input_filename (string): name of the input file
            data_filename (string): override the data file name with this
        """
        if data_filename:
            data_filename = os.path.abspath(os.path.join(os.getcwd(), data_filename))
        if data_filename and ("data_file" in self.lammps_input.settings):
            self.lammps_input.settings["data_file"] = data_filename
            self.data_filename = data_filename
        self.lammps_input.write_file(input_filename)
        # write the data file if present
        if self.lammps_data:
            self.lammps_data.write_file(filename=self.data_filename)

[docs]    @classmethod
    def from_file(cls, name, input_template, user_settings,
                  lammps_data=None, data_filename="in.data"):
        """
        Returns LammpsInputSet from  input file template and input data.

        Args:
            name (str)
            input_template (string): path to the input template file.
            user_settings (dict): User lammps settings, the keys must
                correspond to the keys in the template.
            lammps_data (string/LammpsData): path to the
                data file or an appropriate object
            data_filename (string): name of the the lammps data file.

        Returns:
            LammpsInputSet
        """
        user_settings["data_file"] = data_filename
        lammps_input = LammpsInput.from_file(input_template, user_settings)
        if isinstance(lammps_data, six.string_types):
            lammps_data = LammpsData.from_file(lammps_data)
        return cls(name, lammps_input, lammps_data=lammps_data,
                   data_filename=data_filename)

[docs]    def as_dict(self):
        d = MSONable.as_dict(self)
        if hasattr(self, "kwargs"):
            d.update(**self.kwargs)
        d["lammps_input"] = self.lammps_input.as_dict()
        return d

[docs]    @classmethod
    def from_dict(cls, d):
        decoded = {k: MontyDecoder().process_decoded(v) for k, v in d.items()
                   if k not in ["@module", "@class", "lammps_input"]}
        decoded["lammps_input"] = LammpsInput.from_dict(d["lammps_input"])
        return cls(**decoded)

Quick search

    <form class="search" action="../../../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          modules |

pymatgen 2018.7.23 documentation »

Module code »

pymatgen »

        © Copyright 2011, Pymatgen Development Team.
      Created using Sphinx 1.7.6.

This page uses
Google Analytics to collect statistics. You can disable it by blocking
the JavaScript coming from www.google-analytics.com.


text:
package io.crnk.core.module.internal;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.crnk.core.engine.filter.FilterBehavior;
import io.crnk.core.engine.filter.ResourceFilter;
import io.crnk.core.engine.filter.ResourceFilterContext;
import io.crnk.core.engine.filter.ResourceFilterDirectory;
import io.crnk.core.engine.http.HttpMethod;
import io.crnk.core.engine.http.HttpRequestContextProvider;
import io.crnk.core.engine.information.resource.ResourceField;
import io.crnk.core.engine.information.resource.ResourceFieldType;
import io.crnk.core.engine.information.resource.ResourceInformation;
import io.crnk.core.engine.internal.utils.PreconditionUtil;
import io.crnk.core.engine.query.QueryContext;
import io.crnk.core.engine.registry.RegistryEntry;
import io.crnk.core.engine.registry.ResourceRegistry;
import io.crnk.core.exception.ForbiddenException;
import io.crnk.core.exception.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ResourceFilterDirectoryImpl implements ResourceFilterDirectory {

    private static final Logger LOGGER = LoggerFactory.getLogger(ResourceFilterDirectoryImpl.class);

    private final List<ResourceFilter> filters;

    private final HttpRequestContextProvider requestContextProvider;

    private final ResourceRegistry resourceRegistry;

    public ResourceFilterDirectoryImpl(List<ResourceFilter> filters, HttpRequestContextProvider requestContextProvider,
                                       ResourceRegistry resourceRegistry) {
        this.filters = filters;
        this.requestContextProvider = requestContextProvider;
        this.resourceRegistry = resourceRegistry;
    }

    @Override
    public FilterBehavior get(ResourceInformation resourceInformation, HttpMethod method, QueryContext queryContext) {
        Map<Object, FilterBehavior> map = getCache(method, queryContext);
        if (queryContext != null) {
            FilterBehavior behavior = map.get(resourceInformation);
            if (behavior != null) {
                return behavior;
            }
        }

        ResourceFilterContext filterContext = () -> queryContext;
        FilterBehavior behavior = FilterBehavior.NONE;
        for (ResourceFilter filter : filters) {
            behavior = behavior.merge(filter.filterResource(filterContext, resourceInformation, method));
            if (behavior == FilterBehavior.FORBIDDEN) {
                break;
            }
        }
        if (queryContext != null) {
            map.put(resourceInformation, behavior);
        }
        return behavior;
    }

    @Override
    public FilterBehavior get(ResourceField field, HttpMethod method, QueryContext queryContext) {
    	PreconditionUtil.verify(field != null, "field cannot be null");
        Map<Object, FilterBehavior> map = getCache(method, queryContext);

        FilterBehavior behavior = map.get(field);
        if (behavior != null) {
            return behavior;
        }

        boolean modifiable = field.getAccess().allows(method);

        // TODO field.getAccess not fine-grained, should change in the future
        behavior = modifiable ? FilterBehavior.NONE : FilterBehavior.IGNORED;

        ResourceFilterContext filterContext = () -> queryContext;
        for (ResourceFilter filter : filters) {
            behavior = behavior.merge(filter.filterField(filterContext, field, method));
            if (behavior == FilterBehavior.FORBIDDEN) {
                break;
            }
        }

        if (field.getResourceFieldType() == ResourceFieldType.RELATIONSHIP) {
            // for relationships opposite site must also be accessible (at least with GET)
            String oppositeResourceType = field.getOppositeResourceType();

            if (oppositeResourceType != null && resourceRegistry.hasEntry(oppositeResourceType)) {
				RegistryEntry oppositeRegistryEntry = resourceRegistry.getEntry(oppositeResourceType);
                ResourceInformation oppositeResourceInformation = oppositeRegistryEntry.getResourceInformation();

                // consider checking more than GET? intersection/union of multiple?
                behavior = behavior.merge(get(oppositeResourceInformation, HttpMethod.GET, queryContext));
            } else {
                LOGGER.warn("opposite side {} not found", oppositeResourceType);
            }
        }

        map.put(field, behavior);
        return behavior;
    }

    private Map<Object, FilterBehavior> getCache(HttpMethod method, QueryContext queryContext) {
        if (queryContext == null) {
            return null; // no caching without context
        }
        String key = ResourceFilterDirectoryImpl.class.getSimpleName() + method;
        Map<Object, FilterBehavior> cache = (Map<Object, FilterBehavior>) queryContext.getAttribute(key);
        if (cache == null) {
            cache = new ConcurrentHashMap<>();
            queryContext.setAttribute(key, cache);
        }
        return cache;
    }

    /**
     * Allows to check whether the given field can be written.
     *
     * @param field from the information model or null if is a dynamic field (like JsonAny).
     */
    @Override
    public boolean canAccess(ResourceField field, HttpMethod method, QueryContext queryContext, boolean allowIgnore) {
        if (field == null) {
            return true;
        }
        FilterBehavior filterBehavior = get(field, method, queryContext);
        if (filterBehavior == FilterBehavior.NONE) {
            return true;
        }
        if (filterBehavior == FilterBehavior.FORBIDDEN || !allowIgnore) {
            String resourceType = field.getResourceInformation().getResourceType();
            throw new ForbiddenException("field '" + resourceType + "." + field.getJsonName() + "' cannot be accessed for " + method);
        } else if (filterBehavior == FilterBehavior.UNAUTHORIZED || !allowIgnore) {
            String resourceType = field.getResourceInformation().getResourceType();
            throw new UnauthorizedException("field '" + resourceType + "." + field.getJsonName() + "' can only be access when logged in for " + method);
        } else {
            LOGGER.debug("ignoring field {}", field.getUnderlyingName());
            PreconditionUtil.verifyEquals(FilterBehavior.IGNORED, filterBehavior, "unknown behavior");
            return false;
        }
    }
}


text:
package org.apache.excalibur.instrument.client;

public interface InstrumentableData
    extends ElementData
{
    /**
     * Returns the registered flag of the remote object.
     *
     * @return The registered flag of the remote object.
     */
    boolean isRegistered();

    /**
     * Gets a thread-safe snapshot of the child instrumentable list.
     *
     * @return A thread-safe snapshot of the child instrumentable list.
     */
    InstrumentableData[] getInstrumentables();

    /**
     * Gets a thread-safe snapshot of the instrument list.
     *
     * @return A thread-safe snapshot of the instrument list.
     */
    InstrumentData[] getInstruments();
}


text:
class Cat {
    constructor(name: string, willScratch: number) {
        this._name = name;
        this._willScratch = willScratch;
    }

    private _name: string;
    get Name() {
        return this._name;
    }

    private _willScratch: number;
    get WillScratch() {
        return this._willScratch;
    }

    private _mood: Moods;
    get Mood(): Moods { return this._mood }
    set Mood(value: Moods) {
        this._mood = value;
    }
}


text:
namespace WTS {

class Project;
class WaveformWidget;

class SampleNameValidator : public QValidator
{
    Q_OBJECT
public:
    explicit SampleNameValidator(Project * project, WaveformWidget * waveform);

protected:
    State validate ( QString & input, int & pos ) const;

    Project * m_project;
    WaveformWidget * m_waveform;
};

}

#endif // SAMPLENAMEVALIDATOR_HPP


text:
import baseClone from './_baseClone.js';
import baseMatches from './_baseMatches.js';

/**
 * Creates a function that performs a partial deep comparison between a given
 * object and `source`, returning `true` if the given object has equivalent
 * property values, else `false`.
 *
 * **Note:** The created function is equivalent to `_.isMatch` with `source`
 * partially applied.
 *
 * Partial comparisons will match empty array and empty object `source`
 * values against any array or object value, respectively. See `_.isEqual`
 * for a list of supported value comparisons.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Util
 * @param {Object} source The object of property values to match.
 * @returns {Function} Returns the new spec function.
 * @example
 *
 * var objects = [
 *   { 'a': 1, 'b': 2, 'c': 3 },
 *   { 'a': 4, 'b': 5, 'c': 6 }
 * ];
 *
 * _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));
 * // => [{ 'a': 4, 'b': 5, 'c': 6 }]
 */
function matches(source) {
  return baseMatches(baseClone(source, true));
}

export default matches;


text:
package io.gravitee.am.identityprovider.http.authentication;

import io.gravitee.am.common.exception.authentication.AuthenticationException;
import io.gravitee.am.common.exception.authentication.InternalAuthenticationServiceException;
import io.gravitee.am.common.oidc.StandardClaims;
import io.gravitee.am.identityprovider.api.*;
import io.gravitee.am.identityprovider.http.HttpIdentityProviderResponse;
import io.gravitee.am.identityprovider.http.authentication.spring.HttpAuthenticationProviderConfiguration;
import io.gravitee.am.identityprovider.http.configuration.HttpIdentityProviderConfiguration;
import io.gravitee.am.identityprovider.http.configuration.HttpResourceConfiguration;
import io.gravitee.am.identityprovider.http.configuration.HttpResponseErrorCondition;
import io.gravitee.common.http.HttpHeader;
import io.gravitee.common.http.HttpHeaders;
import io.gravitee.common.http.MediaType;
import io.gravitee.el.TemplateEngine;
import io.reactivex.Maybe;
import io.reactivex.Single;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.MultiMap;
import io.vertx.reactivex.core.buffer.Buffer;
import io.vertx.reactivex.ext.web.client.HttpRequest;
import io.vertx.reactivex.ext.web.client.HttpResponse;
import io.vertx.reactivex.ext.web.client.WebClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Import;

import java.lang.reflect.Constructor;
import java.util.*;

/**
 * @author Titouan COMPIEGNE (titouan.compiegne at graviteesource.com)
 * @author GraviteeSource Team
 */
@Import(HttpAuthenticationProviderConfiguration.class)
public class HttpAuthenticationProvider implements AuthenticationProvider {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpAuthenticationProvider.class);
    private static final String PRINCIPAL_CONTEXT_KEY = "principal";
    private static final String CREDENTIALS_CONTEXT_KEY = "credentials";
    private static final String AUTHENTICATION_RESPONSE_CONTEXT_KEY = "authenticationResponse";

    @Autowired
    @Qualifier("idpHttpAuthWebClient")
    private WebClient client;

    @Autowired
    private HttpIdentityProviderConfiguration configuration;

    @Autowired
    private IdentityProviderMapper mapper;

    @Autowired
    private IdentityProviderRoleMapper roleMapper;

    @Override
    public Maybe<User> loadUserByUsername(Authentication authentication) {
        try {
            // prepare context
            TemplateEngine templateEngine = authentication.getContext().getTemplateEngine();
            templateEngine.getTemplateContext().setVariable(PRINCIPAL_CONTEXT_KEY, authentication.getPrincipal());
            templateEngine.getTemplateContext().setVariable(CREDENTIALS_CONTEXT_KEY, authentication.getCredentials());

            // prepare request
            final HttpResourceConfiguration resourceConfiguration = configuration.getAuthenticationResource();
            final String authenticationURI = templateEngine.getValue(resourceConfiguration.getBaseURL(), String.class);
            final HttpMethod authenticationHttpMethod = HttpMethod.valueOf(resourceConfiguration.getHttpMethod().toString());
            final List<HttpHeader> authenticationHttpHeaders = resourceConfiguration.getHttpHeaders();
            final String authenticationBody = resourceConfiguration.getHttpBody();
            final HttpRequest<Buffer> httpRequest = client.requestAbs(authenticationHttpMethod, authenticationURI);
            final List<HttpResponseErrorCondition> errorConditions = resourceConfiguration.getHttpResponseErrorConditions();

            // set headers
            if (authenticationHttpHeaders != null) {
                authenticationHttpHeaders.forEach(header -> {
                    String extValue = templateEngine.getValue(header.getValue(), String.class);
                    httpRequest.putHeader(header.getName(), extValue);
                });
            }

            // set body
            Single<HttpResponse<Buffer>> responseHandler;
            if (authenticationBody != null && !authenticationBody.isEmpty()) {
                String bodyRequest = templateEngine.getValue(authenticationBody, String.class);
                if (!httpRequest.headers().contains(HttpHeaders.CONTENT_TYPE)) {
                    httpRequest.putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(bodyRequest.length()));
                    responseHandler = httpRequest.rxSendBuffer(Buffer.buffer(bodyRequest));
                } else {
                    String contentTypeHeader = httpRequest.headers().get(HttpHeaders.CONTENT_TYPE);
                    switch (contentTypeHeader) {
                        case(MediaType.APPLICATION_JSON):
                            responseHandler = httpRequest.rxSendJsonObject(new JsonObject(bodyRequest));
                            break;
                        case(MediaType.APPLICATION_FORM_URLENCODED):
                            Map<String, String> queryParameters = format(bodyRequest);
                            MultiMap multiMap = MultiMap.caseInsensitiveMultiMap();
                            multiMap.setAll(queryParameters);
                            responseHandler = httpRequest.rxSendForm(multiMap);
                            break;
                        default:
                            httpRequest.putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(bodyRequest.length()));
                            responseHandler = httpRequest.rxSendBuffer(Buffer.buffer(bodyRequest));
                    }
                }
            } else {
                responseHandler = httpRequest.rxSend();
            }

            return responseHandler
                    .toMaybe()
                    .map(httpResponse -> {
                        String responseBody =  httpResponse.bodyAsString();
                        // put response into template variable for EL
                        templateEngine.getTemplateContext().setVariable(AUTHENTICATION_RESPONSE_CONTEXT_KEY,
                                new HttpIdentityProviderResponse(httpResponse, responseBody));

                        // process authentication response
                        Exception lastException = null;
                        if (errorConditions != null) {
                            Iterator<HttpResponseErrorCondition> iter = errorConditions.iterator();
                            while (iter.hasNext() && lastException == null) {
                                HttpResponseErrorCondition errorCondition = iter.next();
                                if (templateEngine.getValue(errorCondition.getValue(), Boolean.class)) {
                                    Class<? extends Exception> clazz = (Class<? extends Exception>) Class.forName(errorCondition.getException());
                                    if (errorCondition.getMessage() != null) {
                                        String errorMessage = templateEngine.getValue(errorCondition.getMessage(), String.class);
                                        Constructor<?> constructor = clazz.getConstructor(String.class);
                                        lastException = clazz.cast(constructor.newInstance(new Object[]{errorMessage}));
                                    } else {
                                        lastException = clazz.newInstance();
                                    }
                                }
                            }
                        }

                        // if user authentication failed, throw exception
                        if (lastException != null) {
                            throw lastException;
                        }
                        // unable to get user information, throw exception
                        if (responseBody == null) {
                            throw new InternalAuthenticationServiceException("Unable to find user information");
                        }
                        // else connect the user
                        return createUser(authentication.getContext(), new JsonObject(responseBody).getMap());
                    })
                    .onErrorResumeNext(ex -> {
                        if (ex instanceof AuthenticationException) {
                            return Maybe.error(ex);
                        }
                        LOGGER.error("An error has occurred while calling the remote HTTP identity provider {}", ex);
                        return Maybe.error(new InternalAuthenticationServiceException("An error has occurred while calling the remote HTTP identity provider", ex));
                    });
        } catch (Exception ex) {
            LOGGER.error("An error has occurred while authenticating the user {}", ex);
            return Maybe.error(new InternalAuthenticationServiceException("An error has occurred while authenticating the user", ex));
        }
    }

    @Override
    public Maybe<User> loadUserByUsername(String username) {
        return Maybe.empty();
    }

    private User createUser(AuthenticationContext authContext, Map<String, Object> attributes) {
        // apply user mapping
        Map<String, Object> mappedAttributes = applyUserMapping(authContext, attributes);

        // sub claim is required
        if (mappedAttributes.isEmpty() || mappedAttributes.get(StandardClaims.SUB) == null) {
            throw new InternalAuthenticationServiceException("The 'sub' claim for the user is required");
        }

        // apply role mapping
        List<String> roles = applyRoleMapping(authContext, attributes);

        // create the user
        String username = mappedAttributes.getOrDefault(StandardClaims.PREFERRED_USERNAME, mappedAttributes.get(StandardClaims.SUB)).toString();
        DefaultUser user = new DefaultUser(username);
        user.setId(mappedAttributes.get(StandardClaims.SUB).toString());
        // set additional information
        Map<String, Object> additionalInformation = new HashMap<>();
        additionalInformation.putAll(mappedAttributes);
        // update username if user mapping has been changed
        if (additionalInformation.containsKey(StandardClaims.PREFERRED_USERNAME)) {
            user.setUsername(additionalInformation.get(StandardClaims.PREFERRED_USERNAME).toString());
        }
        user.setAdditionalInformation(additionalInformation);
        // set user roles
        user.setRoles(roles);
        return user;
    }

    private Map<String, Object> applyUserMapping(AuthenticationContext authContext, Map<String, Object> attributes) {
        if (!mappingEnabled()) {
            return attributes;
        }
        return this.mapper.apply(authContext, attributes);
    }

    private List<String> applyRoleMapping(AuthenticationContext authContext, Map<String, Object> attributes) {
        if (!roleMappingEnabled()) {
            return Collections.emptyList();
        }
        return this.roleMapper.apply(authContext, attributes);
    }

    private boolean mappingEnabled() {
        return this.mapper != null;
    }

    private boolean roleMappingEnabled() {
        return this.roleMapper != null;
    }

    private static Map<String, String> format(String query) {
        Map<String, String> queryPairs = new LinkedHashMap<String, String>();
        String[] pairs = query.split("&");
        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            queryPairs.put(pair.substring(0, idx), pair.substring(idx + 1));
        }
        return queryPairs;
    }
}


text:
function Component() {}

module.exports = Component;

Component.prototype.view = __dirname;

Component.prototype.init = function(model) {
    this.model.set('state', 'normal');

    /**
     * If true, the button is currently active either because the
     * user is holding down the button, or the button is a toggle
     * and is currently in the active state.
     *
     * @attribute active
     * @type boolean
     * @default false
     */
    this.model.setNull('active', false);

    /**
     * If true, the element currently has focus due to keyboard
     * navigation.
     *
     * @attribute focused
     * @type boolean
     * @default false
     */
    this.model.setNull('focused', false);

    /**
     * If true, the user is currently holding down the button.
     *
     * @attribute pressed
     * @type boolean
     * @default false
     */
    this.model.setNull('pressed', false);

    /**
     * If true, the user cannot interact with this element.
     *
     * @attribute disabled
     * @type boolean
     * @default false
     */
    this.model.setNull('disabled', false);

    /**
     * If true, the button toggles the active state with each tap.
     * Otherwise, the button becomes active when the user is holding
     * it down.
     *
     * @attribute isToggle
     * @type boolean
     * @default false
     */
    this.model.setNull('isToggle', false);

    //----------------------------------------------------------------------
    /**
     * The label of the button.
     *
     * @attribute label
     * @type string
     * @default ''
     */
    this.model.setNull('label', null);

    /**
     * If true, the button will be styled as a "raised" button.
     *
     * @attribute raised
     * @type boolean
     * @default false
     */
    this.model.setNull('raised', false);

    /**
     * (optional) The URL of an image for an icon to use in the button.
     * Should not use `icon` property if you are using this property.
     *
     * @attribute iconSrc
     * @type string
     * @default ''
     */
    this.model.setNull('src', null);

    /**
     * (optional) Specifies the icon name or index in the set of icons
     * available in the icon set. If using this property, load the icon
     * set separately where the icon is used. Should not use `src`
     * if you are using this property.
     *
     * @attribute icon
     * @type string
     * @default ''
     */
    this.model.setNull('icon', null);

    this.model.setNull('z', 0);

    this.model.setNull('tabindex', 0);

    this.model.setNull('splash', false);

    this.model.setNull('rippled', true);
}
Component.prototype.create = function(model) {
    this.model.on('all', 'active', (function (path, event, active) {
        if (this.model.get('active')) {
            // FIXME: remove when paper-ripple can have a default 'down' state.
            if (!this.lastEvent) {
                var rect = this.wrapper.getBoundingClientRect();
                this.lastEvent = {
                    x: rect.left + rect.width / 2,
                    y: rect.top + rect.height / 2
                }
            }
            this.ripple.downAction(this.lastEvent);
        } else {
            this.ripple.upAction();
        }
        this.adjustZ();
    }).bind(this));
    this.model.on('all', 'focused', (function (path, event, focused) {
        this.adjustZ();
    }).bind(this));
    this.model.on('all', 'hover', (function (path, event, value) {
        this.adjustZ();
    }).bind(this));
    this.model.on('all', 'disabled', (function (path, event, disabled) {
        this.adjustZ();

        if (this.model.get('disabled')) {
            this.model.set('tabindex', -1);
        } else {
            this.model.set('tabindex', 0);
        }
    }).bind(this));
}

Component.prototype.insideButton = function (x, y) {
    var rect = this.wrapper.getBoundingClientRect();
    return (rect.left <= x) && (x <= rect.right) && (rect.top <= y) && (y <= rect.bottom);
}

Component.prototype.adjustZ = function () {
    if (this.model.get('focused')) {
        this.model.set('splash', true);
    } else {
        this.model.set('splash', false);

        if (this.model.get('active') || this.model.get('hover')) {
            this.model.set('z', 1);
        } else if (this.model.get('disabled')) {
            this.model.set('z', 0);
        } else {
            this.model.set('z', 0);
        }

    }
}

Component.prototype.focusAction = function() {
    if (!this.model.get('pressed')) {
        // Only render the "focused" state if the element gains focus due to
        // keyboard navigation.
        this.model.set('focused', true);
    }
}

Component.prototype.blurAction = function() {
    this.model.set('focused', false);
}

Component.prototype.downAction = function(event) {
    this.lastEvent = event;

    this.model.set('pressed', true);
    this.model.set('focused', false);

    if (this.model.get('isToggle')) {
        this.model.set('active', !this.model.get('active'));
    } else {
        this.model.set('active', true);
    }
}

Component.prototype.upAction = function() {
    this.model.set('pressed', false);

    if (!this.model.get('isToggle')) {
        this.model.set('active', false);
    }
}

Component.prototype.contextMenuAction = function(){}

Component.prototype.mouseEnterAction = function(event) {
    this.model.set('hover', true);
}
Component.prototype.mouseLeaveAction = function(event) {
    this.model.set('hover', false);
}

Component.prototype.clickAction = function(event, element) {
    this.emit('click', event, element, this.model.get('item'));
}

Component.prototype.dblclickAction = function(event, element) {
    this.emit('dblclick', event, element, this.model.get('item'));
}


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible

from .clients import get_client
from .fields import EncryptedField

class ProviderManager(models.Manager):
    "Additional manager methods for Providers."

    def get_by_natural_key(self, name):
        return self.get(name=name)

@python_2_unicode_compatible
class Provider(models.Model):
    "Configuration for OAuth provider."

    name = models.CharField(max_length=50, unique=True)
    request_token_url = models.CharField(blank=True, max_length=255)
    authorization_url = models.CharField(max_length=255)
    access_token_url = models.CharField(max_length=255)
    profile_url = models.CharField(max_length=255)
    consumer_key = EncryptedField(blank=True, null=True, default=None)
    consumer_secret = EncryptedField(blank=True, null=True, default=None)

    objects = ProviderManager()

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.consumer_key = self.consumer_key or None
        self.consumer_secret = self.consumer_secret or None
        super(Provider, self).save(*args, **kwargs)

    def natural_key(self):
        return (self.name, )

    def enabled(self):
        return self.consumer_key is not None and self.consumer_secret is not None
    enabled.boolean = True

class AccountAccessManager(models.Manager):
    "Additional manager for AccountAccess models."

    def get_by_natural_key(self, identifier, provider):
        provider = Provider.objects.get_by_natural_key(provider)
        return self.get(identifier=identifier, provider=provider)

@python_2_unicode_compatible
class AccountAccess(models.Model):
    "Authorized remote OAuth provider."

    identifier = models.CharField(max_length=255)
    provider = models.ForeignKey(Provider, on_delete=models.CASCADE)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    access_token = EncryptedField(blank=True, null=True, default=None)

    objects = AccountAccessManager()

    class Meta(object):
        unique_together = ('identifier', 'provider')

    def __str__(self):
        return '{0} {1}'.format(self.provider, self.identifier)

    def save(self, *args, **kwargs):
        self.access_token = self.access_token or None
        super(AccountAccess, self).save(*args, **kwargs)

    def natural_key(self):
        return (self.identifier, ) + self.provider.natural_key()
    natural_key.dependencies = ['allaccess.provider']

    @property
    def api_client(self):
        return get_client(self.provider, self.access_token or '')


text:
<TITLE>Review for That Thing You Do! (1996)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

That Thing You Do! (1996)

reviewed by
James Berardinelli

                          That Thing You Do! (1996)
                   A film review by James Berardinelli
                    Copyright 1996 James Berardinelli

RATING (0 TO 10): 6.5
Alternative Scale: **1/2 out of ****

United States, 1996
U.S. Release Date: 10/4/96 (wide)
Running Length: 1:47
MPAA Classification: PG (Mature themes)
Theatrical Aspect Ratio: 1.85:1

Cast: Tom Everett Scott, Jonathan Schaech, Liv Tyler, Steve Zahn,
      Ethan Embry, Tom Hanks, Charlize Theron, Obba Babatunde
Director: Tom Hanks
Producer: Gary Goetzman, Jonathan Demme, Edward Saxon
Screenplay: Tom Hanks
Cinematography: Tak Fujimoto
Music: Howard Shore
U.S. Distributor: Twentieth Century Fox

     Some time after finishing APOLLO 13, Tom Hanks approached
producer/director Jonathan Demme and inquired whether a little script he
had written might make a good feature.  Demme read the screenplay and
not only felt that the movie should be made, but that Hanks should
direct it.  As a result, The Man Everyone Loves pitched the project to
20th Century Fox officials, and, considering Hanks' amazing box office
appeal, how could they refuse?  Thus was born THAT THING YOU DO!, an
enjoyable-but-flawed look at the rapid rise and even more rapid fall of
a pop group during the mid-1960s.

     Throughout the brief history of rock and roll, many bands have
begun in garages.  Most of them have stayed there.  Not so with The
Wonders (originally called The One-Ders), the pride of Erie,
Pennsylvania.  Through a combination of good fortune and natural
charisma (probably more of the former than the latter), this quartet --
singer/songwriter Jimmy Mattingly (Jonathan Schaech), drummer Guy
Patterson (Tom Everett Scott), guitarist Lenny (Steve Zahn), and a
nameless bass player (Ethan Embry) -- soars into the national spotlight
when their debut song, "That Thing You Do!" starts a dramatic rise up
the charts.  Managed by Mr. White (Tom Hanks) of Play-Tone Records (not
RESERVOIR DOGS), the Wonders become a nationwide phenomenon with TV and
movie appearances, but internal friction threatens to turn them into The
One Hit Wonders.

     Although Hanks' film starts out strong, it finishes on shaky
ground.  THAT THING YOU DO! is mostly a serio-comedy/fantasy whose light
dramatic arc can't support the awkward and unnecessarily melodramatic
ending.  For most of the movie, the first-time director lets things move
forward in an unforced manner, but, as the running time approaches the
ninety-minute mark, he appears uncertain how to wrap things up cleanly.
The result is an imposed climax that doesn't ring true.  Two of the band
members split on a whim and the lead singer decides that the
commercialization of The Wonders offends his artistic integrity.  If the
film had adequately built to this moment, it might have worked, but, as
it is, it feels manufactured and artificial.

     On the other hand, THAT THING YOU DO! contains its share of magical
moments.  The sequence when the excited band members first hear their
single on the radio is one (they run around an appliance store owned by
Guy's father, shouting, dancing, and turning every radio on full blast).
Another occurs when Guy's previously-doubting family clusters around the
TV to watch his debut on the "Hollywood Television Showcase".  There's
also a recording session that takes place in a church and a rather
amusing takeoff of the '60s beach movies (with The Wonders making a
background cameo in an Avalon/Funicello-type flick).  When Hanks pushes
drama aside in favor of just having fun, things click.

     From a romantic angle, THAT THING YOU DO! is a disappointment.  For
most of the film, Liv Tyler's Faye has little to do except tag along
after the band offering support to her boyfriend, Jimmy, and silently
longing after Guy.  Had this triangle been developed, it could have
created the kind of believable tension necessary to splinter the band,
but we never see much in the way of affection between Jimmy and Faye,
and Guy doesn't really come into the picture until Jimmy is effectively
out of it.

     Tom Everett Scott not only plays Guy like a young Tom Hanks, but
looks the part.  Jonathon Schaech is perpetually sullen.  Despite a
significant amount of screen time, his Jimmy rarely appears without a
frown, and we never get to learn much about him other than that he's a
"genius" songwriter.  Steve Zahn and Ethan Embry don't have well-
developed characters (Embry's bass player doesn't even have a name), and
appear to be on board primarily for comic relief.  Finally, there's
Hanks, who gives his least impressive acting turn since the forgettable
BONFIRE OF THE VANITIES (maybe it's because he's only in a supporting
role).  For a while, it looks like Mr. White is going to be an
unappealing, no-nonsense business type, but Hanks, who seems incapable
of playing an dislikable guy, softens White's most abrasive edges and
makes him into something of a father-figure.

     Viewed as a playful survey of the ups and downs of the music world,
THAT THING YOU DO! is somewhat more successful than the recent GRACE OF
MY HEART.  But there's not a whole lot of musical variety here.  By the
time you leave, you're likely to know all the words to "That Thing You
Do!" since it's played, in whole or in part, about a dozen times.  At
least the song, which was written by Adam Schleisenger, captures the
sound of the era.  It doesn't take much imagination to hear the Beatles,
the Spencer Davis Group, or some other popular '60s band covering the
tune.

     As a movie, THAT THING YOU DO! adapts Tom Hanks' most recognizable
public traits:  affability and inoffensiveness.  The problems, none of
which are crippling, can be attributed more to Hanks the screenwriter
than Hanks the director.  THAT THING YOU DO! is a credible first effort,
but it will take a lot more time and effort before Hanks attains the
same reputation behind the camera that he has in front of it.

- James Berardinelli
e-mail: berardin@bc.cybernex.net
ReelViews web site: http://www.cybernex.net/~berardin

"We go away from our parents in youth and then we gradually come back to
them; and in that moment, we have grown up." -- Ingmar Bergman

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package org.dmr.domain.impl;

public class RobotWrapper {

	private String idUser;
	private Robot robot;

	public String getIdUser() {
		return idUser;
	}
	public void setIdUser(String idUser) {
		this.idUser = idUser;
	}
	public Robot getRobot() {
		return robot;
	}
	public void setRobot(Robot robot) {
		this.robot = robot;
	}

}