text:
__author__ = 'Frank Sehnke, sehnke@in.tum.de'

from pybrain.rl.environments import EpisodicTask
from pybrain.rl.environments.ode.sensors import SpecificBodyPositionSensor
from scipy import tanh, zeros, array, random, sqrt, asarray

#Basic class for all ccrl tasks
class CCRLTask(EpisodicTask):
    def __init__(self, env):
        EpisodicTask.__init__(self, env)
        #Overall maximal tourque - is multiplied with relative max tourque for individual joint.
        self.maxPower = 100.0
        self.reward_history = []
        self.count = 0 #timestep counter
        self.epiLen = 1500 #suggestet episodic length for normal Johnnie tasks
        self.incLearn = 0 #counts the task resets for incrementall learning
        self.env.FricMu = 20.0 #We need higher friction for CCRL
        self.env.dt = 0.002 #We also need more timly resolution

        # normalize standard sensors to (-1, 1)
        self.sensor_limits = []
        #Angle sensors
        for i in range(self.env.actLen):
            self.sensor_limits.append((self.env.cLowList[i], self.env.cHighList[i]))
        # Joint velocity sensors
        for i in range(self.env.actLen):
            self.sensor_limits.append((-20, 20))
        #Norm all actor dimensions to (-1, 1)
        self.actor_limits = [(-1, 1)] * env.actLen
        self.oldAction = zeros(env.actLen, float)
        self.dist = zeros(9, float)
        self.dif = array([0.0, 0.0, 0.0])
        self.target = array([-6.5, 1.75, -10.5])
        self.grepRew = 0.0
        self.tableFlag = 0.0
        self.env.addSensor(SpecificBodyPositionSensor(['objectP00'], "glasPos"))
        self.env.addSensor(SpecificBodyPositionSensor(['palmLeft'], "palmPos"))
        self.env.addSensor(SpecificBodyPositionSensor(['fingerLeft1'], "finger1Pos"))
        self.env.addSensor(SpecificBodyPositionSensor(['fingerLeft2'], "finger2Pos"))
        #we changed sensors so we need to update environments sensorLength variable
        self.env.obsLen = len(self.env.getSensors())
        #normalization for the task spezific sensors
        for i in range(self.env.obsLen - 2 * self.env.actLen):
            self.sensor_limits.append((-4, 4))

    def getObservation(self):
        """ a filtered mapping to getSample of the underlying environment. """
        sensors = self.env.getSensors()
        #Sensor hand to target object
        for i in range(3):
            self.dist[i] = ((sensors[self.env.obsLen - 9 + i] + sensors[self.env.obsLen - 6 + i] + sensors[self.env.obsLen - 3 + i]) / 3.0 - (sensors[self.env.obsLen - 12 + i] + self.dif[i])) * 4.0 #sensors[self.env.obsLen-12+i]
        #Sensor hand angle to horizontal plane X-Axis
        for i in range(3):
            self.dist[i + 3] = (sensors[self.env.obsLen - 3 + i] - sensors[self.env.obsLen - 6 + i]) * 5.0
        #Sensor hand angle to horizontal plane Y-Axis
        for i in range(3):
            self.dist[i + 6] = ((sensors[self.env.obsLen - 3 + i] + sensors[self.env.obsLen - 6 + i]) / 2.0 - sensors[self.env.obsLen - 9 + i]) * 10.0
        if self.sensor_limits:
            sensors = self.normalize(sensors)
        sens = []
        for i in range(self.env.obsLen - 12):
            sens.append(sensors[i])
        for i in range(9):
            sens.append(self.dist[i])
        for i in self.oldAction:
            sens.append(i)
        return sens

    def performAction(self, action):
        #Filtered mapping towards performAction of the underlying environment
        #The standard CCRL task uses a PID controller to controll directly angles instead of forces
        #This makes most tasks much simpler to learn
        self.oldAction = action
        #Grasping as reflex depending on the distance to target - comment in for more easy grasping
        #if abs(self.dist[2])<2.0: action[15]=(1.0+2.0*action[15])*.3333 #self.grepRew=action[15]*.01
        #else: action[15]=(-1.0+2.0*action[15])*.3333 #self.grepRew=action[15]*-.03
        isJoints=array(self.env.getSensorByName('JointSensor')) #The joint angles
        isSpeeds=array(self.env.getSensorByName('JointVelocitySensor')) #The joint angular velocitys
        act=(action+1.0)/2.0*(self.env.cHighList-self.env.cLowList)+self.env.cLowList #norm output to action intervall
        action=tanh((act-isJoints-0.9*isSpeeds*self.env.tourqueList)*16.0)*self.maxPower*self.env.tourqueList #simple PID
        EpisodicTask.performAction(self, action)
        #self.env.performAction(action)

    def isFinished(self):
        #returns true if episode timesteps has reached episode length and resets the task
        if self.count > self.epiLen:
            self.res()
            return True
        else:
            self.count += 1
            return False

    def res(self):
        #sets counter and history back, increases incremental counter
        self.count = 0
        self.incLearn += 1
        self.reward_history.append(self.getTotalReward())
        self.tableFlag = 0.0

    def getReward(self):
        #rewarded for approaching the object
        dis = sqrt((self.dist[0:3] ** 2).sum())
        return (25.0 - dis) / float(self.epiLen) - float(self.env.tableSum) * 0.1

#Learn to grasp a glas at a fixed location
class CCRLGlasTask(CCRLTask):
    def __init__(self, env):
        CCRLTask.__init__(self, env)
        self.dif = array([0.0, 0.0, 0.0])
        self.epiLen = 1000 #suggestet episodic length for normal Johnnie tasks

    def isFinished(self):
        #returns true if episode timesteps has reached episode length and resets the task
        if self.count > self.epiLen:
            self.res()
            return True
        else:
            if self.count == 1: self.pertGlasPos(0)
            self.count += 1
            return False

    def pertGlasPos(self, num):
        if num == 0: self.env.pert = asarray([0.0, 0.0, 0.5])

    def getReward(self):
        if self.env.glasSum >= 2: grip = 1.0 + float(self.env.glasSum - 2)
        else: grip = 0.0
        if self.env.tableSum > 0: self.tableFlag = 10.0
        self.dist[3] = 0.0
        self.dist[8] = 0.0
        dis = sqrt((self.dist ** 2).sum())
        nig = (abs(self.dist[4]) + 1.0)
        if self.env.stepCounter == self.epiLen:
            return 25.0 + grip / nig - dis - self.tableFlag #-dis
        else:
            return (25.0 - dis) / float(self.epiLen) + (grip / nig - float(self.env.tableSum)) * 0.1 #+self.grepRew (10.0-dis)/float(self.epiLen)+

#Learn to grasp a plate at a fixed location
class CCRLPlateTask(CCRLTask):
    def __init__(self, env):
        CCRLTask.__init__(self, env)
        self.dif = array([0.0, 0.2, 0.8])
        self.epiLen = 1000 #suggestet episodic length for normal Johnnie tasks

    def isFinished(self):
        #returns true if episode timesteps has reached episode length and resets the task
        if self.count > self.epiLen:
            self.res()
            return True
        else:
            if self.count == 1: self.pertGlasPos(0)
            self.count += 1
            return False

    def pertGlasPos(self, num):
        if num == 0: self.env.pert = asarray([0.0, 0.0, 0.5])

    def getReward(self):
        if self.env.glasSum >= 2: grip = 1.0
        else: grip = 0.0
        if self.env.tableSum > 0: self.tableFlag = 10.0
        #self.dist[4]=0.0
        #self.dist[8]=0.0
        dis = sqrt((self.dist[0:3] ** 2).sum())
        if self.count == self.epiLen:
            return 25.0 + grip - dis - self.tableFlag #/nig
        else:
            return (25.0 - dis) / float(self.epiLen) + (grip - float(self.env.tableSum)) * 0.1 #/nig -(1.0+self.oldAction[15])

#Learn to grasp a glas at 5 different locations
class CCRLGlasVarTask(CCRLGlasTask):
    def __init__(self, env):
        CCRLGlasTask.__init__(self, env)
        self.epiLen = 5000 #suggestet episodic length for normal Johnnie tasks

    def isFinished(self):
        #returns true if episode timesteps has reached episode length and resets the task
        if self.count > self.epiLen:
            self.res()
            return True
        else:
            if self.count == 1:
                self.pertGlasPos(0)
            if self.count == self.epiLen / 5 + 1:
                self.env.reset()
                self.pertGlasPos(1)
            if self.count == 2 * self.epiLen / 5 + 1:
                self.env.reset()
                self.pertGlasPos(2)
            if self.count == 3 * self.epiLen / 5 + 1:
                self.env.reset()
                self.pertGlasPos(3)
            if self.count == 4 * self.epiLen / 5 + 1:
                self.env.reset()
                self.pertGlasPos(4)
            self.count += 1
            return False

    def pertGlasPos(self, num):
        if num == 0: self.env.pert = asarray([1.0, 0.0, 0.5])
        if num == 1: self.env.pert = asarray([-1.0, 0.0, 0.5])
        if num == 2: self.env.pert = asarray([1.0, 0.0, 0.0])
        if num == 3: self.env.pert = asarray([-1.0, 0.0, 0.0])
        if num == 4: self.env.pert = asarray([0.0, 0.0, 0.25])

    def getReward(self):
        if self.env.glasSum >= 2: grip = 1.0
        else: grip = 0.0
        if self.env.tableSum > 0: self.tableFlag = 10.0
        self.dist[3] = 0.0
        self.dist[8] = 0.0
        dis = sqrt((self.dist ** 2).sum())
        nig = (abs(self.dist[4]) + 1.0)
        if self.count == self.epiLen or self.count == self.epiLen / 5 or self.count == 2 * self.epiLen / 5 or self.count == 3 * self.epiLen / 5 or self.count == 4 * self.epiLen / 5:
            return 25.0 + grip / nig - dis - self.tableFlag #/nig
        else:
            return (25.0 - dis) / float(self.epiLen) + (grip / nig - float(self.env.tableSum)) * 0.1 #/nig

#Learn to grasp a glas at random locations
class CCRLGlasVarRandTask(CCRLGlasVarTask):
    def pertGlasPos(self, num):
        self.env.pert = asarray([random.random()*2.0 - 1.0, 0.0, random.random()*0.5 + 0.5])

#Some experimental stuff
class CCRLPointTask(CCRLGlasVarTask):
    def __init__(self, env):
        CCRLGlasVarTask.__init__(self, env)
        self.epiLen = 1000 #suggestet episodic length for normal Johnnie tasks

    def isFinished(self):
        #returns true if episode timesteps has reached episode length and resets the task
        if self.count > self.epiLen:
            self.res()
            return True
        else:
            if self.count == 1:
                self.pertGlasPos(0)
            self.count += 1
            return False

    def getObservation(self):
        """ a filtered mapping to getSample of the underlying environment. """
        sensors = self.env.getSensors()
        sensSort = []
        #Angle and angleVelocity
        for i in range(32):
            sensSort.append(sensors[i])
        #Angles wanted (old action)
        for i in self.oldAction:
            sensSort.append(i)
        #Hand position
        for i in range(3):
            sensSort.append((sensors[38 + i] + sensors[41 + i]) / 2)
        #Hand orientation (Hack - make correkt!!!!)
        sensSort.append((sensors[38] - sensors[41]) / 2 - sensors[35]) #pitch
        sensSort.append((sensors[38 + 1] - sensors[41 + 1]) / 2 - sensors[35 + 1]) #yaw
        sensSort.append((sensors[38 + 1] - sensors[41 + 1])) #roll
        #Target position
        for i in range(3):
            sensSort.append(self.target[i])
        #Target orientation
        for i in range(3):
            sensSort.append(0.0)
        #Object type (start with random)
        sensSort.append(float(random.randint(-1, 1))) #roll

        #normalisation
        if self.sensor_limits:
            sensors = self.normalize(sensors)
        sens = []
        for i in range(32):
            sens.append(sensors[i])
        for i in range(29):
            sens.append(sensSort[i + 32])

        #calc dist to target
        self.dist = array([(sens[54] - sens[48]), (sens[55] - sens[49]), (sens[56] - sens[50]), sens[51], sens[52], sens[53], sens[15]])
        return sens

    def pertGlasPos(self, num):
        if num == 0: self.target = asarray([0.0, 0.0, 1.0])
        self.env.pert = self.target.copy()
        self.target = self.target.copy() + array([-6.5, 1.75, -10.5])

    def getReward(self):
        dis = sqrt((self.dist ** 2).sum())
        return (25.0 - dis) / float(self.epiLen) - float(self.env.tableSum) * 0.1

class CCRLPointVarTask(CCRLPointTask):
    def __init__(self, env):
        CCRLPointTask.__init__(self, env)
        self.epiLen = 2000 #suggestet episodic length for normal Johnnie tasks

    def isFinished(self):
        #returns true if episode timesteps has reached episode length and resets the task
        if self.count > self.epiLen:
            self.res()
            return True
        else:
            if self.count == 1:
                self.pertGlasPos(0)
            if self.count == self.epiLen / 2 + 1:
                self.env.reset()
                self.pertGlasPos(1)
            self.count += 1
            return False

    def getObservation(self):
        """ a filtered mapping to getSample of the underlying environment. """
        sensors = self.env.getSensors()
        sensSort = []
        #Angle and angleVelocity
        for i in range(32):
            sensSort.append(sensors[i])
        #Angles wanted (old action)
        for i in self.oldAction:
            sensSort.append(i)
        #Hand position
        for i in range(3):
            sensSort.append((sensors[38 + i] + sensors[41 + i]) / 2)
        #Hand orientation (Hack - make correkt!!!!)
        sensSort.append((sensors[38] - sensors[41]) / 2 - sensors[35]) #pitch
        sensSort.append((sensors[38 + 1] - sensors[41 + 1]) / 2 - sensors[35 + 1]) #yaw
        sensSort.append((sensors[38 + 1] - sensors[41 + 1])) #roll
        #Target position
        for i in range(3):
            sensSort.append(self.target[i])
        #Target orientation
        for i in range(3):
            sensSort.append(0.0)
        #Object type (start with random)
        sensSort.append(float(random.randint(-1, 1))) #roll

        #normalisation
        if self.sensor_limits:
            sensors = self.normalize(sensors)
        sens = []
        for i in range(32):
            sens.append(sensors[i])
        for i in range(29):
            sens.append(sensSort[i + 32])

        #calc dist to target
        self.dist = array([(sens[54] - sens[48]) * 10.0, (sens[55] - sens[49]) * 10.0, (sens[56] - sens[50]) * 10.0, sens[51], sens[52], sens[53], 1.0 + sens[15]])
        return sens

    def pertGlasPos(self, num):
        if num == 0: self.target = asarray([1.0, 0.0, 1.0])
        if num == 1: self.target = asarray([-1.0, 0.0, 1.0])
        if num == 2: self.target = asarray([1.0, 0.0, 0.0])
        if num == 3: self.target = asarray([-1.0, 0.0, 0.0])
        if num == 4: self.target = asarray([0.0, 0.0, 0.5])
        self.env.pert = self.target.copy()
        self.target = self.target.copy() + array([-6.5, 1.75, -10.5])

    def getReward(self):
        dis = sqrt((self.dist ** 2).sum())
        subEpi = self.epiLen / 2
        if self.count == self.epiLen or self.count == subEpi:
            return (25.0 - dis) / 2.0
        else:
            return (25.0 - dis) / float(self.epiLen) - float(self.env.tableSum) * 0.1


text:
/**
@Name: Array.prototype.max
@Author: Paul Visco
@Version: 1.1 11/19/07
@Description: Finds the maximum value in an alpha/numeric array.  Sorts alphanumerically and chooses the highest.  Number have preference over letters, so 1 is higher than 'apple'

@Return: String/Number Returns the max value
@Example:
var myArray = [5, 10, 15];
var answer = myArray.max();
//answer = 15;
*/
Array.prototype.max = function(){
	 var max=this[0];
	 this.forEach(function(v){max=(v>max)?v:max;});
	 return max;
};

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<!-- Copyright (C) 2008-2014 Free Software Foundation, Inc.

     Copying and distribution of this file, with or without modification,
     are permitted in any medium without royalty provided the copyright
     notice and this notice are preserved.  -->

<!DOCTYPE target SYSTEM "gdb-target.dtd">
<target>
  <architecture>powerpc:e500</architecture>
  <xi:include href="power-core.xml"/>
  <xi:include href="power-spe.xml"/>
  <xi:include href="power-linux.xml"/>
</target>


text:
FROM frodenas/ubuntu
MAINTAINER Ferran Rodenas <frodenas@gmail.com>

# Install and configure ArangoDB 2.2
RUN DEBIAN_FRONTEND=noninteractive && \
    cd /tmp && \
    wget https://www.arangodb.org/repositories/arangodb2/xUbuntu_14.04/Release.key && \
    apt-key add - < Release.key && \
    echo 'deb https://www.arangodb.org/repositories/arangodb2/xUbuntu_14.04/ /' >> /etc/apt/sources.list.d/arangodb.list && \
    apt-get update && \
    apt-get install -y --force-yes arangodb=2.2.7 && \
    service arangodb stop && \
    sed -e 's/^directory = .*$/directory = \/data\/databases/' -i /etc/arangodb/arangod.conf && \
    sed -e 's/^app-path = .*$/app-path = \/data\/apps/' -i /etc/arangodb/arangod.conf && \
    sed -e 's/^data-path = .*$/data-path = \/data\/cluster/' -i /etc/arangodb/arangod.conf && \
    sed -e 's/^disable-authentication = .*$/disable-authentication = no/' -i /etc/arangodb/arangod.conf && \
    apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# Add scripts
ADD scripts /scripts
RUN chmod +x /scripts/*.sh
RUN touch /.firstrun

# Command to run
ENTRYPOINT ["/scripts/run.sh"]
CMD [""]

# Expose listen port
EXPOSE 8529

# Expose our data, logs and configuration volumes
VOLUME ["/data", "/var/log/arangodb", "/etc/arangodb"]


text:
typedef unsigned int   uint;
typedef unsigned short ushort;
typedef unsigned char  uchar;
typedef uint pde_t;
typedef struct {
          uint locked;
        } lock_t;
struct Semaphore;


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=type.U659.html">

Redirecting to type.U659.html...


text:
package org.lambda3.indra;

public class AnalyzedPair {
    protected final TextPair pair;
    protected AnalyzedTerm t1;
    protected AnalyzedTerm t2;

    public AnalyzedPair(TextPair pair) {
        if (pair == null) {
            throw new IllegalArgumentException("pair can't be null");
        }
        this.pair = pair;
    }

    public void setAnalyzedTerm1(AnalyzedTerm t1) {
        this.t1 = t1;
    }

    public void setAnalyzedTerm2(AnalyzedTerm t2) {
        this.t2 = t2;
    }

    public TextPair getTextPair() {
        return this.pair;
    }

    public AnalyzedTerm getAnalyzedT1() {
        return t1;
    }

    public AnalyzedTerm getAnalyzedT2() {
        return t2;
    }

}


text:
import { CardSearchPagedComponent } from '../../lib/cardSearch';
import {
  OPERATOR_HAS,
  OPERATOR_SORT,
  OPERATOR_USER,
  ORDER_ASCENDING,
  PREDICATE_DUE_AT,
} from '../../../config/search-const';
import { QueryParams } from '../../../config/query-classes';

// const subManager = new SubsManager();

BlazeComponent.extendComponent({
  dueCardsView() {
    // eslint-disable-next-line no-console
    // console.log('sort:', Utils.dueCardsView());
    return Utils.dueCardsView();
  },

  events() {
    return [
      {
        'click .js-due-cards-view-change': Popup.open('dueCardsViewChange'),
      },
    ];
  },
}).register('dueCardsHeaderBar');

Template.dueCards.helpers({
  userId() {
    return Meteor.userId();
  },
});

BlazeComponent.extendComponent({
  events() {
    return [
      {
        'click .js-due-cards-view-me'() {
          Utils.setDueCardsView('me');
          Popup.back();
        },

        'click .js-due-cards-view-all'() {
          Utils.setDueCardsView('all');
          Popup.back();
        },
      },
    ];
  },
}).register('dueCardsViewChangePopup');

class DueCardsComponent extends CardSearchPagedComponent {
  onCreated() {
    super.onCreated();

    const queryParams = new QueryParams();
    queryParams.addPredicate(OPERATOR_HAS, {
      field: PREDICATE_DUE_AT,
      exists: true,
    });
    // queryParams[OPERATOR_LIMIT] = 5;
    queryParams.addPredicate(OPERATOR_SORT, {
      name: PREDICATE_DUE_AT,
      order: ORDER_ASCENDING,
    });

    if (Utils.dueCardsView() !== 'all') {
      queryParams.addPredicate(OPERATOR_USER, Meteor.user().username);
    }

    this.runGlobalSearch(queryParams);
  }

  dueCardsView() {
    // eslint-disable-next-line no-console
    //console.log('sort:', Utils.dueCardsView());
    return Utils.dueCardsView();
  }

  sortByBoard() {
    return this.dueCardsView() === 'board';
  }

  dueCardsList() {
    const results = this.getResults();
    console.log('results:', results);
    const cards = [];
    if (results) {
      results.forEach(card => {
        cards.push(card);
      });
    }

    cards.sort((a, b) => {
      const x = a.dueAt === null ? new Date('2100-12-31') : a.dueAt;
      const y = b.dueAt === null ? new Date('2100-12-31') : b.dueAt;

      if (x > y) return 1;
      else if (x < y) return -1;

      return 0;
    });

    // eslint-disable-next-line no-console
    console.log('cards:', cards);
    return cards;
  }
}

DueCardsComponent.register('dueCards');


text:
package ru.job4j.dao.hibernate;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ru.job4j.dao.UserDAO;
import ru.job4j.dao.daofactory.PostgresDAOFactory;
import ru.job4j.model.Address;
import ru.job4j.model.MusicType;
import ru.job4j.model.Role;
import ru.job4j.model.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Класс DAO для CRUD операций с пользователем в базе данных Postgres.
 *
 * @author Alexander Ivanov
 * @version 1.0
 * @since 25.12.2017
 */
public class PostgresUserDAO extends UserDAO {
    /**
     * Логгер.
     */
    private static final Logger LOGGER = LogManager.getLogger(Logger.class.getName());

    /**
     * Фабрика, для получения соединения с базой данных Postgres.
     */
    PostgresDAOFactory factory = PostgresDAOFactory.getInstance();

    /**
     * Создание пользователя в базе данных Postgres.
     *
     * @param entity пользователь.
     * @return true если пользователь создался успешно.
     */
    @Override
    public boolean create(User entity) {
        boolean isCreated = false;
        try (Connection connection = factory.getConnection()) {
            Address address = entity.getAddress();
            PostgresAddressDAO postgresAddressDAO = new PostgresAddressDAO();
            postgresAddressDAO.create(address);
            PreparedStatement preparedStatement = connection
                    .prepareStatement("INSERT INTO users (login, password, name, role_id, address_id) "
                            + "SELECT ?, ?, ?, (SELECT id FROM roles WHERE name = ?), ? WHERE NOT EXISTS "
                            + "(SELECT id FROM users WHERE login = ?) RETURNING id");
            preparedStatement.setString(1, entity.getLogin());
            preparedStatement.setString(2, entity.getPassword());
            preparedStatement.setString(3, entity.getName());
            preparedStatement.setString(4, entity.getRole().getName());
            preparedStatement.setInt(5, entity.getAddress().getId());
            preparedStatement.setString(6, entity.getLogin());
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                int userID = resultSet.getInt("id");
                entity.setId(userID);
                String insertUserMusic = "INSERT INTO usersmusic (user_id, musictype_id) VALUES ("
                        + userID + ", (SELECT id FROM musictypes WHERE type = '%s'))";
                Statement statement = connection.createStatement();
                List<MusicType> musicTypes = entity.getMusicTypes();
                for (MusicType music : musicTypes) {
                    statement.addBatch(String.format(insertUserMusic, music.getType()));
                }
                statement.executeBatch();
                isCreated = true;
            }
        } catch (SQLException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return isCreated;
    }

    /**
     * Получение всех пользователей из базы данных Postgres.
     *
     * @return список пользователей.
     */
    @Override
    public List<User> getAll() {
        List<User> userList = new ArrayList<>();
        try (Connection connection = factory.getConnection()) {
            PreparedStatement preparedStatement = connection
                    .prepareStatement("SELECT u.id uid, u.login ulogin, u.password upassword, u.name uname, "
                            + "a.id aid, a.city acity, a.street astreet, a.home ahome, r.id rid, r.name rname "
                            + "FROM users u LEFT OUTER JOIN addresses a "
                            + "ON u.address_id = a.id INNER JOIN roles r ON u.role_id = r.id");
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                int userID = resultSet.getInt("uid");
                User user = new User();
                user.setId(userID);
                user.setLogin(resultSet.getString("ulogin"));
                user.setPassword(resultSet.getString("upassword"));
                user.setName(resultSet.getString("uname"));
                Address address = new Address();
                address.setId(resultSet.getInt("aid"));
                address.setCity(resultSet.getString("acity"));
                address.setStreet(resultSet.getString("astreet"));
                address.setHouse(resultSet.getInt("ahome"));
                user.setAddress(address);
                Role role = new Role();
                role.setId(resultSet.getInt("rid"));
                role.setName(resultSet.getString("rname"));
                user.setRole(role);
                user.setMusicTypes(getMusicTypesByID(userID, connection));
                userList.add(user);
            }
        } catch (SQLException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return userList;
    }

    /**
     * Получение пользователя из базы данных Postgres по ID.
     *
     * @param id пользователя.
     * @return пользователя.
     */
    @Override
    public User getByID(int id) {
        User user = null;
        try (Connection connection = factory.getConnection()) {
            PreparedStatement preparedStatement = connection
                    .prepareStatement("SELECT u.login ulogin, u.password upassword, u.name uname, "
                            + "a.id aid, a.city acity, a.street astreet, a.home ahome, r.id rid, r.name rname "
                            + "FROM users u INNER JOIN roles r ON u.role_id = r.id "
                            + "INNER JOIN addresses a ON u.address_id = a.id WHERE u.id = ?");
            preparedStatement.setInt(1, id);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                user = new User();
                user.setId(id);
                user.setName(resultSet.getString("uname"));
                user.setLogin(resultSet.getString("ulogin"));
                user.setPassword(resultSet.getString("upassword"));
                Address address = new Address();
                address.setId(resultSet.getInt("aid"));
                address.setCity(resultSet.getString("acity"));
                address.setStreet(resultSet.getString("astreet"));
                address.setHouse(resultSet.getInt("ahome"));
                user.setAddress(address);
                Role role = new Role();
                role.setId(resultSet.getInt("rid"));
                role.setName(resultSet.getString("rname"));
                user.setRole(role);
                user.setMusicTypes(getMusicTypesByID(id, connection));
            }
        } catch (SQLException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return user;
    }

    /**
     * Обновить пользователя в базе данных Postgres.
     *
     * @param entity пользователь.
     * @return true если пользователь успешно обновлен.
     */
    @Override
    public boolean update(User entity) {
        int isUpdated = 0;
        boolean isAddressUpdated = false;
        boolean isRoleUpdated = false;
        boolean isMusicTypesUpdated = false;
        try (Connection connection = factory.getConnection()) {
            PostgresAddressDAO addressDAO = new PostgresAddressDAO();
            isAddressUpdated = addressDAO.update(entity.getAddress());
            PostgresRoleDAO roleDAO = new PostgresRoleDAO();
            isRoleUpdated = roleDAO.update(entity.getRole());
            PreparedStatement preparedStatement = connection
                    .prepareStatement("UPDATE users SET login = ?, password = ?, name = ? WHERE id = ?");
            preparedStatement.setString(1, entity.getLogin());
            preparedStatement.setString(2, entity.getPassword());
            preparedStatement.setString(3, entity.getName());
            preparedStatement.setInt(4, entity.getId());
            isUpdated = preparedStatement.executeUpdate();

            List<MusicType> newMusicTypes = new ArrayList<>(entity.getMusicTypes());
            PreparedStatement statement = connection
                    .prepareStatement("SELECT musictype_id, type FROM musictypes m INNER JOIN usersmusic u "
                            + "ON m.id = u.musictype_id WHERE u.user_id = ?");
            statement.setInt(1, entity.getId());
            ResultSet musicTypesResultSet = statement.executeQuery();
            List<MusicType> oldMusicTypes = new ArrayList<>();
            while (musicTypesResultSet.next()) {
                MusicType type = new MusicType();
                type.setId(musicTypesResultSet.getInt("musictype_id"));
                type.setType(musicTypesResultSet.getString("type"));
                oldMusicTypes.add(type);
            }
            if (oldMusicTypes.size() != newMusicTypes.size() || !oldMusicTypes.containsAll(newMusicTypes)) {
                Statement musicTypeStatement = connection.createStatement();
                String deleteOldUserMusic = "DELETE FROM usersmusic WHERE user_id = " + entity.getId();
                String insertUserMusic = "INSERT INTO usersmusic (user_id, musictype_id) VALUES ("
                        + entity.getId() + ", (SELECT id FROM musictypes WHERE type = '%s'))";
                musicTypeStatement.execute(deleteOldUserMusic);
                for (MusicType music : newMusicTypes) {
                    musicTypeStatement.addBatch(String.format(insertUserMusic, music.getType()));
                }
                musicTypeStatement.executeBatch();
                isMusicTypesUpdated = true;
            }
        } catch (SQLException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return isUpdated > 0 || isAddressUpdated || isRoleUpdated || isMusicTypesUpdated;
    }

    /**
     * Удалить пользователя из базы данных Postgres.
     *
     * @param entity пользователь.
     * @return true если пользователь успешно удален.
     */
    @Override
    public boolean delete(User entity) {
        int isDeleted = 0;
        try (Connection connection = factory.getConnection()) {
            PreparedStatement statement = connection.prepareStatement("DELETE FROM usersmusic WHERE user_id = ?");
            statement.setInt(1, entity.getId());
            statement.executeUpdate();
            PreparedStatement preparedStatement = connection
                    .prepareStatement("DELETE FROM users WHERE id = ?");
            preparedStatement.setInt(1, entity.getId());
            isDeleted = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return isDeleted > 0;
    }

    /**
     * Получить список музыкальных типов пользователя по ID.
     *
     * @param userID     ID пользователя.
     * @param connection соединение с базой данных.
     * @return список музыкальных типов пользователя.
     * @throws SQLException .
     */
    private List<MusicType> getMusicTypesByID(int userID, Connection connection) throws SQLException {
        PreparedStatement statement = connection
                .prepareStatement("SELECT m.id mid, m.type mtype FROM musictypes m "
                        + "INNER JOIN usersmusic u ON m.id = u.musictype_id WHERE u.user_id = ?");
        statement.setInt(1, userID);
        ResultSet musicResultSet = statement.executeQuery();
        List<MusicType> musicTypes = new ArrayList<>();
        while (musicResultSet.next()) {
            MusicType type = new MusicType();
            type.setId(musicResultSet.getInt("mid"));
            type.setType(musicResultSet.getString("mtype"));
            musicTypes.add(type);
        }
        return musicTypes;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/sensor_type_wheel_encoder_title"
        android:textColor="#F5DC49"
        android:paddingTop="25dp"
        android:paddingBottom="25dp"
        />

    <TableRow
    android:layout_width="wrap_content"
    android:layout_height="match_parent">

        <TextView
            android:layout_width="450dp"
            android:layout_height="50dp"
            android:text="@string/sensor_type_wheel_encoder_value0_text"
            android:id="@+id/id_sensor_type_wheel_encoder_value0_text"
            android:layout_column="0" />

        <TextView
            android:layout_width="300dp"
            android:layout_height="50dp"
            android:text="@string/sensor_type_wheel_encoder_value0_value"
            android:id="@+id/id_sensor_type_wheel_encoder_value0_value"
            android:layout_column="1" />
    </TableRow>

    <TableRow
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="450dp"
            android:layout_height="50dp"
            android:text="@string/sensor_type_wheel_encoder_value1_text"
            android:id="@+id/id_sensor_type_wheel_encoder_value1_text"
            android:layout_column="0" />

        <TextView
            android:layout_width="300dp"
            android:layout_height="50dp"
            android:text="@string/sensor_type_wheel_encoder_value1_value"
            android:id="@+id/id_sensor_type_wheel_encoder_value1_value"
            android:layout_column="1" />
    </TableRow>

    <Space
        android:layout_width="match_parent"
        android:layout_height="40dp"
        />
</TableLayout>


text:
package evaluator

import (
	"fmt"

	"github.com/google/gapid/gapis/api/gles/glsl/ast"
	"github.com/google/gapid/gapis/api/gles/glsl/parser"
)

type evalError string

func (e evalError) Error() string { return string(e) }

func makeError(msg string, args ...interface{}) evalError { return evalError(fmt.Sprintf(msg, args...)) }

// Given a scalar value v and a vector or matrix type t, construct a new value of type t by
// by replicating v. It is assumed types of v and t have equal fundamental types.
func expandScalar(v ast.Value, t ast.BareType) ast.Value {
	col, row := ast.TypeDimensions(t)
	if col > 1 {
		return ast.NewMatrixValue(t, func(uint8, uint8) ast.Value { return v })
	}
	if row > 1 {
		return ast.NewVectorValue(t, func(uint8) ast.Value { return v })
	}
	panic(fmt.Errorf("Unexpected type '%s'.", t))
}

func getType(v ast.Value) ast.BareType { return v.Type().(*ast.BuiltinType).Type.Canonicalize() }

// If one of the values is scalar, this function expands it to match the type of the other value.
// Both values must have the same fundamental types.
func expandScalars(left ast.Value, right ast.Value) (ast.Value, ast.Value) {
	lt := getType(left)
	rt := getType(right)

	if ast.HasVectorExpansions(lt) && !ast.HasVectorExpansions(rt) {
		left = expandScalar(left, rt)
	} else if ast.HasVectorExpansions(rt) && !ast.HasVectorExpansions(lt) {
		right = expandScalar(right, lt)
	}
	return left, right
}

// Performs the correct type of scalar addition, depending on the value type (float, int, uint).
// Both values must have the same type.
func scalarAdd(left, right ast.Value) ast.Value {
	switch left := left.(type) {
	case ast.IntValue:
		return left + right.(ast.IntValue)
	case ast.UintValue:
		return left + right.(ast.UintValue)
	case ast.FloatValue:
		return left + right.(ast.FloatValue)
	}
	panic(fmt.Errorf("Unknown type '%s'.", getType(left)))
}

// Performs the correct type of scalar binary and, depending on the value type (int, uint).
// Both values must have the same type.
func scalarBand(left, right ast.Value) ast.Value {
	switch left := left.(type) {
	case ast.IntValue:
		return left & right.(ast.IntValue)
	case ast.UintValue:
		return left & right.(ast.UintValue)
	}
	panic(fmt.Errorf("Unknown type '%s'.", getType(left)))
}

// Performs the correct type of scalar binary or, depending on the value type (int, uint).
// Both values must have the same type.
func scalarBor(left, right ast.Value) ast.Value {
	switch left := left.(type) {
	case ast.IntValue:
		return left | right.(ast.IntValue)
	case ast.UintValue:
		return left | right.(ast.UintValue)
	}
	panic(fmt.Errorf("Unknown type '%s'.", getType(left)))
}

// Performs the correct type of scalar binary xor, depending on the value type (int, uint).
// Both values must have the same type.
func scalarBxor(left, right ast.Value) ast.Value {
	switch left := left.(type) {
	case ast.IntValue:
		return left ^ right.(ast.IntValue)
	case ast.UintValue:
		return left ^ right.(ast.UintValue)
	}
	panic(fmt.Errorf("Unknown type '%s'.", getType(left)))
}

// Performs the correct type of scalar division, depending on the value type (float, int, uint).
// Both values must have the same type.
func scalarDiv(left, right ast.Value) ast.Value {
	switch left := left.(type) {
	case ast.IntValue:
		return left / right.(ast.IntValue)
	case ast.UintValue:
		return left / right.(ast.UintValue)
	case ast.FloatValue:
		return left / right.(ast.FloatValue)
	}
	panic(fmt.Errorf("Unknown type '%s'.", getType(left)))
}

// Performs the correct type of scalar modulo, depending on the value type (int, uint).
// Both values must have the same type.
func scalarMod(left, right ast.Value) ast.Value {
	switch left := left.(type) {
	case ast.IntValue:
		return left % right.(ast.IntValue)
	case ast.UintValue:
		return left % right.(ast.UintValue)
	}
	panic(fmt.Errorf("Unknown type '%s'.", getType(left)))
}

// Performs the correct type of scalar multiplication, depending on the value type (float, int, uint).
// Both values must have the same type.
func scalarMul(left, right ast.Value) ast.Value {
	switch left := left.(type) {
	case ast.IntValue:
		return left * right.(ast.IntValue)
	case ast.UintValue:
		return left * right.(ast.UintValue)
	case ast.FloatValue:
		return left * right.(ast.FloatValue)
	}
	panic(fmt.Errorf("Unknown type '%s'.", getType(left)))
}

// Performs the correct type of scalar shift left, depending on the value type (int, uint).
// The type of the second value must be uint.
func scalarShl(left, right ast.Value) ast.Value {
	switch left := left.(type) {
	case ast.IntValue:
		return left << right.(ast.UintValue)
	case ast.UintValue:
		return left << right.(ast.UintValue)
	}
	panic(fmt.Errorf("Unknown type '%s'.", getType(left)))
}

// Performs the correct type of scalar shift right, depending on the value type (int, uint).
// The type of the second value must be uint.
func scalarShr(left, right ast.Value) ast.Value {
	switch left := left.(type) {
	case ast.IntValue:
		return left >> right.(ast.UintValue)
	case ast.UintValue:
		return left >> right.(ast.UintValue)
	}
	panic(fmt.Errorf("Unknown type '%s'.", getType(left)))
}

// Performs the correct type of scalar comparison, depending on the value type (float, int, uint).
// Both values must have the same type.
func (v *evaluator) scalarLess(left, right ast.Value) ast.BoolValue {
	left = v.intFixup(left)
	right = v.intFixup(right)
	switch left := left.(type) {
	case ast.IntValue:
		return ast.BoolValue(left < right.(ast.IntValue))
	case ast.UintValue:
		return ast.BoolValue(left < right.(ast.UintValue))
	case ast.FloatValue:
		return ast.BoolValue(left < right.(ast.FloatValue))
	}
	panic(fmt.Errorf("Unknown type '%s'.", getType(left)))
}

// Performs the correct type of scalar subtraction, depending on the value type (float, int, uint).
// Both values must have the same type.
func scalarSub(left, right ast.Value) ast.Value {
	switch left := left.(type) {
	case ast.IntValue:
		return left - right.(ast.IntValue)
	case ast.UintValue:
		return left - right.(ast.UintValue)
	case ast.FloatValue:
		return left - right.(ast.FloatValue)
	}
	panic(fmt.Errorf("Unknown type '%s'.", getType(left)))
}

// Performs the correct type of scalar binary negation, depending on the value type (int, uint).
func scalarBnot(v ast.Value) ast.Value {
	switch v := v.(type) {
	case ast.IntValue:
		return ^v
	case ast.UintValue:
		return ^v
	}
	panic(fmt.Errorf("Unknown type '%s'.", getType(v)))
}

// Performs the correct type of scalar arithmetic negation, depending on the value type (float, int, uint).
func scalarMinus(v ast.Value) ast.Value {
	switch v := v.(type) {
	case ast.IntValue:
		return -v
	case ast.UintValue:
		return -v
	case ast.FloatValue:
		return -v
	}
	panic(fmt.Errorf("Unknown type '%s'.", getType(v)))
}

// Performs the binary scalar operation given by the functor argument on the two values provided.
// In case the operands are vectors or matrices, the scalar operation is applied for each
// component separately. If one of the operands is scalar, it is expanded to the size of the
// other operand.
func (v *evaluator) evalBinaryPiecewiseExpr(left, right ast.Value, scalarOp func(ast.Value, ast.Value) ast.Value) ast.Value {
	left, right = expandScalars(left, right)

	t := getType(left)
	col, row := ast.TypeDimensions(t)
	if col > 1 {
		left, right := left.(ast.MatrixValue), right.(ast.MatrixValue)
		return ast.NewMatrixValue(t, func(i, j uint8) ast.Value {
			return scalarOp(left.Members[i][j], right.Members[i][j])
		})
	}
	if row > 1 {
		left, right := left.(ast.VectorValue), right.(ast.VectorValue)
		return ast.NewVectorValue(t,
			func(i uint8) ast.Value { return scalarOp(left.Members[i], right.Members[i]) })
	}
	return scalarOp(v.intFixup(left), v.intFixup(right))
}

// Perform a multiplication operation.
func (v *evaluator) evalMul(left, right ast.Value) ast.Value {
	lt, rt := getType(left), getType(right)

	// These cases are handled the same as other binary operators.
	if ast.HasVectorExpansions(lt) || ast.HasVectorExpansions(rt) ||
		(ast.IsVectorType(lt) && ast.IsVectorType(rt)) {

		return v.evalBinaryPiecewiseExpr(left, right, scalarMul)
	}

	// Here we do matrix multiplication.

	// Convert the left operand to a matrix.
	var lmat ast.MatrixValue
	if v, ok := left.(ast.VectorValue); ok {
		lmat = ast.NewMatrixValueCR(uint8(len(v.Members)), 1,
			func(i, j uint8) ast.Value { return v.Members[i] })
	} else {
		lmat = left.(ast.MatrixValue)
	}

	// Convert the right operand to a matrix.
	var rmat ast.MatrixValue
	if v, ok := right.(ast.VectorValue); ok {
		rmat.Members = [][]ast.Value{v.Members}
	} else {
		rmat = right.(ast.MatrixValue)
	}

	if len(lmat.Members) != len(rmat.Members[0]) {
		panic(fmt.Errorf("Incompatible matrix dimensions (%dx%d) vs. (%dx%d).", len(lmat.Members),
			len(lmat.Members[0]), len(rmat.Members), len(rmat.Members[0])))
	}

	// Do the actual multiplication.
	mat := ast.NewMatrixValueCR(uint8(len(rmat.Members)), uint8(len(lmat.Members[0])),
		func(i, j uint8) ast.Value {
			acc := ast.FloatValue(0.0)
			for k := range lmat.Members {
				acc += lmat.Members[k][j].(ast.FloatValue) * rmat.Members[i][k].(ast.FloatValue)
			}
			return acc
		})

	// Return a matrix with one column as a vector.
	if len(mat.Members) == 1 {
		return ast.VectorValue{
			Members: mat.Members[0],
			ValType: ast.BuiltinType{Type: ast.GetVectorType(ast.TFloat, uint8(len(mat.Members[0])))},
		}
	}

	// Return a 1x1 matrix as a scalar.
	if len(mat.Members[0]) == 1 {
		return ast.NewVectorValue(ast.GetVectorType(ast.TFloat, uint8(len(mat.Members))),
			func(i uint8) ast.Value { return mat.Members[i][0] })
	}
	return mat
}

type evaluator struct {
	resolver func(sym ast.ValueSymbol) ast.Value
	language ast.Language
}

// If evaluating preprocessor expressions, values are coerced to a boolean in boolean contexts.
// In other cases, the values should already have the correct type.
func (v *evaluator) boolFixup(val ast.Value) ast.Value {
	if v.language == ast.LangPreprocessor {
		return convertBool(val)
	}
	return val
}

// If evaluating preprocessor expressions, values are coerced to an integer in int contexts.
// In other cases, the values should already have the correct type.
func (v *evaluator) intFixup(val ast.Value) ast.Value {
	if v.language == ast.LangPreprocessor {
		return convertInt(val)
	}
	return val
}

// Evaluate a binary expression.
func (v *evaluator) evalBinaryExpr(e *ast.BinaryExpr) ast.Value {
	// TODO: Assignment operators ???
	left := v.eval(e.Left)

	switch e.Op {
	case ast.BoLand:
		if !v.boolFixup(left).(ast.BoolValue) {
			return left
		}
	case ast.BoLor:
		if v.boolFixup(left).(ast.BoolValue) {
			return left
		}
	}

	right := v.eval(e.Right)

	switch e.Op {
	case ast.BoAdd:
		return v.evalBinaryPiecewiseExpr(left, right, scalarAdd)
	case ast.BoBand:
		return v.evalBinaryPiecewiseExpr(left, right, scalarBand)
	case ast.BoBor:
		return v.evalBinaryPiecewiseExpr(left, right, scalarBor)
	case ast.BoBxor:
		return v.evalBinaryPiecewiseExpr(left, right, scalarBxor)
	case ast.BoDiv:
		return v.evalBinaryPiecewiseExpr(left, right, scalarDiv)
	case ast.BoMod:
		return v.evalBinaryPiecewiseExpr(left, right, scalarMod)
	case ast.BoShl:
		return v.evalBinaryPiecewiseExpr(left, right, scalarShl)
	case ast.BoShr:
		return v.evalBinaryPiecewiseExpr(left, right, scalarShr)
	case ast.BoSub:
		return v.evalBinaryPiecewiseExpr(left, right, scalarSub)
	case ast.BoMul:
		return v.evalMul(left, right)

	case ast.BoLand:
		return right
	case ast.BoLor:
		return right
	case ast.BoLxor:
		return ast.BoolValue(v.boolFixup(left).(ast.BoolValue) != v.boolFixup(right).(ast.BoolValue))

	case ast.BoEq:
		return ast.BoolValue(ast.ValueEquals(left, right))
	case ast.BoNotEq:
		return ast.BoolValue(!ast.ValueEquals(left, right))
	case ast.BoLess:
		return v.scalarLess(left, right)
	case ast.BoLessEq:
		return !v.scalarLess(right, left)
	case ast.BoMore:
		return v.scalarLess(right, left)
	case ast.BoMoreEq:
		return !v.scalarLess(left, right)

	case ast.BoComma:
		return right
	}
	return nil
}

// Performs the unary scalar operation given by the functor argument on the provided value.
func (v *evaluator) evalUnaryPiecewiseExpr(val ast.Value, scalarOp func(ast.Value) ast.Value) ast.Value {
	t := getType(val)
	col, row := ast.TypeDimensions(t)
	if col > 1 {
		val := val.(ast.MatrixValue)
		return ast.NewMatrixValue(t, func(i, j uint8) ast.Value { return scalarOp(val.Members[i][j]) })
	}
	if row > 1 {
		val := val.(ast.VectorValue)
		return ast.NewVectorValue(t, func(i uint8) ast.Value { return scalarOp(val.Members[i]) })
	}
	return scalarOp(v.intFixup(val))
}

// Checks that the value is within the range 0..size-1. Returns the value as a uint64.
func checkIndexRange(v ast.Value, size uint64) (index uint64, ok bool) {
	switch v := v.(type) {
	case ast.IntValue:
		if uint64(v) >= size || v < 0 {
			return 0, false
		}
		return uint64(v), true
	case ast.UintValue:
		if uint64(v) >= size {
			return 0, false
		}
		return uint64(v), true
	}
	panic(fmt.Errorf("Unexpected type '%v' as index.", parser.Formatter(v.Type())))
}

// Helper type for doing type conversions.
type convertBuiltin ast.BareType

// Converts a matrix in the argument to the type given by c, according to the GLSL rules. The
// slice v should contain a single value.
func (c convertBuiltin) matrixToMatrix(v []ast.Value) ast.Value {
	members := v[0].(ast.MatrixValue).Members
	return ast.NewMatrixValue(ast.BareType(c), func(i, j uint8) ast.Value {
		switch {
		case int(i) < len(members) && int(j) < len(members[i]):
			return members[i][j]
		case i == j:
			return ast.FloatValue(1.0)
		default:
			return ast.FloatValue(0.0)
		}
	})
}

// convert a value to a boolean
func convertBool(v ast.Value) ast.Value {
	switch v := v.(type) {
	case ast.BoolValue:
		return v
	case ast.UintValue:
		return ast.BoolValue(v != 0)
	case ast.IntValue:
		return ast.BoolValue(v != 0)
	case ast.FloatValue:
		return ast.BoolValue(v != 0.0)
	}
	panic(fmt.Errorf("Unknown type '%v'.", v.Type()))
}

// convert a value to an unsigned integer
func convertUint(v ast.Value) ast.Value {
	switch v := v.(type) {
	case ast.BoolValue:
		if v {
			return ast.UintValue(1)
		}
		return ast.UintValue(0)
	case ast.UintValue:
		return v
	case ast.IntValue:
		return ast.UintValue(v)
	case ast.FloatValue:
		return ast.UintValue(v)
	}
	panic(fmt.Errorf("Unknown type '%v'.", v.Type()))
}

// convert a value to a signed integer
func convertInt(v ast.Value) ast.Value {
	switch v := v.(type) {
	case ast.BoolValue:
		if v {
			return ast.IntValue(1)
		}
		return ast.IntValue(0)
	case ast.UintValue:
		return ast.IntValue(v)
	case ast.IntValue:
		return v
	case ast.FloatValue:
		return ast.IntValue(v)
	}
	panic(fmt.Errorf("Unknown type '%v'.", v.Type()))
}

// convert a value to a float
func convertFloat(v ast.Value) ast.Value {
	switch v := v.(type) {
	case ast.BoolValue:
		if v {
			return ast.FloatValue(1.0)
		}
		return ast.FloatValue(0.0)
	case ast.UintValue:
		return ast.FloatValue(v)
	case ast.IntValue:
		return ast.FloatValue(v)
	case ast.FloatValue:
		return v
	}
	panic(fmt.Errorf("Unknown type '%v'.", v.Type()))
}

var convertMap = map[ast.BareType]func(ast.Value) ast.Value{
	ast.TBool:  convertBool,
	ast.TUint:  convertUint,
	ast.TInt:   convertInt,
	ast.TFloat: convertFloat,
}

// Construct a value of type c from a single scalar present in the slice v, as per GLSL spec.
func (c convertBuiltin) fromScalar(v []ast.Value) ast.Value {
	t := ast.BareType(c)
	value := convertMap[ast.GetFundamentalType(t)](v[0])

	col, row := ast.TypeDimensions(t)
	switch {
	case col > 1:
		return ast.NewMatrixValue(t,
			func(i, j uint8) ast.Value {
				if i == j {
					return value
				} else {
					return ast.FloatValue(0.0)
				}
			})
	case row > 1:
		return ast.NewVectorValue(t, func(uint8) ast.Value { return value })
	default:
		return value
	}
}

// The general conversion function of GLSL. Constructs a sequence of components from the given
// slice and uses these components to initialize a new value of type c. There should always be
// enough components in v to fully initialize the value.
func (c convertBuiltin) generalConvert(v []ast.Value) ast.Value {
	t := ast.BareType(c)
	convertFun := convertMap[ast.GetFundamentalType(t)]

	var components []ast.Value
	for _, v := range v {
		switch v := v.(type) {
		case ast.MatrixValue:
			for _, v := range v.Members {
				components = append(components, v...)
			}
		case ast.VectorValue:
			components = append(components, v.Members...)
		default:
			components = append(components, v)
		}
	}

	i := 0
	col, row := ast.TypeDimensions(t)
	switch {
	case col > 1:
		return ast.NewMatrixValue(t,
			func(uint8, uint8) ast.Value { i++; return convertFun(components[i-1]) })
	case row > 1:
		return ast.NewVectorValue(t,
			func(uint8) ast.Value { i++; return convertFun(components[i-1]) })
	default:
		return convertFun(components[0])
	}
}

type makeStruct ast.StructType

// Constructs a new struct using the values in the slice v. The input values should have the
// correct types.
func (t *makeStruct) construct(v []ast.Value) ast.Value {
	i := 0
	return ast.NewStructValue((*ast.StructType)(t), func(string) ast.Value { i++; return v[i-1] })
}

// Returns a function value which will perform the correct type conversion on its arguments when
// invoked.
func (v *evaluator) evalTypeConversion(e *ast.TypeConversionExpr) ast.Value {
	returnFunc := func(f func(v []ast.Value) ast.Value) ast.FunctionValue {
		return ast.FunctionValue{
			Func:    f,
			ValType: e.Type().(*ast.FunctionType),
		}
	}

	switch retType := e.RetType.(type) {
	case *ast.BuiltinType:
		if len(e.ArgTypes) == 1 {
			argBare := e.ArgTypes[0].(*ast.BuiltinType).Type

			switch {
			case ast.HasVectorExpansions(argBare):
				return returnFunc(convertBuiltin(retType.Type).fromScalar)

			case ast.IsMatrixType(retType.Type) &&
				ast.IsMatrixType(e.ArgTypes[0].(*ast.BuiltinType).Type):

				return returnFunc(convertBuiltin(retType.Type).matrixToMatrix)
			}
		}

		return returnFunc(convertBuiltin(retType.Type).generalConvert)

	case *ast.StructType:
		return returnFunc((*makeStruct)(retType).construct)

	case *ast.ArrayType:
		return returnFunc(func(v []ast.Value) ast.Value { return ast.ArrayValue(v) })

	default:
		panic(fmt.Errorf("Unknown type: %T", e.RetType))
	}
}

// Evaluates an index expression base[index], for all supported types of base (matrix, vector,
// array). Returns an error if the index is out of range.
func (v *evaluator) evalIndexExpr(e *ast.IndexExpr) ast.Value {
	base := v.eval(e.Base)
	index := v.eval(e.Index)
	switch base := base.(type) {
	case ast.MatrixValue:
		if index, ok := checkIndexRange(index, uint64(len(base.Members))); ok {
			return ast.VectorValue{
				Members: base.Members[index],
				ValType: ast.BuiltinType{
					Type: ast.GetVectorType(ast.TFloat, uint8(len(base.Members[index]))),
				},
			}
		}

	case ast.VectorValue:
		if index, ok := checkIndexRange(index, uint64(len(base.Members))); ok {
			return base.Members[uint64(index)]
		}

	case ast.ArrayValue:
		if index, ok := checkIndexRange(index, uint64(len(base))); ok {
			return base[uint64(index)]
		}
	}
	panic(makeError("Index %d is out of range for a value of type '%v'.", index,
		parser.Formatter(base.Type())))
}

// Computes the value of an expression by dispatching based on the expression type.
func (v *evaluator) eval(e ast.Expression) ast.Value {
	switch e := e.(type) {
	case *ast.BinaryExpr:
		return v.evalBinaryExpr(e)
	case *ast.IndexExpr:
		return v.evalIndexExpr(e)

	case *ast.UnaryExpr:
		expr := v.eval(e.Expr)
		// TODO post/pre-inc/dec
		switch e.Op {
		case ast.UoBnot:
			return v.evalUnaryPiecewiseExpr(expr, scalarBnot)
		case ast.UoLnot:
			return !v.boolFixup(expr).(ast.BoolValue)
		case ast.UoMinus:
			return v.evalUnaryPiecewiseExpr(expr, scalarMinus)
		case ast.UoPlus:
			return expr
		}

	case *ast.ConditionalExpr:
		cond := v.eval(e.Cond)
		if cond.(ast.BoolValue) {
			return v.eval(e.TrueExpr)
		} else {
			return v.eval(e.FalseExpr)
		}

	case *ast.DotExpr:
		if t, ok := e.Expr.Type().(*ast.ArrayType); ok {
			if e.Field != "length" {
				panic(fmt.Errorf("Unexpected array field '%s'.", e.Field))
			}
			length := ast.UintValue(t.ComputedSize)
			return ast.FunctionValue{
				Func:    func([]ast.Value) ast.Value { return length },
				ValType: e.ExprType.(*ast.FunctionType),
			}
		}

		expr := v.eval(e.Expr)
		switch expr := expr.(type) {
		case ast.StructValue:
			return expr.Members[e.Field]
		case ast.VectorValue:
			getField := func(i uint8) ast.Value {
				pos, _ := ast.GetVectorComponentInfo(rune(e.Field[i]))
				return expr.Members[pos]
			}
			if len(e.Field) == 1 {
				return getField(0)
			}
			return ast.NewVectorValue(e.ExprType.(*ast.BuiltinType).Type, getField)
		}

	case *ast.ConstantExpr:
		return e.Value

	case *ast.VarRefExpr:
		return v.resolver(e.Sym)

	case *ast.TypeConversionExpr:
		return v.evalTypeConversion(e)

	case *ast.ParenExpr:
		return v.eval(e.Expr)

	case *ast.CallExpr:
		callee := v.eval(e.Callee)
		args := make([]ast.Value, len(e.Args))
		for i := range e.Args {
			args[i] = v.eval(e.Args[i])
		}
		return callee.(ast.FunctionValue).Func(args)

	}
	panic(fmt.Errorf("Unknown expression kind %T.", e))
}

// Evaluate evaluates an expression in a GLES Shading Language program. It assumes the expression
// has already been typed and statically checked for correctness by the sema package. This
// function is suitable to be passed as the evaluator argument to the sema.Analyze function. Its
// arguments are:
//
// - expr the expression to evaluate
//
// - res a function resolving Symbols occuring in the expressions to values
//
// - lang the language whose semantics to employ during evaluation
//
// The function returns the value obtained by evaluating the expression. If the evaluation fails,
// the second result shall contain a list of errors.
func Evaluate(expr ast.Expression, res func(sym ast.ValueSymbol) ast.Value,
	lang ast.Language) (val ast.Value, err []error) {

	// Any evalErrors thrown during the evaluation indicate a malformed expression, and are
	// returned as an error. Any thrown error is let through as it is either an assertion
	// (should not happen in production), or foreign exception.
	defer func() {
		if r := recover(); r != nil {
			if er, ok := r.(evalError); ok {
				err = []error{er}
			} else {
				panic(r)
			}
		}
	}()

	return (&evaluator{resolver: res, language: lang}).eval(expr), nil
}

// EvaluatePreprocessorExpression is a wrapper around Evaluate, which adapts it to processing
// preprocessor expressions. This function is suitable to be passed as the evaluator argument to
// parse.Parse function.
func EvaluatePreprocessorExpression(e ast.Expression) (val ast.IntValue, err []error) {
	var ppErr ast.ErrorCollector
	resolver := func(sym ast.ValueSymbol) ast.Value {
		ppErr.Errorf("Unknown symbol: '%s'.", sym.Name())
		return ast.IntValue(0)
	}

	result, evalErr := Evaluate(e, resolver, ast.LangPreprocessor)
	if len(err) == 0 {
		val = convertInt(result).(ast.IntValue)
	}
	err = append(ppErr.GetErrors(), evalErr...)
	return
}


text:
namespace
{
using namespace ::testing;

using namespace iox::roudi;

class RouDiMemoryManager_Test : public Test
{
  public:
    void SetUp() override
    {
    }

    void TearDown() override
    {
    }

    static const int32_t nbTestCase = 4;

    RouDiMemoryManagerError m_testCombinationRoudiMemoryManagerError[nbTestCase] = {
        RouDiMemoryManagerError::MEMORY_PROVIDER_EXHAUSTED,
        RouDiMemoryManagerError::NO_MEMORY_PROVIDER_PRESENT,
        RouDiMemoryManagerError::MEMORY_CREATION_FAILED,
        RouDiMemoryManagerError::MEMORY_DESTRUCTION_FAILED,
    };

    const char* m_testResultOperatorMethod[nbTestCase] = {"MEMORY_PROVIDER_EXHAUSTED",
                                                          "NO_MEMORY_PROVIDER_PRESENT",
                                                          "MEMORY_CREATION_FAILED",
                                                          "MEMORY_DESTRUCTION_FAILED"};

    MemoryBlockMock memoryBlock1;
    MemoryBlockMock memoryBlock2;
    MemoryProviderTestImpl memoryProvider1;
    MemoryProviderTestImpl memoryProvider2;

    RouDiMemoryManager sut;
};

TEST_F(RouDiMemoryManager_Test, CallingCreateAndAnnounceMemoryWithoutMemoryProviderFails)
{
    ::testing::Test::RecordProperty("TEST_ID", "8048cd15-3786-4eaf-9c26-e1cd6dce753c");
    auto expectError = sut.createAndAnnounceMemory();
    ASSERT_THAT(expectError.has_error(), Eq(true));
    EXPECT_THAT(expectError.get_error(), Eq(RouDiMemoryManagerError::NO_MEMORY_PROVIDER_PRESENT));
}

TEST_F(RouDiMemoryManager_Test, CallingCreateMemoryWithMemoryProviderSucceeds)
{
    ::testing::Test::RecordProperty("TEST_ID", "0634d8d5-5ab9-448b-a7c6-031b58374366");
    uint64_t MEMORY_SIZE_1{16};
    uint64_t MEMORY_ALIGNMENT_1{8};
    uint64_t MEMORY_SIZE_2{32};
    uint64_t MEMORY_ALIGNMENT_2{16};
    EXPECT_CALL(memoryBlock1, size()).WillRepeatedly(Return(MEMORY_SIZE_1));
    EXPECT_CALL(memoryBlock1, alignment()).WillRepeatedly(Return(MEMORY_ALIGNMENT_1));
    EXPECT_CALL(memoryBlock1, onMemoryAvailable(_));
    EXPECT_CALL(memoryBlock2, size()).WillRepeatedly(Return(MEMORY_SIZE_2));
    EXPECT_CALL(memoryBlock2, alignment()).WillRepeatedly(Return(MEMORY_ALIGNMENT_2));
    EXPECT_CALL(memoryBlock2, onMemoryAvailable(_));

    IOX_DISCARD_RESULT(memoryProvider1.addMemoryBlock(&memoryBlock1));
    IOX_DISCARD_RESULT(memoryProvider2.addMemoryBlock(&memoryBlock2));

    ASSERT_FALSE(sut.addMemoryProvider(&memoryProvider1).has_error());
    ASSERT_FALSE(sut.addMemoryProvider(&memoryProvider2).has_error());

    EXPECT_THAT(sut.createAndAnnounceMemory().has_error(), Eq(false));

    EXPECT_CALL(memoryBlock1, destroy());
    EXPECT_CALL(memoryBlock2, destroy());
}

TEST_F(RouDiMemoryManager_Test, CallingCreateMemoryWithMemoryProviderError)
{
    ::testing::Test::RecordProperty("TEST_ID", "b3d5a955-8dd3-40cb-9ac1-88021fbc52e1");
    ASSERT_FALSE(sut.addMemoryProvider(&memoryProvider1).has_error());

    // If no memory block is added to memory provider, Create and Announce Memory will return a error
    ASSERT_THAT(sut.createAndAnnounceMemory().has_error(), Eq(true));
    EXPECT_THAT(sut.createAndAnnounceMemory().get_error(), Eq(RouDiMemoryManagerError::MEMORY_CREATION_FAILED));

    ASSERT_FALSE(sut.destroyMemory().has_error());
}

TEST_F(RouDiMemoryManager_Test, RouDiMemoryManagerDTorTriggersMemoryProviderDestroy)
{
    ::testing::Test::RecordProperty("TEST_ID", "bb14b892-9f78-4494-a269-0c361b6a88bd");
    uint64_t MEMORY_SIZE_1{16};
    uint64_t MEMORY_ALIGNMENT_1{8};
    EXPECT_CALL(memoryBlock1, size()).WillRepeatedly(Return(MEMORY_SIZE_1));
    EXPECT_CALL(memoryBlock1, alignment()).WillRepeatedly(Return(MEMORY_ALIGNMENT_1));
    EXPECT_CALL(memoryBlock1, onMemoryAvailable(_));

    IOX_DISCARD_RESULT(memoryProvider1.addMemoryBlock(&memoryBlock1));

    {
        RouDiMemoryManager sutDestroy;
        ASSERT_FALSE(sutDestroy.addMemoryProvider(&memoryProvider1).has_error());
        ASSERT_FALSE(sutDestroy.createAndAnnounceMemory().has_error());
        EXPECT_CALL(memoryBlock1, destroy()).Times(1);
    }
    EXPECT_CALL(memoryBlock1, destroy()).Times(0);
}

TEST_F(RouDiMemoryManager_Test, AddMemoryProviderExceedsCapacity)
{
    ::testing::Test::RecordProperty("TEST_ID", "d80b71b8-7120-49f2-a77b-0f44a8abadde");
    MemoryProviderTestImpl memoryProvider[iox::MAX_NUMBER_OF_MEMORY_PROVIDER + 1];
    RouDiMemoryManager sutExhausting;

    for (uint32_t i = 0; i < iox::MAX_NUMBER_OF_MEMORY_PROVIDER; ++i)
    {
        EXPECT_THAT(sutExhausting.addMemoryProvider(&memoryProvider[i]).has_error(), Eq(false));
    }

    auto expectError = sutExhausting.addMemoryProvider(&memoryProvider[iox::MAX_NUMBER_OF_MEMORY_PROVIDER]);
    ASSERT_THAT(expectError.has_error(), Eq(true));
    EXPECT_THAT(expectError.get_error(), Eq(RouDiMemoryManagerError::MEMORY_PROVIDER_EXHAUSTED));
}

TEST_F(RouDiMemoryManager_Test, OperatorTest)
{
    ::testing::Test::RecordProperty("TEST_ID", "67167a98-5ac2-498d-8062-47a61102a130");
    iox::testing::Logger_Mock loggerMock;
    for (uint16_t i = 0; i < nbTestCase; i++)
    {
        IOX_LOGSTREAM_MOCK(loggerMock) << m_testCombinationRoudiMemoryManagerError[i];
        ASSERT_THAT(loggerMock.logs.size(), Eq(i + 1U));
        EXPECT_THAT(loggerMock.logs[i].message, Eq(m_testResultOperatorMethod[i]));
    }
}

} // namespace