text:
package com.ctrip.zeus.model.model;

public class SlbServer {
    private Long m_slbId;

    private String m_ip;

    private String m_hostName;

    public SlbServer() {
    }

    protected boolean equals(Object o1, Object o2) {
        if (o1 == null) {
            return o2 == null;
        } else if (o2 == null) {
            return false;
        } else {
            return o1.equals(o2);
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof SlbServer) {
            SlbServer _o = (SlbServer) obj;

            if (!equals(m_slbId, _o.getSlbId())) {
                return false;
            }

            if (!equals(m_ip, _o.getIp())) {
                return false;
            }

            if (!equals(m_hostName, _o.getHostName())) {
                return false;
            }

            return true;
        }

        return false;
    }

    public String getHostName() {
        return m_hostName;
    }

    public String getIp() {
        return m_ip;
    }

    public Long getSlbId() {
        return m_slbId;
    }

    @Override
    public int hashCode() {
        int hash = 0;

        hash = hash * 31 + (m_slbId == null ? 0 : m_slbId.hashCode());
        hash = hash * 31 + (m_ip == null ? 0 : m_ip.hashCode());
        hash = hash * 31 + (m_hostName == null ? 0 : m_hostName.hashCode());

        return hash;
    }

    public SlbServer setHostName(String hostName) {
        m_hostName = hostName;
        return this;
    }

    public SlbServer setIp(String ip) {
        m_ip = ip;
        return this;
    }

    public SlbServer setSlbId(Long slbId) {
        m_slbId = slbId;
        return this;
    }

}


text:
ngBrokenImage
=============

An AngularJS directive that replaces broken images with a default image.

redpajama_set_name: RedPajamaGithub


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

<TITLE>
Uses of Class com.fourspaces.couchdb.AdHocView (CouchDB4AJ 0.3.0-SVN API)
</TITLE>

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

      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
com.fourspaces.couchdb.AdHocView

Uses of AdHocView in com.fourspaces.couchdb

Methods in com.fourspaces.couchdb with parameters of type AdHocView

 ViewResults
Database.adhoc(AdHocView view)

          Runs an ad-hoc view from an AdHocView object.

      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
import sys
import django
from django.conf import settings, global_settings as default_settings
from django.core.management import execute_from_command_line
from os import path

# Give feedback on used versions
sys.stderr.write('Using Python version {0} from {1}\n'.format(sys.version[:5], sys.executable))
sys.stderr.write('Using Django version {0} from {1}\n'.format(
    django.get_version(),
    path.dirname(path.abspath(django.__file__)))
)

if not settings.configured:
    settings.configure(
        DATABASES = {
            'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:',},
        },
        SITE_ID = 1,
        INSTALLED_APPS = (
            'django.contrib.contenttypes',
            'django.contrib.sites',
            'django.contrib.auth',
            'fluent_contents',
            'fluentcms_emailtemplates',
            'fluentcms_emailtemplates.plugins.emailtext',
        ),
        TEMPLATES = [
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'DIRS': (),
                'OPTIONS': {
                    'loaders': (
                        'django.template.loaders.filesystem.Loader',
                        'django.template.loaders.app_directories.Loader',
                    ),
                    'context_processors': (
                        'django.template.context_processors.debug',
                        'django.template.context_processors.i18n',
                        'django.template.context_processors.media',
                        'django.template.context_processors.request',
                        'django.template.context_processors.static',
                        'django.contrib.auth.context_processors.auth',
                    ),
                },
            },
        ],
        MIDDLEWARE = (),
        TEST_RUNNER = 'django.test.runner.DiscoverRunner',
    )

DEFAULT_TEST_APPS = [
    'fluentcms_emailtemplates',
]

def runtests():
    other_args = list(filter(lambda arg: arg.startswith('-'), sys.argv[1:]))
    test_apps = list(filter(lambda arg: not arg.startswith('-'), sys.argv[1:])) or DEFAULT_TEST_APPS
    argv = sys.argv[:1] + ['test', '--traceback'] + other_args + test_apps
    execute_from_command_line(argv)

if __name__ == '__main__':
    runtests()


text:
import moment from 'moment';

import AnalyticsRaw from '../../../../../app/models/server/raw/Analytics';
import Sessions from '../../../../../app/models/server/raw/Sessions';
import { Users } from '../../../../../app/models/server/raw';
import { Analytics } from '../../../../../app/models/server';
import { convertDateToInt, diffBetweenDaysInclusive, getTotalOfWeekItems, convertIntToDate } from './date';

export const handleUserCreated = (user) => {
	if (user.roles?.includes('anonymous')) {
		return;
	}

	Promise.await(AnalyticsRaw.saveUserData({
		date: convertDateToInt(user.ts),
		user,
	}));
	return user;
};

export const fillFirstDaysOfUsersIfNeeded = async (date) => {
	const usersFromAnalytics = await AnalyticsRaw.findByTypeBeforeDate({
		type: 'users',
		date: convertDateToInt(date),
	}).toArray();
	if (!usersFromAnalytics.length) {
		const startOfPeriod = moment(date).subtract(90, 'days').toDate();
		const users = await Users.getTotalOfRegisteredUsersByDate({
			start: startOfPeriod,
			end: date,
		});
		users.forEach((user) => Analytics.insert({
			...user,
			date: parseInt(user.date),
		}));
	}
};

export const findWeeklyUsersRegisteredData = async ({ start, end }) => {
	const daysBetweenDates = diffBetweenDaysInclusive(end, start);
	const endOfLastWeek = moment(start).clone().subtract(1, 'days').toDate();
	const startOfLastWeek = moment(endOfLastWeek).clone().subtract(daysBetweenDates, 'days').toDate();
	const today = convertDateToInt(end);
	const yesterday = convertDateToInt(moment(end).clone().subtract(1, 'days').toDate());
	const currentPeriodUsers = await AnalyticsRaw.getTotalOfRegisteredUsersByDate({
		start: convertDateToInt(start),
		end: convertDateToInt(end),
		options: { count: daysBetweenDates, sort: { _id: -1 } },
	});
	const lastPeriodUsers = await AnalyticsRaw.getTotalOfRegisteredUsersByDate({
		start: convertDateToInt(startOfLastWeek),
		end: convertDateToInt(endOfLastWeek),
		options: { count: daysBetweenDates, sort: { _id: -1 } },
	});
	const yesterdayUsers = (currentPeriodUsers.find((item) => item._id === yesterday) || {}).users || 0;
	const todayUsers = (currentPeriodUsers.find((item) => item._id === today) || {}).users || 0;
	const currentPeriodTotalUsers = getTotalOfWeekItems(currentPeriodUsers, 'users');
	const lastPeriodTotalUsers = getTotalOfWeekItems(lastPeriodUsers, 'users');
	return {
		days: currentPeriodUsers.map((day) => ({ day: convertIntToDate(day._id), users: day.users })),
		period: {
			count: currentPeriodTotalUsers,
			variation: currentPeriodTotalUsers - lastPeriodTotalUsers,
		},
		yesterday: {
			count: yesterdayUsers,
			variation: todayUsers - yesterdayUsers,
		},
	};
};

export const findActiveUsersMonthlyData = async ({ start, end }) => {
	const startOfPeriod = moment(start);
	const endOfPeriod = moment(end);

	return {
		month: await Sessions.getActiveUsersOfPeriodByDayBetweenDates({
			start: {
				year: startOfPeriod.year(),
				month: startOfPeriod.month() + 1,
				day: startOfPeriod.date(),
			},
			end: {
				year: endOfPeriod.year(),
				month: endOfPeriod.month() + 1,
				day: endOfPeriod.date(),
			},
		}),
	};
};

export const findBusiestsChatsInADayByHours = async ({ start }) => {
	const now = moment(start);
	const yesterday = moment(now).clone().subtract(24, 'hours');
	return {
		hours: await Sessions.getBusiestTimeWithinHoursPeriod({
			start: yesterday.toDate(),
			end: now.toDate(),
		}),
	};
};

export const findBusiestsChatsWithinAWeek = async ({ start }) => {
	const today = moment(start);
	const startOfCurrentWeek = moment(today).clone().subtract(7, 'days');

	return {
		month: await Sessions.getTotalOfSessionsByDayBetweenDates({
			start: {
				year: startOfCurrentWeek.year(),
				month: startOfCurrentWeek.month() + 1,
				day: startOfCurrentWeek.date(),
			},
			end: {
				year: today.year(),
				month: today.month() + 1,
				day: today.date(),
			},
		}),
	};
};

export const findUserSessionsByHourWithinAWeek = async ({ start, end }) => {
	const startOfPeriod = moment(start);
	const endOfPeriod = moment(end);

	return {
		week: await Sessions.getTotalOfSessionByHourAndDayBetweenDates({
			start: startOfPeriod.toDate(),
			end: endOfPeriod.toDate(),
		}),
	};
};


text:
require "test_helper"

describe HttpObjects::Headers::Tools do

  TestObject = Class.new

  subject { Object.new.extend(HttpObjects::Headers::Tools) }

  describe "Header" do
    it "creates Class" do
      header_class = subject.Header("name", TestObject)
      header_class.new.must_be_kind_of(TestObject)
    end
    it "creates Class with header_name" do
      header_class = subject.Header("name", TestObject)
      header_class.header_name.must_equal("name")
    end
    it "creates Class using block" do
      header_class = subject.Header("custom") do
        def self.parse(value)
          "#{value} header class!"
        end
      end
      header_class.parse("custom").must_equal("custom header class!")
    end
  end

end


text:
package org.apache.bookkeeper.proto;

import org.apache.bookkeeper.net.BookieSocketAddress;
import org.apache.bookkeeper.tls.SecurityException;
import org.apache.bookkeeper.tls.SecurityHandlerFactory;

/**
 * Factory to create {@link org.apache.bookkeeper.proto.PerChannelBookieClient}.
 */
interface PerChannelBookieClientFactory {

    /**
     * Create a {@link org.apache.bookkeeper.proto.PerChannelBookieClient} to
     * <i>address</i>.
     *
     * @return the client connected to address.
     * @throws SecurityException
     */
    PerChannelBookieClient create(BookieSocketAddress address,
            PerChannelBookieClientPool pcbcPool, SecurityHandlerFactory shFactory) throws SecurityException;
}


text:
import React, { Component } from "react";
import PropTypes from "prop-types";
import Add from "./Add";
import conferences from "./data/events.json";
import archive from "./data/archiveMetadata.json";
import "./App.css";
import moment from "moment";
import ButtonGroup from "./ButtonGroup";
import { isMobileish } from "./utils/layoutUtils";
import {
  getCompressedObject,
  getDecompressedObject
} from "./utils/compressionUtils";
import DetailsSection from "./DetailsSection";
import Share from "./Share";
import axios from "axios";
import { Link } from "react-router-dom";

import {
  Header,
  Footer,
  FooterLeft,
  FooterMiddle,
  FooterRight,
  SharedHeadingWrapper,
  AdWrapper,
  FullWidthRow,
  Column
} from './styles';

const FAVORITE_KEY = "conferenceradar:favorites";

const status = {
  cancelled: "cancelled",
  postponed: "postponed",
  happening: "happening",
  online: "online",
  noInfo: "noInfo"
};

class App extends Component {
  static childContextTypes = {
    favorites: PropTypes.object
  };

  state = {
    dataType: "upcoming",
    showForm: false,
    additionalFilter: ""
  };

  metadataLookup = {};
  upcomingLookup = {};
  metadataKeys = [];
  favoriteKeys = [];

  // this is kind of tricky -- we are rendering data but controlling it through this.state.dataType
  data = {};

  constructor() {
    super();

    //build metadata lookup;
    archive.forEach(item => {
      this.metadataLookup[item.key.toString()] = item;
    });

    this.metadataKeys = [
      "upcoming",
      ...Object.keys(this.metadataLookup).sort((a, b) => b - a)
    ];

    conferences.forEach(item => {
      this.upcomingLookup[item.key] = item;
    });

    this.data["upcoming"] = conferences;
    this.favoriteKeys = this.getFavorites();
  }

  getChildContext() {
    return {
      favorites: {
        favoriteKeys: this.favoriteKeys,
        getFavorites: this.getFavorites,
        setFavorites: this.setFavorites,
        addItemToFavorites: this.addItemToFavorites,
        removeItemFromFavorites: this.removeItemFromFavorites,
        // TODO: Clean this up -- pretty messy
        getCompressedFavorites: () => {
          return getCompressedObject(this.wrapFavoriteKeys(this.favoriteKeys));
        }
      }
    };
  }

  getFavorites = () => {
    const favorites = localStorage.getItem(FAVORITE_KEY);
    return !!favorites
      ? this.unwrapFavoriteKeys(getDecompressedObject(favorites))
      : [];
  };

  // This is to make it so we can have versions of the
  // favorite keys objects that get saved to local storage and shared
  // we are basically hardcoding this all to version: 0 for now
  // because I do think we will want to change some things moving forward.
  wrapFavoriteKeys = favoriteKeys => {
    return {
      version: 0,
      favoriteKeys
    };
  };

  unwrapFavoriteKeys = obj => {
    return obj.favoriteKeys;
  };

  setFavorites = () => {
    const wrapped = this.wrapFavoriteKeys(this.favoriteKeys);
    return localStorage.setItem(FAVORITE_KEY, getCompressedObject(wrapped));
  };

  addItemToFavorites = itemKey => {
    this.favoriteKeys.push(itemKey);
    this.setFavorites();
  };

  removeItemFromFavorites = itemKey => {
    // TODO: Make better
    const items = this.favoriteKeys.filter(item => item !== itemKey);
    this.favoriteKeys = items;
    this.setFavorites();
  };

  loadData = key => {
    // TODO: this is a pretty ugly check -- no-op if key is invalid
    if (
      key !== "upcoming" &&
      Object.keys(this.metadataLookup).indexOf(key) < 0
    ) {
      return;
    }

    // set state and return if we already have this data
    if (this.data[key]) {
      this.setState({ dataType: key, additionalFilter: "" });
      return;
    }

    // load the data if we don't have it already and update the dataType
    axios.get(this.metadataLookup[key].path).then(response => {
      this.data[key] = response.data;
      this.setState({ dataType: key, additionalFilter: "" });
    });
  };

  // TODO: Don't really dig this so much
  // this branches based on what is calling the change
  // it's either a filter or it says load new data
  onChangeFilter = filter => {
    let additionalStates = {};
    if (filter !== "dates") {
      additionalStates = { startDate: undefined, endDate: undefined };
    }
    if (filter === this.state.additionalFilter) {
      return;
    }

    this.setState(previousState => {
      return filter === "openCfps"
        ? {
          additionalFilter: filter,
          dataType: "upcoming",
          ...additionalStates
        }
        : {
          additionalFilter: filter,
          ...additionalStates
        };
    });
  };

  onToggleForm = () => {
    this.setState(prevState => ({
      showForm: !prevState.showForm,
      showShare: false
    }));
  };

  onToggleShare = () => {
    this.setState(prevState => ({
      showShare: !prevState.showShare,
      showForm: false
    }));
  };

  getSharedTitle = () => {
    const { isShared, title } = this.props;

    if (isShared) {
      return (

          {getDecompressedObject(title)} (shared)

      );
    }
  };

  getData = () => {
    const { dataType, additionalFilter, startDate, endDate } = this.state;
    const { isShared, list } = this.props;

    if (isShared) {
      const items = this.unwrapFavoriteKeys(getDecompressedObject(list));
      return conferences.filter(
        conference => items.indexOf(conference.key) >= 0
      );
    }

    const data = this.data[dataType];
    switch (additionalFilter) {
      case "openCfps":
        return conferences.filter(
          conference =>
            conference.cfpEndDate &&
            conference.cfpEndDate > moment().toISOString()
        );
      case "myRadar":
        return conferences.filter(
          conference => this.favoriteKeys.indexOf(conference.key) >= 0
        );
      case "dates":
        return conferences.filter(
          conference =>
            conference.eventStartDate > this.state.startDate &&
            conference.eventEndDate < this.state.endDate
        );
      case status.cancelled:
        return conferences.filter(
          conference => conference.status === status.cancelled
        );
      case status.happening:
        return conferences.filter(
          conference => conference.status === status.happening
        );
      case status.online:
        return conferences.filter(
          conference => conference.status === status.online
        );
      case status.noInfo:
        return conferences.filter(
          conference => conference.status === status.noInfo
        );
      case status.postponed:
        return conferences.filter(
          conference => conference.status === status.postponed
        );
      default:
        return data;
    }
  };

  setDates = (startDate, endDate) => {
    this.setState({ startDate, endDate, additionalFilter: "dates" });
  };

  render() {
    const data = this.getData();
    const sharedTitle = this.getSharedTitle();
    return (

          <FullWidthRow style={{ width: "100%" }}>
            <Column>

Conference Radar

Keep track of conference cancellations.

            </Column>
            <Column className="addEventButtonWrapper">

                  Know of a conference not listed? Notice an issue?

                  <button
                    onClick={this.onToggleForm}
                    className={`addEvent button`}
                  >
                    {this.state.showForm ? 'Back to list' : 'Add Event'}
                  </button>

            </Column>
          </FullWidthRow>

        {this.props.isShared
          ? (
            <SharedHeadingWrapper>
              <Link to='/'>Back to all listings</Link>
              {sharedTitle}
            </SharedHeadingWrapper>
          )
          : (
            <ButtonGroup
              onChangeFilter={this.onChangeFilter}
              onChangeData={this.loadData}
              items={this.metadataKeys}
              selectedDropdownItem={this.state.dataType}
              selectedTab={this.state.additionalFilter || 'main'}
              toggleForm={this.onToggleForm}
              toggleShare={this.onToggleShare}
              isMobile={isMobileish()}
              showShare={this.state.showShare}
              showForm={this.state.showForm}
              startDate={this.state.startDate}
              endDate={this.state.endDate}
              setDates={this.setDates}
            />)
        }
        {this.state.showForm && <Add />}
        {!isMobileish() && this.state.showShare && <Share />}
        {!this.state.showForm && <DetailsSection data={data} />}

          <FooterLeft>
            For more information on the Coronavirus/COVID-19, please visit the World Health Organization's official page.

            Please also consider donating to Doctors Without Borders.
        </FooterLeft>
          <FooterMiddle>
            <AdWrapper>

                FIST BUMPS ONLY™
Better than a handshake. Pins, shirts, and more.

            </AdWrapper>
          </FooterMiddle>
          <FooterRight>

              This is a community maintained site/list provided as-is without
              guarantee or warranty. If you notice an issue or innacuracy,
              please{" "}

                file an issue/PR on GitHub

              .

          </FooterRight>

    );
  }
}

export default App;


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

<!--
 // SIX OVAL
 // Spring Application Context - property
 //
 // @author	Akihito Nakamura
-->

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/util
      http://www.springframework.org/schema/util/spring-util.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- external configurations -->
    <context:property-placeholder
        location="classpath:io/opensec/six/oval/core/six-oval_defaults.properties,classpath:six-oval.properties"
        ignore-resource-not-found="true"
        system-properties-mode="OVERRIDE"
        />
        <!-- NOTE:
        location: Properties defined in later files will override properties defined earlier files,
            in case of overlapping keys.
        system-properties-mode: "override" will check for a system property first,
            before trying the specified properties.
        -->

    <!-- ************************************************************** -->
    <!-- *  Properties bean                                           * -->
    <!-- ************************************************************** -->

<!-- NOW, we use these paths as constructor arguments of SpringContext superclass.
    If the properties file does NOT exist, e.g. classpath:opensec-oval.properties,
    the Spring container throws an exception to indicate failure in creating the properties bean.

    <util:properties id="six-oval-default-properties"
        location="classpath:io/opensec/oval/core/six-oval_defaults.properties"/>

    <util:properties id="opensec-oval-properties"
        location="classpath:opensec-oval.properties"/>
-->

<!-- DO NOT USE THIS!
    <context:property-override location="classpath:opensec-oval.properties"
        ignore-resource-not-found="true"
        />
-->

</beans>


text:
using System;
using Introduction_to_Entity_Framework.Data.Models;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace P02_DatabaseFirst
{
    class StartUp
    {
        static void Main(string[] args)
        {
            var context = new SoftUniDbContext();
            using (context)
            {
                var employees = context.Employees
                    .Where(e => e.FirstName.StartsWith('S') &&
                    e.FirstName.IndexOf('a') == 1)
                    .Select(e => new
                    {
                        e.FirstName,
                        e.LastName,
                        e.JobTitle,
                        e.Salary
                    })
                    .OrderBy(e => e.FirstName)
                    .ThenBy(e => e.LastName)
                    .ToList();

                foreach (var e in employees)
                {
                    Console.WriteLine($"{e.FirstName} {e.LastName} - {e.JobTitle} - (${e.Salary:f2})");
                }
            }
        }
    }
}


text:
"""Make filters with the mongo language"""
import operator
from functools import partial

from ut.pdict.get import get_value_in_key_path

print(
    'This is a partial implementation of mongoquery (https://pypi.org/project/mongoquery/) '
    'before I knew it existed. Might want to use mongoquery instead.'
)

def nor(*args):
    for a in args:
        if not bool(a):
            return True
    return False

mg_op_key_to_op = {
    '$gte': operator.le,  # operator reversed because arguments inverse of order we need in code
    '$gt': operator.lt,  # operator reversed because arguments inverse of order we need in code
    '$lte': operator.ge,  # operator reversed because arguments inverse of order we need in code
    '$lt': operator.gt,  # operator reversed because arguments inverse of order we need in code
    '$in': operator.contains,
    '$nin': lambda element, _set: not operator.contains(_set, element),
    '$eq': operator.eq,
    '$neq': operator.ne,
    '$not': operator.not_,
    '$and': operator.__and__,  # TODO: Need to extend to more than two operands
    '$or': operator.__or__,  # TODO: Need to extend to more than two operands
    '$nor': nor,
}  # NOTE: Apparent misalignment of gt and lt ops on purpose (order of operator and use is flipped.

def mg_filt_kv_to_func_2(key_path, val_condition):
    """
    """
    func_list = _func_list_of_val_condition(val_condition)
    if func_list:
        if isinstance(val_condition, dict):
            if func_list:
                return _conjunction_key_func_for_func_list_and_key_path(
                    func_list, key_path
                )
        elif isinstance(val_condition, list):
            if key_path == '$and':
                return _conjunction_key_func_for_func_list_and_key_path(
                    func_list, key_path
                )
            elif key_path == '$or':
                return _disjunction_key_func_for_func_list_and_key_path(
                    func_list, key_path
                )
            else:
                raise ValueError(
                    'val_condition was a list, but key_path was neither $and nor $or'
                )

    def key_func(_dict):
        return get_value_in_key_path(_dict, key_path, None) == val_condition

    return key_func

def _conjunction_key_func_for_func_list_and_key_path(func_list, key_path):
    def key_func(_dict):
        """
        Returns True if and only iff all func_list funcs return True
        """
        for f in func_list:
            if not f(get_value_in_key_path(_dict, key_path, None)):
                return False  # stop early, we know it's False
        return True

    return key_func

def _disjunction_key_func_for_func_list_and_key_path(func_list, key_path):
    def key_func(_dict):
        """
        Returns True if and only iff all func_list funcs return True
        """
        for f in func_list:
            if not f(get_value_in_key_path(_dict, key_path, None)):
                return True  # stop early, we know it's False
        return False

    return key_func

def _func_list_of_val_condition(val_condition):
    func_list = list()
    if isinstance(val_condition, dict):
        for k, v in val_condition.items():
            if k.startswith('$'):
                func_list.append(partial(mg_op_key_to_op[k], v))
    return func_list

def mg_filt_kv_to_func(key_path, val_condition):
    """
    Returns a function that checks
        (1) The existance of a key path in a dict
        (2) If the value satisfies the condition specified by mongo-query-like val_condition
    :param key_path: A key path. That is, a field name, or a nested field specification,
        such as 'this.is.a.nested.field'.
    :param val_condition: A value or a (single field) mongo-query-like dict
    :return: A function
    """
    if isinstance(val_condition, dict):
        func_list = list()
        for k, v in val_condition.items():
            if k.startswith('$'):
                func_list.append(partial(mg_op_key_to_op[k], v))
        if func_list:

            def key_func(_dict):
                """
                Returns True if and only iff all func_list funcs return True
                """
                for f in func_list:
                    if not f(get_value_in_key_path(_dict, key_path, None)):
                        return False  # stop early, we know it's False
                return True

            return key_func

    def key_func(_dict):
        return get_value_in_key_path(_dict, key_path, None) == val_condition

    return key_func

def key_func_list_from_mg_filt(mg_filt):
    """
    Just applies mg_filt_kv_to_func to every element of the (dict) mg_filt
    :param mg_filt: A mongo-query-like dict (can have several fields
    :return: A list of functions
    """
    return [mg_filt_kv_to_func(*x) for x in iter(mg_filt.items())]

def dict_filt_from_mg_filt(mg_filt):
    """
    The final intent is to do what a mongo query does on a collection, but with a dict iterator instead.
    dict_filt_from_mg_filt creates, based on a mg_filt (that uses the same language as mongo, a filter.
    A filter is a function that returns True iff mg_filt condition is satistfied.
    Basically, if mgc is a mongo collection and dict_iter is a dict iterator containing the same dicts,
    the following should be equivalent:
        mgc.find(mg_filt) and itertools.ifilter(dict_filt_from_mg_filt(mg_filt), dict_iter)
    In fact, you can test this directly with a (small) mongo collection by doing:
        assert list(mgc.find(mg_filt)) == filter(dict_filt_from_mg_filt(mg_filt), mgc.find())
    :param mg_filt:
    :return: a filter (a function returning True or False)

    >>> ####### A complicated one
    >>> mg_filt = {
    ...    'a': {'$in': [3, 4, 5]},
    ...    'x': {'$gte': 10, '$lt': 20},
    ...    'foo.bar': 'bit',
    ...    'this': {'is': 'that'},
    ... }
    >>> filt = dict_filt_from_mg_filt(mg_filt)
    >>> filt({'a': 3, 'x': 15, 'foo': {'bar': 'bit'}, 'this': {'is': 'that'}, 'and_something': 'else'})
    True
    >>> filt({'a': 1, 'x': 15, 'foo': {'bar': 'bit'}, 'this': {'is': 'that'}, 'and_something': 'else'})
    False
    >>> filt({'a': 3, 'x': 20, 'foo': {'bar': 'bit'}, 'this': {'is': 'that'}, 'and_something': 'else'})
    False
    >>> filt({'a': 3, 'x': 15, 'foo.bar': 'bit', 'this': {'is': 'that'}, 'and_something': 'else'})
    False
    >>> ####### testing equality
    >>> filt = dict_filt_from_mg_filt(mg_filt={'foo': 'bar'})
    >>> # True when equal
    >>> filt({'foo': 'bar'})
    True
    >>> # false when not equal
    >>> filt({'foo': 'bear'})
    False
    >>> # false if key not present
    >>> filt({'fool': 'bar'})
    False
    >>> # can also have equality of dicts
    >>> filt = dict_filt_from_mg_filt(mg_filt={'foo': {'bar': 'bit'}})
    >>> filt({'foo': {'bar': 'bit'}})
    True
    >>> ####### A single >= comparison
    >>> mg_filt = {'a': {'$gte': 10}}
    >>> filt = dict_filt_from_mg_filt(mg_filt)
    >>> filt({'a': 9})
    False
    >>> filt({'a': 10})
    True
    >>> filt({'a': 11})
    True
    >>> ####### A single > comparison
    >>> filt = dict_filt_from_mg_filt({'a': {'$gt': 10}})
    >>> filt({'a': 9})
    False
    >>> filt({'a': 10})
    False
    >>> filt({'a': 11})
    True
    >>> ####### A range query
    >>> filt = dict_filt_from_mg_filt({'a': {'$gte': 10, '$lt': 20}})
    >>> map(filt, [{'a': x} for x in [9, 10, 15, 20, 21]])
    [False, True, True, False, False]
    """
    key_func_list = key_func_list_from_mg_filt(mg_filt)

    def _filt(_dict):
        for i, f in enumerate(key_func_list):
            if not f(_dict):
                return False
        return True  # if you get this far

    return _filt


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syll. fung. (Abellini) 21: 418 (1912)

#### Original name
Hypochnus tabacinus Bres.

### Remarks
null


text:
#include <algorithm>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include "sample_allelic_expression.h"

SampleAllelicExpression::SampleAllelicExpression(AlignmentIncidenceMatrix *alignment_incidence, double tolerance) :
    alignment_incidence_(alignment_incidence)
{
    num_haplotypes = (int)alignment_incidence->num_haplotypes();
    num_transcripts = (int)alignment_incidence->num_transcripts();

    current_ = new double[size()];
    previous_ = new double[size()];

    // This is allocated during init(), since it's size depends on the
    // maximum number of transcripts with hits in a single read
    working_ = NULL;

    // only used by some normalization modes, will allocate if required.
    transcript_sums_ = NULL;
    gene_sums_ = NULL;
    gene_sum_by_strain_ = NULL;
    gene_sum_by_strain_hits_only_ = NULL;
    gene_sum_hits_only_ = NULL;
    gene_masks_ = NULL;
    read_sum_by_gene_ = NULL;

    /*
    if (alignment_incidence->transcript_lengths_.size() / num_haplotypes == alignment_incidence->num_transcripts()) {
        // we are doing length adjustment, mutltiply threshold by 1M
        threshold_ = tolerance * 1000000;
    }
    else {
        // no length adjustment, multiply threshold by number of reads
        threshold_ = tolerance * alignment_incidence->total_reads();
    }
    */

    threshold_ = tolerance * alignment_incidence->total_reads();

    init();
}

SampleAllelicExpression::~SampleAllelicExpression() {
    delete [] current_;
    delete [] previous_;

    if (transcript_sums_) {
        delete [] transcript_sums_;
    }

    if (gene_sum_hits_only_) {
        delete [] gene_sum_hits_only_;
    }

    if (working_) {
        delete [] working_;
    }

    if (gene_sums_) {
        delete [] gene_sums_;
    }

    if (gene_sum_by_strain_) {
        delete [] gene_sum_by_strain_;
    }

    if (gene_sum_by_strain_hits_only_) {
        delete [] gene_sum_by_strain_hits_only_;
    }

    if (gene_masks_) {
        delete [] gene_masks_;
    }

    if (read_sum_by_gene_) {
        delete [] read_sum_by_gene_;
    }
}

void SampleAllelicExpression::init() {
    init_normalize_read();
    applyTranscriptLength();
}

void SampleAllelicExpression::init_normalize_read() {
    std::fill(current_, current_ + size(), 0.0);

    int working_size;
    int start_index;
    int free_slots;
    int work_index;
    double read_sum;
    auto end = alignment_incidence_->row_ptr.size() - 1;

    working_size = num_haplotypes * 4;
    free_slots = working_size;
    working_ = new double[working_size];

    //iterate over each read
    for (int i = 0; i != end; ++i) {
        work_index = 0;
        read_sum = 0.0;
        free_slots = working_size;

        // alignment_incidence_->row_ptr[i] gives us the start index for the
        // nozero values that make up this row
        // and there will be alignment_incidence_->row_ptr[i+1] - alignment_incidence_->row_ptr[i] values
        for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {
            // make sure we haven't run out of memory in our working_ buffer
            // if it is full, double the capacity.  The size will always be a
            // multiple of num_haplotypes.
            if (free_slots == 0) {
                double *tmp = working_;
                working_ = new double[working_size * 2];
                std::copy(tmp, tmp + working_size, working_);

                // increased capacity by working_size, so we have working_size
                // free slots now (was full).
                free_slots = working_size;
                working_size *= 2;
                delete tmp;
            }

            // going to consume num_haplotypes more elements in working_ so
            // decrement the amount of free space
            free_slots -= num_haplotypes;

            // okay, we can do the actual work for this read
            for (int k = 0; k < num_haplotypes; ++k) {
                // initialize to 1.0 if they had a hit, 0 otherwise
                // each haplotype is represented by a single bit in the value
                if (alignment_incidence_->val[j] & (1 << k)) {
                    working_[work_index++] = 1.0;
                    read_sum += 1.0;
                }
                else {
                    working_[work_index++] = 0.0;
                }
            }
        }

        work_index = 0;
        for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {
            start_index = alignment_incidence_->col_ind[j] * num_haplotypes;
            for (int k = 0; k < num_haplotypes; ++k) {
                current_[start_index + k] += (working_[work_index++] / read_sum) * (double)alignment_incidence_->counts[i];
            }
        }
    }
}

void SampleAllelicExpression::update(SampleAllelicExpression::model m) {
    switch (m) {

        case MODEL_1:
            updateModel1();
            break;

        case MODEL_2:
            updateModel2();
            break;

        case MODEL_3:
            updateModel3();
            break;

        case MODEL_4:
            updateModel4();
            break;
    }

    applyTranscriptLength();

}

void SampleAllelicExpression::updateNoApplyTL(SampleAllelicExpression::model m) {
    switch (m) {

        case MODEL_1:
            updateModel1();
            break;

        case MODEL_2:
            updateModel2();
            break;

        case MODEL_3:
            updateModel3();
            break;

        case MODEL_4:
            updateModel4();
            break;
    }
}

void SampleAllelicExpression::updateModel1() {
    int start_index;
    int work_index;
    double read_sum;
    auto end = alignment_incidence_->row_ptr.size() - 1;

    if (!gene_sums_) {
        gene_sums_ =  new double[alignment_incidence_->num_genes()];
    }

    // allocate some extra working memory needed by this model
    if (!gene_sum_by_strain_) {
        gene_sum_by_strain_ = new double[num_haplotypes * alignment_incidence_->num_genes()];
    }

    if (!gene_sum_hits_only_) {
        gene_sum_hits_only_ = new double[alignment_incidence_->num_genes()];
    }

    if (!gene_sum_by_strain_hits_only_) {
        gene_sum_by_strain_hits_only_ = new double[num_haplotypes * alignment_incidence_->num_genes()];
    }

    if (!gene_masks_) {
        gene_masks_ = new int[alignment_incidence_->num_genes()];
    }

    if (!transcript_sums_) {
        transcript_sums_ = new double[num_transcripts];
    }

    std::swap(current_, previous_);

    // clear current_ so we can use it to accumulate sums
    std::fill(current_, current_ + size(), 0.0);

    // generate gene_sum_by_strain from previous value
    std::fill(gene_sum_by_strain_, gene_sum_by_strain_ + alignment_incidence_->num_genes() * num_haplotypes, 0.0);
    for (int i = 0; i < num_transcripts; ++i) {
        for (int j = 0; j < num_haplotypes; ++j) {
            gene_sum_by_strain_[alignment_incidence_->tx_to_gene[i] * num_haplotypes + j] += previous_[i * num_haplotypes + j];
        }
    }

    // generate transcript sums from previous value
    for (int i = 0; i < num_transcripts; ++i) {
        transcript_sums_[i] = 0.0;
        for (int j = 0; j < num_haplotypes; ++j) {
            transcript_sums_[i] += previous_[i*num_haplotypes + j];
        }
    }

    // generate gene sums from previous value
    std::fill(gene_sums_, gene_sums_ + alignment_incidence_->num_genes(), 0.0);
    double genes_total = 0.0;
    for (int i = 0; i < num_transcripts; ++i) {
        gene_sums_[alignment_incidence_->tx_to_gene[i]] += transcript_sums_[i];
        genes_total += transcript_sums_[i];
    }

    //std::cout << "END: " << end << std::endl;
    //iterate over each read
    for (int i = 0; i != end; ++i) {
        read_sum = 0.0;

        /* unfortunately, given the information we have and the way it is stored in memory,  we need to make three passes over
           this read computing some values we need for the actual update, which is yet another pass over this read, followed by
           a read-normalization step giving us a total of 5 iterations over the read.  It would be
           possible to come up with another way to store the data that might reduce the number of passes we need.  Initial
           benchmarking gave us around a 4s update time for a test file with 8 strains, ~30K genes, ~95K transcripts, and 5.9M reads
           on an Intel Xeon E5-2670.  This is still fast enough for us to converge in a few minutes in most cases, and this is
           before multi-threading is implemented.
         */

        for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {
            // make sure gene_sum_by_strain_hits_only_ is initialized to zero for any gene that has a hit for this read
            for (int k = 0; k < num_haplotypes; ++k) {
                gene_sum_by_strain_hits_only_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]] * num_haplotypes + k] = 0.0;
            }
            // also need to clear out gene_sum_hits_only_ and gene_masks_ for any gene with a hit
            gene_sum_hits_only_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]]] = 0.0;
            gene_masks_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]]] = 0;
        }

        // compute gene_sum_by_strain_hits_only_, gene_masks_
        for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {
            start_index = alignment_incidence_->col_ind[j] * num_haplotypes;

            for (int k = 0; k < num_haplotypes; ++k) {
                if (alignment_incidence_->val[j] & (1 << k)) {
                    gene_sum_by_strain_hits_only_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]] * num_haplotypes + k] += previous_[start_index + k];
                }
                gene_masks_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]]] |= alignment_incidence_->val[j];
            }
        }

        // compute gene_sum_hits_only_ using gene_sum_by_strain_ and gene_masks_
        for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {
            start_index = alignment_incidence_->col_ind[j] * num_haplotypes;

            if (gene_masks_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]]]) {
                for (int k = 0; k < num_haplotypes; ++k) {
                    if (gene_masks_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]]] & (1 << k)) {
                        gene_sum_hits_only_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]]] += gene_sum_by_strain_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]] * num_haplotypes + k];
                    }
                }

                // don't contribute this gene to the sum more than once even if it appears multiple times in read
                // zeroing out the mask will ensure we skip this gene if we see it again
                gene_masks_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]]] = 0;
            }
        }

        // finally we can compute the actual values to add to current_
        work_index = 0;
        for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {

            start_index = alignment_incidence_->col_ind[j] * num_haplotypes;

            for (int k = 0; k < num_haplotypes; ++k) {
                if (alignment_incidence_->val[j] & (1 << k)) {
                    working_[work_index] = (previous_[start_index + k] / gene_sum_by_strain_hits_only_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]] * num_haplotypes + k]) *
                                           (gene_sum_by_strain_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]] * num_haplotypes + k] / gene_sum_hits_only_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]]]) *
                                           (gene_sums_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]]] / genes_total);

                    if (working_[work_index] != working_[work_index]) {
                        // nan! underflow!

                        // set to zero
                        working_[work_index] = 0.0;

                        // skip this location next time
                        alignment_incidence_->val[j] &= ~(1 << k);
                    }
                    read_sum += working_[work_index++];
                }
                else {
                    working_[work_index++] = 0.0;
                }
            }
        }

        //std::cout << "read_sum: " << read_sum << std::endl;
        // now we can normalize by read and sum into current_
        if (read_sum > 0) {
            work_index = 0;
            for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {

                start_index = alignment_incidence_->col_ind[j] * num_haplotypes;

                for (int k = 0; k < num_haplotypes; ++k) {
                    current_[start_index + k] += (working_[work_index] / read_sum) * (double)alignment_incidence_->counts[i];
                    work_index++;
                }
            }
        }
    }
}

void SampleAllelicExpression::updateModel2() {
    std::swap(current_, previous_);

    // clear current_ so we can use it to accumulate sums
    std::fill(current_, current_ + size(), 0.0);

    int start_index;
    int work_index;
    int transcript_hits;
    double transcript_sum;
    double read_sum;
    auto end = alignment_incidence_->row_ptr.size() - 1;

    if (!gene_sums_) {
        gene_sums_ =  new double[alignment_incidence_->num_genes()];
    }

    if (!gene_sum_hits_only_) {
        gene_sum_hits_only_ = new double[alignment_incidence_->num_genes()];
    }

    if (!transcript_sums_) {
        transcript_sums_ = new double[num_transcripts];
    }

    // generate transcript sums from previous value
    for (int i = 0; i < num_transcripts; ++i) {
        transcript_sums_[i] = 0.0;
        for (int j = 0; j < num_haplotypes; ++j) {
            transcript_sums_[i] += previous_[i*num_haplotypes + j];
        }
    }

    // generate gene sums from previous value
    std::fill(gene_sums_, gene_sums_ + alignment_incidence_->num_genes(), 0.0);
    double genes_total = 0.0;
    for (long i = 0; i < num_transcripts; ++i) {
        gene_sums_[alignment_incidence_->tx_to_gene[i]] += transcript_sums_[i];
        genes_total += transcript_sums_[i];
    }

    // normalize gene_sums_
    for (int i = 0; i < alignment_incidence_->num_genes(); i++) {
        gene_sums_[i] /= genes_total;
    }

    //iterate over each read
    for (int i = 0; i != end; ++i) {
        work_index = 0;
        read_sum = 0.0;

        for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {
            gene_sum_hits_only_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]]] = 0.0;

            start_index = alignment_incidence_->col_ind[j] * num_haplotypes;
            for (int k = 0; k < num_haplotypes; ++k) {
                // initialize all strains at this locus
                if (alignment_incidence_->val[j] & (1 << k)) {
                    working_[work_index++] = previous_[start_index + k];
                }
                else {
                    working_[work_index++] = 0.0;
                }
            }
        }

        transcript_hits = work_index / num_haplotypes;

        // normalize working_ by transcript
        for (long j = 0; j < transcript_hits; j++) {
            transcript_sum = 0.0;
            for (int k = 0; k < num_haplotypes; ++k) {
                transcript_sum += working_[j * num_haplotypes + k];
            }
            for (int k = 0; k < num_haplotypes; ++k) {
                 working_[j * num_haplotypes + k] /= transcript_sum;
            }
        }

        // isoform_specificity
        for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {
            long gene_index = alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]];
            gene_sum_hits_only_[gene_index] += transcript_sums_[alignment_incidence_->col_ind[j]];
        }

        work_index = 0;
        for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {
            long gene_index = alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]];
            double isoform_specificity = transcript_sums_[alignment_incidence_->col_ind[j]] / gene_sum_hits_only_[gene_index];
            for (int k = 0; k < num_haplotypes; ++k) {
                working_[work_index] *= isoform_specificity * gene_sums_[gene_index];

                if (working_[work_index] != working_[work_index]) {
                    // nan! underflow!

                    // set to zero
                    working_[work_index] = 0.0;

                    // skip this location next time
                    alignment_incidence_->val[j] &= ~(1 << k);
                }
                read_sum += working_[work_index++];

            }
        }

        work_index = 0;
        for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {
            start_index = alignment_incidence_->col_ind[j] * num_haplotypes;
            for (int k = 0; k < num_haplotypes; ++k) {
                current_[start_index + k] += (working_[work_index++] / read_sum) * (double)alignment_incidence_->counts[i];
            }
        }
    }
}

void SampleAllelicExpression::updateModel3() {
    long start_index;
    int work_index;
    double read_sum;
    auto end = alignment_incidence_->row_ptr.size() - 1;

    if (!read_sum_by_gene_) {
        read_sum_by_gene_ = new double[alignment_incidence_->num_genes()];
    }

    if (!gene_sums_) {
        gene_sums_ =  new double[alignment_incidence_->num_genes()];
    }

    if (!gene_sum_hits_only_) {
        gene_sum_hits_only_ = new double[alignment_incidence_->num_genes()];
    }

    if (!transcript_sums_) {
        transcript_sums_ = new double[num_transcripts];
    }

    std::swap(current_, previous_);
    std::fill(current_, current_ + size(), 0.0);

    // generate transcript sums from previous value
    for (int i = 0; i < num_transcripts; ++i) {
        transcript_sums_[i] = 0.0;
        for (int j = 0; j < num_haplotypes; ++j) {
            transcript_sums_[i] += previous_[i*num_haplotypes + j];
        }
    }

    // generate gene sums from previous value
    std::fill(gene_sums_, gene_sums_ + alignment_incidence_->num_genes(), 0.0);
    double genes_total = 0.0;
    for (int i = 0; i < num_transcripts; ++i) {
        gene_sums_[alignment_incidence_->tx_to_gene[i]] += transcript_sums_[i];
        genes_total += transcript_sums_[i];
    }

    // normalize gene_sums_
    for (int i = 0; i < alignment_incidence_->num_genes(); i++) {
        gene_sums_[i] /= genes_total;
    }

    //iterate over each read
    for (int i = 0; i != end; ++i) {
        read_sum = 0.0;

        for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {
            // make sure read_sum_by_gene_ is initialized to zero for any gene that has a hit for this read
            read_sum_by_gene_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]]] = 0.0;
        }

        work_index = 0;

        for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {
            gene_sum_hits_only_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]]] = 0.0;

            start_index = alignment_incidence_->col_ind[j] * num_haplotypes;
            for (int k = 0; k < num_haplotypes; ++k) {
                // initialize all strains at this locus
                if (alignment_incidence_->val[j] & (1 << k)) {
                    working_[work_index++] = previous_[start_index + k];
                    read_sum_by_gene_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]]] += previous_[start_index + k];
                }
                else {
                    working_[work_index++] = 0.0;
                }
            }
        }

        work_index = 0;

        for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {
            for (int k = 0; k < num_haplotypes; ++k) {
                if (alignment_incidence_->val[j] & (1 << k)) {
                    working_[work_index] /= read_sum_by_gene_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]]];
                    working_[work_index] *= gene_sums_[alignment_incidence_->tx_to_gene[alignment_incidence_->col_ind[j]]];

                    if (working_[work_index] != working_[work_index]) {
                        // nan! underflow!

                        // set to zero
                        working_[work_index] = 0.0;

                        // skip this location next time
                        alignment_incidence_->val[j] &= ~(1 << k);
                    }
                }
                read_sum += working_[work_index++];
            }
        }

        work_index = 0;

        for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {
            start_index = alignment_incidence_->col_ind[j] * num_haplotypes;
            for (int k = 0; k < num_haplotypes; ++k) {
                current_[start_index + k] += (working_[work_index++] / read_sum)  * (double)alignment_incidence_->counts[i];
            }
        }

    }
}

void SampleAllelicExpression::updateModel4() {
    std::swap(current_, previous_);

    // clear current_ so we can use it to accumulate sums
    std::fill(current_, current_ + size(), 0.0);

    int start_index;
    int work_index;
    double read_sum;
    auto end = alignment_incidence_->row_ptr.size() - 1;

    //iterate over each read
    for (int i = 0; i != end; ++i) {
        work_index = 0;
        read_sum = 0.0;

        for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {
            start_index = alignment_incidence_->col_ind[j] * num_haplotypes;

            for (int k = 0; k < num_haplotypes; ++k) {
                // initialize all strains at this locus
                if (alignment_incidence_->val[j] & (1 << k)) {
                    working_[work_index++] = previous_[start_index + k];
                    read_sum += previous_[start_index + k];
                }
                else {
                    working_[work_index++] = 0.0;
                }
            }
        }

        work_index = 0;

        for (long j = alignment_incidence_->row_ptr[i]; j < alignment_incidence_->row_ptr[i+1]; ++j) {
            start_index = alignment_incidence_->col_ind[j] * num_haplotypes;
            for (int k = 0; k < num_haplotypes; ++k) {
                current_[start_index + k] += (working_[work_index++] / read_sum)  * (double)alignment_incidence_->counts[i];
            }
        }
    }
}

bool SampleAllelicExpression::converged(double &change, int verbose) {
    change = 0.0;
    double current_sum = 0.0;
    double previous_sum = 0.0;

    for (int i = 0; i < size(); ++i) {
        // change += std::abs(current_[i] - previous_[i]);
        current_sum += current_[i] * alignment_incidence_->transcript_lengths_[i];
        previous_sum += previous_[i] * alignment_incidence_->transcript_lengths_[i];
        change += std::abs(current_[i] - previous_[i]) * alignment_incidence_->transcript_lengths_[i];
    }

    if (verbose) {
        std::cout << "current sum: " << current_sum << ", previous sum: " << previous_sum << std::endl;
    }

    if (change < threshold_) {
        return true;
    }

    return false;
}

void SampleAllelicExpression::saveStackSums(std::string filename_isoform, std::string filename_gene,
                                            int compact_results) {
    std::ofstream outfile_isoform;
    outfile_isoform.open(filename_isoform, std::fstream::app);

    outfile_isoform << "#target_id";

    if (num_haplotypes > 1) {
        for (int i = 0; i < num_haplotypes; i++) {
            outfile_isoform << '\t' << alignment_incidence_->haplotype_names[i];
        }
    }

    outfile_isoform << '\t' << "total" << std::endl;

    // use 4 fixed decimal places for output
    outfile_isoform << std::fixed;
    outfile_isoform << std::setprecision(6);

    double sum;
    std::ostringstream line;
    line << std::fixed;
    line << std::setprecision(6);
    double *gene_sums;

    if (alignment_incidence_->has_gene_mappings_) {
        gene_sums = new double[num_haplotypes * alignment_incidence_->num_genes()];
        std::fill(gene_sums, gene_sums + alignment_incidence_->num_genes() * num_haplotypes, 0.0);
    }

    for (int i = 0; i < num_transcripts; i++) {
        if (num_haplotypes == 1) {
            if (alignment_incidence_->has_gene_mappings_) {
                gene_sums[alignment_incidence_->tx_to_gene[i]] += current_[i];
            }

            if (!(compact_results && current_[i] == 0.0)) {
                outfile_isoform << alignment_incidence_->transcript_names[i] << '\t' << current_[i] << std::endl;
            }
        } else {
            sum = 0.0;
            line.str(std::string());

            for (int j = 0; j < num_haplotypes;  j++) {
                if (alignment_incidence_->has_gene_mappings_) {
                    gene_sums[alignment_incidence_->tx_to_gene[i] * num_haplotypes + j] += current_[i * num_haplotypes + j];
                }

                line << current_[i * num_haplotypes + j];
                sum += current_[i * num_haplotypes + j];
                line << '\t';
            }

            if (!(compact_results && sum == 0.0)) {
                outfile_isoform << alignment_incidence_->transcript_names[i] << '\t' << line.str() << sum << std::endl;
            }
        }
    }

    if (alignment_incidence_->has_gene_mappings_) {
        std::ofstream outfile_gene;
        outfile_gene.open(filename_gene, std::fstream::app);

        outfile_gene << "#target_id";

        if (num_haplotypes > 1) {
            for (int i = 0; i < num_haplotypes; i++) {
                outfile_gene << '\t' << alignment_incidence_->haplotype_names[i];
            }
        }

        outfile_gene << '\t' << "total" << std::endl;

        // use 4 fixed decimal places for output
        outfile_gene << std::fixed;
        outfile_gene << std::setprecision(6);

        for (int i = 0; i < alignment_incidence_->num_genes(); i++) {
            if (num_haplotypes == 1) {
                if (!(compact_results && current_[i] == 0.0)) {
                    outfile_gene << alignment_incidence_->gene_names[i] << '\t' << gene_sums[i] << std::endl;
                }
            } else {
                sum = 0.0;
                line.str(std::string());

                for (int j = 0; j < num_haplotypes; j++) {
                    line << gene_sums[i * num_haplotypes + j];
                    sum += gene_sums[i * num_haplotypes + j];
                    line << '\t';
                }

                if (!(compact_results && sum == 0.0)) {
                    outfile_gene << alignment_incidence_->gene_names[i] << '\t' << line.str() << sum << std::endl;
                }
            }
        }
    }
}

void SampleAllelicExpression::saveStackSums(std::string filename_isoform, std::string filename_gene,
                                            std::string sample_name, bool output_header, int compact_results) {
    std::ofstream outfile_isoform;
    outfile_isoform.open(filename_isoform, std::fstream::app);

    if (output_header) {
        outfile_isoform << "#target_id";

        if (num_haplotypes > 1) {
            for (int i = 0; i < num_haplotypes; i++) {
                outfile_isoform << '\t' << alignment_incidence_->haplotype_names[i];
            }
        }

        outfile_isoform << '\t' << "total" << std::endl;
    }

    outfile_isoform << "#sample_id: " << sample_name << std::endl;

    // use 6 fixed decimal places for output
    outfile_isoform << std::fixed;
    outfile_isoform << std::setprecision(6);

    double sum;
    std::ostringstream line;
    line << std::fixed;
    line << std::setprecision(6);
    double *gene_sums;

    if (alignment_incidence_->has_gene_mappings_) {
        gene_sums = new double[num_haplotypes * alignment_incidence_->num_genes()];
        std::fill(gene_sums, gene_sums + alignment_incidence_->num_genes() * num_haplotypes, 0.0);
    }

    for (int i = 0; i < num_transcripts; i++) {
        if (num_haplotypes == 1) {
            if (alignment_incidence_->has_gene_mappings_) {
                gene_sums[alignment_incidence_->tx_to_gene[i]] += current_[i];
            }

            if (!(compact_results && current_[i] == 0.0)) {
                outfile_isoform << alignment_incidence_->transcript_names[i] << '\t' << current_[i] << std::endl;
            }
        } else {
            sum = 0.0;
            line.str(std::string());

            //outfile_isoform << "----\nTRANSCRIPT: " << alignment_incidence_->transcript_names[i] << std::endl;

            for (int j = 0; j < num_haplotypes;  j++) {
                if (alignment_incidence_->has_gene_mappings_) {
                    //outfile_isoform << "HAPLOTYPE: " << alignment_incidence_->haplotype_names[j] << std::endl;
                    //outfile_isoform << "\tVAL: " << current_[i * num_haplotypes + j] << std::endl;
                    //outfile_isoform << "\tTOTAL WAS: " << gene_sums[alignment_incidence_->tx_to_gene[i] * num_haplotypes + j] << std::endl;
                    gene_sums[alignment_incidence_->tx_to_gene[i] * num_haplotypes + j] += current_[i * num_haplotypes + j];
                    //outfile_isoform << "\tNOW IS: " << gene_sums[alignment_incidence_->tx_to_gene[i] * num_haplotypes + j] << std::endl;
                }

                line << current_[i * num_haplotypes + j];
                sum += current_[i * num_haplotypes + j];
                line << '\t';
            }

            if (!(compact_results && sum == 0.0)) {
                outfile_isoform << alignment_incidence_->transcript_names[i] << '\t' << line.str() << sum << std::endl;
            }
        }
    }

    if (alignment_incidence_->has_gene_mappings_) {
        std::ofstream outfile_gene;
        outfile_gene.open(filename_gene, std::fstream::app);

        if (output_header) {
            outfile_gene << "#target_id";

            if (num_haplotypes > 1) {
                for (int i = 0; i < num_haplotypes; i++) {
                    outfile_gene << '\t' << alignment_incidence_->haplotype_names[i];
                }
            }

            outfile_gene << '\t' << "total" << std::endl;
        }

        outfile_gene << "#sample_id: " << sample_name << std::endl;

        // use 6 fixed decimal places for output
        outfile_gene << std::fixed;
        outfile_gene << std::setprecision(6);

        for (int i = 0; i < alignment_incidence_->num_genes(); i++) {
            if (num_haplotypes == 1) {
                if (!(compact_results && gene_sums[i] == 0.0)) {
                    outfile_gene << alignment_incidence_->gene_names[i] << '\t' << gene_sums[i] << std::endl;
                }
            } else {
                sum = 0.0;
                line.str(std::string());

                for (int j = 0; j < num_haplotypes; j++) {
                    line << gene_sums[i * num_haplotypes + j];
                    sum += gene_sums[i * num_haplotypes + j];
                    line << '\t';
                }

                if (!(compact_results && sum == 0.0)) {
                    outfile_gene << alignment_incidence_->gene_names[i] << '\t' << line.str() << sum << std::endl;
                }
            }
        }
    }
}

void SampleAllelicExpression::applyTranscriptLength(bool in_tpm) {

    if (alignment_incidence_->transcript_lengths_.size() == 0) {
        // didn't load transcript lengths, don't do anything
        return;
    }

    if (in_tpm) {
        double sum = 0.0;
        for (int i = 0; i < num_transcripts; i++) {
            for (int j = 0; j < num_haplotypes;  j++) {
                current_[i * num_haplotypes + j] /= alignment_incidence_->transcript_lengths_[i * num_haplotypes + j];
                sum += current_[i * num_haplotypes + j];
            }
        }
        for (int i = 0; i < num_transcripts; i++) {
            for (int j = 0; j < num_haplotypes; j++) {
                current_[i * num_haplotypes + j] *= 1000000.0 / sum;
            }
        }
    } else {
        for (int i = 0; i < num_transcripts; i++) {
            for (int j = 0; j < num_haplotypes;  j++) {
                current_[i * num_haplotypes + j] /= alignment_incidence_->transcript_lengths_[i * num_haplotypes + j];
            }
        }
    }

}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

var _YearButton = require('./YearButton');

var _YearButton2 = _interopRequireDefault(_YearButton);

var _dateUtils = require('./dateUtils');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var CalendarYear = function (_React$Component) {
  _inherits(CalendarYear, _React$Component);

  function CalendarYear() {
    var _Object$getPrototypeO;

    var _temp, _this, _ret;

    _classCallCheck(this, CalendarYear);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(CalendarYear)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.handleTouchTap = function (event, year) {
      if (_this.props.onYearTouchTap) _this.props.onYearTouchTap(event, year);
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(CalendarYear, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.scrollToSelectedYear();
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate() {
      this.scrollToSelectedYear();
    }
  }, {
    key: 'getYears',
    value: function getYears() {
      var minYear = this.props.minDate.getFullYear();
      var maxYear = this.props.maxDate.getFullYear();

      var years = [];
      var dateCheck = (0, _dateUtils.cloneDate)(this.props.selectedDate);
      for (var year = minYear; year <= maxYear; year++) {
        dateCheck.setFullYear(year);
        var selected = this.props.selectedDate.getFullYear() === year;
        var selectedProps = {};
        if (selected) {
          selectedProps = { ref: 'selectedYearButton' };
        }

        var yearButton = _react2.default.createElement(_YearButton2.default, _extends({
          key: 'yb' + year,
          year: year,
          onTouchTap: this.handleTouchTap,
          selected: selected
        }, selectedProps));

        years.push(yearButton);
      }

      return years;
    }
  }, {
    key: 'scrollToSelectedYear',
    value: function scrollToSelectedYear() {
      if (this.refs.selectedYearButton === undefined) return;

      var container = _reactDom2.default.findDOMNode(this);
      var yearButtonNode = _reactDom2.default.findDOMNode(this.refs.selectedYearButton);

      var containerHeight = container.clientHeight;
      var yearButtonNodeHeight = yearButtonNode.clientHeight || 32;

      var scrollYOffset = yearButtonNode.offsetTop + yearButtonNodeHeight / 2 - containerHeight / 2;
      container.scrollTop = scrollYOffset;
    }
  }, {
    key: 'render',
    value: function render() {
      var years = this.getYears();
      var backgroundColor = this.context.muiTheme.datePicker.calendarYearBackgroundColor;
      var styles = {
        position: 'relative',
        height: 'inherit',
        lineHeight: '36px',
        textAlign: 'center',
        padding: '8px 14px 0 14px',
        backgroundColor: backgroundColor,
        overflowX: 'hidden',
        overflowY: 'scroll'
      };

      return _react2.default.createElement(
        'div',
        { style: styles },
        years
      );
    }
  }]);

  return CalendarYear;
}(_react2.default.Component);

CalendarYear.propTypes = {
  displayDate: _react2.default.PropTypes.object.isRequired,
  maxDate: _react2.default.PropTypes.object,
  minDate: _react2.default.PropTypes.object,
  onYearTouchTap: _react2.default.PropTypes.func,
  selectedDate: _react2.default.PropTypes.object.isRequired
};
CalendarYear.contextTypes = {
  muiTheme: _react2.default.PropTypes.object.isRequired
};
exports.default = CalendarYear;


text:
using Shop.Core.Entites;
using Shop.Core.Interfaces;

namespace Shop.Infrastructure.Data.Mappers
{
    public class BasketMapper : IMapToExisting<Basket, Basket>
    {
        public bool Map(Basket source, Basket target)
        {
            target.MarkClean();

            target.ShippingMethod = source.ShippingMethod;

            if (target.IsDirty)
                target.MarkUpdated();

            return target.IsDirty;
        }
    }
}


text:
#include "androidjniinput.h"
#include "androidjnimain.h"
#include "qandroidplatformintegration.h"

#include <qpa/qwindowsysteminterface.h>
#include <QTouchEvent>
#include <QPointer>

#include <QDebug>

using namespace QtAndroid;

namespace QtAndroidInput
{
    static jmethodID m_showSoftwareKeyboardMethodID = 0;
    static jmethodID m_resetSoftwareKeyboardMethodID = 0;
    static jmethodID m_hideSoftwareKeyboardMethodID = 0;
    static jmethodID m_isSoftwareKeyboardVisibleMethodID = 0;
    static jmethodID m_updateSelectionMethodID = 0;

    static bool m_ignoreMouseEvents = false;

    static QList<QWindowSystemInterface::TouchPoint> m_touchPoints;

    static QPointer<QWindow> m_mouseGrabber;

    void updateSelection(int selStart, int selEnd, int candidatesStart, int candidatesEnd)
    {
        AttachedJNIEnv env;
        if (!env.jniEnv)
            return;

#ifdef QT_DEBUG_ANDROID_IM_PROTOCOL
        qDebug() << ">>> UPDATESELECTION" << selStart << selEnd << candidatesStart << candidatesEnd;
#endif
        env.jniEnv->CallStaticVoidMethod(applicationClass(), m_updateSelectionMethodID,
                                         selStart, selEnd, candidatesStart, candidatesEnd);
    }

    void showSoftwareKeyboard(int left, int top, int width, int height, int inputHints)
    {
        AttachedJNIEnv env;
        if (!env.jniEnv)
            return;

        env.jniEnv->CallStaticVoidMethod(applicationClass(),
                                         m_showSoftwareKeyboardMethodID,
                                         left,
                                         top,
                                         width,
                                         height,
                                         inputHints);
#ifdef QT_DEBUG_ANDROID_IM_PROTOCOL
        qDebug() << "@@@ SHOWSOFTWAREKEYBOARD" << left << top << width << height << inputHints;
#endif
    }

    void resetSoftwareKeyboard()
    {
        AttachedJNIEnv env;
        if (!env.jniEnv)
            return;

        env.jniEnv->CallStaticVoidMethod(applicationClass(), m_resetSoftwareKeyboardMethodID);
#ifdef QT_DEBUG_ANDROID_IM_PROTOCOL
        qDebug() << "@@@ RESETSOFTWAREKEYBOARD";
#endif
    }

    void hideSoftwareKeyboard()
    {
        AttachedJNIEnv env;
        if (!env.jniEnv)
            return;

        env.jniEnv->CallStaticVoidMethod(applicationClass(), m_hideSoftwareKeyboardMethodID);
#ifdef QT_DEBUG_ANDROID_IM_PROTOCOL
        qDebug() << "@@@ HIDESOFTWAREKEYBOARD";
#endif
    }

    bool isSoftwareKeyboardVisible()
    {
        AttachedJNIEnv env;
        if (!env.jniEnv)
            return false;

        bool visibility = env.jniEnv->CallStaticBooleanMethod(applicationClass(), m_isSoftwareKeyboardVisibleMethodID);
#ifdef QT_DEBUG_ANDROID_IM_PROTOCOL
        qDebug() << "@@@ ISSOFTWAREKEYBOARDVISIBLE" << visibility;
#endif
        return visibility;
    }

    static void mouseDown(JNIEnv */*env*/, jobject /*thiz*/, jint /*winId*/, jint x, jint y)
    {
        if (m_ignoreMouseEvents)
            return;

        QPoint globalPos(x,y);
        QWindow *tlw = topLevelWindowAt(globalPos);
        m_mouseGrabber = tlw;
        QPoint localPos = tlw ? (globalPos - tlw->position()) : globalPos;
        QWindowSystemInterface::handleMouseEvent(tlw,
                                                 localPos,
                                                 globalPos,
                                                 Qt::MouseButtons(Qt::LeftButton));
    }

    static void mouseUp(JNIEnv */*env*/, jobject /*thiz*/, jint /*winId*/, jint x, jint y)
    {
        QPoint globalPos(x,y);
        QWindow *tlw = m_mouseGrabber.data();
        if (!tlw)
            tlw = topLevelWindowAt(globalPos);
        QPoint localPos = tlw ? (globalPos -tlw->position()) : globalPos;
        QWindowSystemInterface::handleMouseEvent(tlw, localPos, globalPos
                                                , Qt::MouseButtons(Qt::NoButton));
        m_ignoreMouseEvents = false;
        m_mouseGrabber = 0;
    }

    static void mouseMove(JNIEnv */*env*/, jobject /*thiz*/, jint /*winId*/, jint x, jint y)
    {

        if (m_ignoreMouseEvents)
            return;

        QPoint globalPos(x,y);
        QWindow *tlw = m_mouseGrabber.data();
        if (!tlw)
            tlw = topLevelWindowAt(globalPos);
        QPoint localPos = tlw ? (globalPos-tlw->position()) : globalPos;
        QWindowSystemInterface::handleMouseEvent(tlw,
                                                 localPos,
                                                 globalPos,
                                                 Qt::MouseButtons(Qt::LeftButton));
    }

    static void longPress(JNIEnv */*env*/, jobject /*thiz*/, jint /*winId*/, jint x, jint y)
    {
        //### TODO: add proper API for Qt 5.2
        static bool rightMouseFromLongPress = qgetenv("QT_NECESSITAS_COMPATIBILITY_LONG_PRESS").toInt();
        if (!rightMouseFromLongPress)
            return;
        m_ignoreMouseEvents = true;
        QPoint globalPos(x,y);
        QWindow *tlw = topLevelWindowAt(globalPos);
        QPoint localPos = tlw ? (globalPos-tlw->position()) : globalPos;

        // Release left button
        QWindowSystemInterface::handleMouseEvent(tlw,
                                                 localPos,
                                                 globalPos,
                                                 Qt::MouseButtons(Qt::NoButton));

        // Press right button
        QWindowSystemInterface::handleMouseEvent(tlw,
                                                 localPos,
                                                 globalPos,
                                                 Qt::MouseButtons(Qt::RightButton));
    }

    static void touchBegin(JNIEnv */*env*/, jobject /*thiz*/, jint /*winId*/)
    {
        m_touchPoints.clear();
    }

    static void touchAdd(JNIEnv */*env*/, jobject /*thiz*/, jint /*winId*/, jint id, jint action, jboolean /*primary*/, jint x, jint y, jfloat size, jfloat pressure)
    {
        Qt::TouchPointState state = Qt::TouchPointStationary;
        switch (action) {
        case 0:
            state = Qt::TouchPointPressed;
            break;
        case 1:
            state = Qt::TouchPointMoved;
            break;
        case 2:
            state = Qt::TouchPointStationary;
            break;
        case 3:
            state = Qt::TouchPointReleased;
            break;
        }

        const int dw = desktopWidthPixels();
        const int dh = desktopHeightPixels();
        QWindowSystemInterface::TouchPoint touchPoint;
        touchPoint.id = id;
        touchPoint.pressure = pressure;
        touchPoint.normalPosition = QPointF(double(x / dw), double(y / dh));
        touchPoint.state = state;
        touchPoint.area = QRectF(x - double(dw*size) / 2.0,
                                 y - double(dh*size) / 2.0,
                                 double(dw*size),
                                 double(dh*size));
        m_touchPoints.push_back(touchPoint);
    }

    static void touchEnd(JNIEnv */*env*/, jobject /*thiz*/, jint /*winId*/, jint /*action*/)
    {
        if (m_touchPoints.isEmpty())
            return;

        QAndroidPlatformIntegration *platformIntegration = QtAndroid::androidPlatformIntegration();
        if (!platformIntegration)
            return;

        QTouchDevice *touchDevice = platformIntegration->touchDevice();
        if (touchDevice == 0) {
            touchDevice = new QTouchDevice;
            touchDevice->setType(QTouchDevice::TouchScreen);
            touchDevice->setCapabilities(QTouchDevice::Position
                                         | QTouchDevice::Area
                                         | QTouchDevice::Pressure
                                         | QTouchDevice::NormalizedPosition);
            QWindowSystemInterface::registerTouchDevice(touchDevice);
            platformIntegration->setTouchDevice(touchDevice);
        }

        QWindow *window = QtAndroid::topLevelWindowAt(m_touchPoints.at(0).area.center().toPoint());
        QWindowSystemInterface::handleTouchEvent(window, touchDevice, m_touchPoints);
    }

    static int mapAndroidKey(int key)
    {
        // 0--9        0x00000007 -- 0x00000010
        if (key >= 0x00000007 && key <= 0x00000010)
            return Qt::Key_0 + key - 0x00000007;

        // A--Z        0x0000001d -- 0x00000036
        if (key >= 0x0000001d && key <= 0x00000036)
            return Qt::Key_A + key - 0x0000001d;

        // F1--F12     0x00000083 -- 0x0000008e
        if (key >= 0x00000083 && key <= 0x0000008e)
            return Qt::Key_F1 + key - 0x00000083;

        // NUMPAD_0--NUMPAD_9     0x00000090 -- 0x00000099
        if (key >= 0x00000090 && key <= 0x00000099)
            return Qt::KeypadModifier + Qt::Key_0 + key - 0x00000090;

        // BUTTON_1--KEYCODE_BUTTON_16 0x000000bc -- 0x000000cb

        switch (key) {
        case 0x00000000: // KEYCODE_UNKNOWN
            return Qt::Key_unknown;

        case 0x00000001: // KEYCODE_SOFT_LEFT
            return Qt::Key_Left;

        case 0x00000002: // KEYCODE_SOFT_RIGHT
            return Qt::Key_Right;

        // 0x00000003: // KEYCODE_HOME is never delivered to applications.

        case 0x00000004: // KEYCODE_BACK
            return Qt::Key_Back;

        case 0x00000005: // KEYCODE_CALL
            return Qt::Key_Call;

        case 0x00000006: // KEYCODE_ENDCALL
            return Qt::Key_Hangup;

       // 0--9        0x00000007 -- 0x00000010

        case 0x00000011: // KEYCODE_STAR
            return Qt::Key_Asterisk;

        case 0x00000012: // KEYCODE_POUND
            return Qt::Key_NumberSign;

        case 0x00000013: //KEYCODE_DPAD_UP
            return Qt::Key_Up;

        case 0x00000014: // KEYCODE_DPAD_DOWN
            return Qt::Key_Down;

        case 0x00000015: //KEYCODE_DPAD_LEFT
            return Qt::Key_Left;

        case 0x00000016: //KEYCODE_DPAD_RIGHT
            return Qt::Key_Right;

        case 0x00000017: // KEYCODE_DPAD_CENTER
            return Qt::Key_Enter;

        case 0x00000018: // KEYCODE_VOLUME_UP
            return Qt::Key_VolumeUp;

        case 0x00000019: // KEYCODE_VOLUME_DOWN
            return Qt::Key_VolumeDown;

        case 0x0000001a:
            return Qt::Key_PowerOff;

        case 0x0000001b: // KEYCODE_CAMERA
            return Qt::Key_Camera;

        case 0x0000001c: // KEYCODE_CLEAR
            return Qt::Key_Clear;

        // A--Z        0x0000001d -- 0x00000036

        case 0x00000037: // KEYCODE_COMMA
            return Qt::Key_Comma;

        case 0x00000038: // KEYCODE_PERIOD
            return Qt::Key_Period;

        case 0x00000039: // KEYCODE_ALT_LEFT
        case 0x0000003a: // KEYCODE_ALT_RIGHT
            return Qt::Key_Alt;

        case 0x0000003b: // KEYCODE_SHIFT_LEFT
        case 0x0000003c: // KEYCODE_SHIFT_RIGHT
            return Qt::Key_Shift;

        case 0x0000003d: // KEYCODE_TAB
            return Qt::Key_Tab;

        case 0x0000003e: // KEYCODE_SPACE
            return Qt::Key_Space;

        case 0x0000003f: // KEYCODE_SYM
            return Qt::Key_Meta;

        case 0x00000040: // KEYCODE_EXPLORER
            return Qt::Key_Explorer;

        case 0x00000041: //KEYCODE_ENVELOPE
            return Qt::Key_LaunchMail;

        case 0x00000042: // KEYCODE_ENTER
            return Qt::Key_Return;

        case 0x00000043: // KEYCODE_DEL
            return Qt::Key_Backspace;

        case 0x00000044: // KEYCODE_GRAVE
            return Qt::Key_QuoteLeft;

        case 0x00000045: // KEYCODE_MINUS
            return Qt::Key_Minus;

        case 0x00000046: // KEYCODE_EQUALS
            return Qt::Key_Equal;

        case 0x00000047: // KEYCODE_LEFT_BRACKET
            return Qt::Key_BracketLeft;

        case 0x00000048: // KEYCODE_RIGHT_BRACKET
            return Qt::Key_BracketRight;

        case 0x00000049: // KEYCODE_BACKSLASH
            return Qt::Key_Backslash;

        case 0x0000004a: // KEYCODE_SEMICOLON
            return Qt::Key_Semicolon;

        case 0x0000004b: // KEYCODE_APOSTROPHE
            return Qt::Key_Apostrophe;

        case 0x0000004c: // KEYCODE_SLASH
            return Qt::Key_Slash;

        case 0x0000004d: // KEYCODE_AT
            return Qt::Key_At;

        case 0x0000004e: // KEYCODE_NUM
            return Qt::Key_Alt;

        case 0x0000004f: // KEYCODE_HEADSETHOOK
            return 0;

        case 0x00000050: // KEYCODE_FOCUS
            return Qt::Key_CameraFocus;

        case 0x00000051: // KEYCODE_PLUS
            return Qt::Key_Plus;

        case 0x00000052: // KEYCODE_MENU
            return Qt::Key_Menu;

        case 0x00000053: // KEYCODE_NOTIFICATION
            return 0;

        case 0x00000054: // KEYCODE_SEARCH
            return Qt::Key_Search;

        case 0x00000055: // KEYCODE_MEDIA_PLAY_PAUSE
            return Qt::Key_MediaPlay;

        case 0x00000056: // KEYCODE_MEDIA_STOP
            return Qt::Key_MediaStop;

        case 0x00000057: // KEYCODE_MEDIA_NEXT
            return Qt::Key_MediaNext;

        case 0x00000058: // KEYCODE_MEDIA_PREVIOUS
            return Qt::Key_MediaPrevious;

        case 0x00000059: // KEYCODE_MEDIA_REWIND
            return Qt::Key_AudioRewind;

        case 0x0000005a: // KEYCODE_MEDIA_FAST_FORWARD
            return Qt::Key_AudioForward;

        case 0x0000005b: // KEYCODE_MUTE
            return Qt::Key_MicMute;

        case 0x0000005c: // KEYCODE_PAGE_UP
            return Qt::Key_PageUp;

        case 0x0000005d: // KEYCODE_PAGE_DOWN
            return Qt::Key_PageDown;

        case 0x0000005e: // KEYCODE_PICTSYMBOLS
            return 0;

        case 0x00000060: // KEYCODE_BUTTON_A
        case 0x00000061: // KEYCODE_BUTTON_B
        case 0x00000062: // KEYCODE_BUTTON_B
        case 0x00000063: // KEYCODE_BUTTON_X
        case 0x00000064: // KEYCODE_BUTTON_Y
        case 0x00000065: // KEYCODE_BUTTON_Z
        case 0x00000066: // KEYCODE_BUTTON_L1
        case 0x00000067: // KEYCODE_BUTTON_R1
        case 0x00000068: // KEYCODE_BUTTON_L2
        case 0x00000069: // KEYCODE_BUTTON_R2
        case 0x0000006a: // KEYCODE_BUTTON_THUMBL
        case 0x0000006b: // KEYCODE_BUTTON_THUMBR
        case 0x0000006c: // KEYCODE_BUTTON_START
        case 0x0000006d: // KEYCODE_BUTTON_SELECT
        case 0x0000006e: // KEYCODE_BUTTON_MODE
            return 0;

        case 0x0000006f: // KEYCODE_ESCAPE
            return Qt::Key_Escape;

        case 0x00000070: // KEYCODE_FORWARD_DEL
            return Qt::Key_Delete;

        case 0x00000071: // KEYCODE_CTRL_LEFT
        case 0x00000072: // KEYCODE_CTRL_RIGHT
            return Qt::Key_Control;

        case 0x00000073: // KEYCODE_CAPS_LOCK
            return Qt::Key_CapsLock;

        case 0x00000074: // KEYCODE_SCROLL_LOCK
            return Qt::Key_ScrollLock;

        case 0x00000075: // KEYCODE_META_LEFT
        case 0x00000076: // KEYCODE_META_RIGHT
            return Qt::Key_Meta;

        case 0x00000077: // KEYCODE_FUNCTION
            return 0;

        case 0x00000078: // KEYCODE_SYSRQ
            return Qt::Key_Print;

        case 0x00000079: // KEYCODE_BREAK
            return Qt::Key_Pause;

        case 0x0000007a: // KEYCODE_MOVE_HOME
            return Qt::Key_Home;

        case 0x0000007b: // KEYCODE_MOVE_END
            return Qt::Key_End;

        case 0x0000007c: // KEYCODE_MOVE_INSERT
            return Qt::Key_Insert;

        case 0x0000007d: // KEYCODE_FORWARD
            return Qt::Key_Forward;

        case 0x0000007e: // KEYCODE_MEDIA_PLAY
            return Qt::Key_MediaPlay;

        case 0x0000007f: // KEYCODE_MEDIA_PAUSE
            return Qt::Key_MediaPause;

        case 0x00000080: // KEYCODE_MEDIA_CLOSE
        case 0x00000081: // KEYCODE_MEDIA_EJECT
            return Qt::Key_Eject;

        case 0x00000082: // KEYCODE_MEDIA_RECORD
            return Qt::Key_MediaRecord;

        // F1--F12     0x00000083 -- 0x0000008e

        case 0x0000008f: // KEYCODE_NUM_LOCK
            return Qt::Key_NumLock;

        // NUMPAD_0--NUMPAD_9     0x00000090 -- 0x00000099

        case 0x0000009a: // KEYCODE_NUMPAD_DIVIDE
            return Qt::KeypadModifier + Qt::Key_Slash;

        case 0x0000009b: // KEYCODE_NUMPAD_MULTIPLY
            return Qt::KeypadModifier + Qt::Key_Asterisk;

        case 0x0000009c: // KEYCODE_NUMPAD_SUBTRACT
            return Qt::KeypadModifier + Qt::Key_Minus;

        case 0x0000009d: // KEYCODE_NUMPAD_ADD
            return Qt::KeypadModifier + Qt::Key_Plus;

        case 0x0000009e: // KEYCODE_NUMPAD_DOT
            return Qt::KeypadModifier + Qt::Key_Period;

        case 0x0000009f: // KEYCODE_NUMPAD_COMMA
            return Qt::KeypadModifier + Qt::Key_Comma;

        case 0x000000a0: // KEYCODE_NUMPAD_ENTER
            return Qt::Key_Enter;

        case 0x000000a1: // KEYCODE_NUMPAD_EQUALS
            return Qt::KeypadModifier + Qt::Key_Equal;

        case 0x000000a2: // KEYCODE_NUMPAD_LEFT_PAREN
            return Qt::Key_ParenLeft;

        case 0x000000a3: // KEYCODE_NUMPAD_RIGHT_PAREN
            return Qt::Key_ParenRight;

        case 0x000000a4: // KEYCODE_VOLUME_MUTE
            return Qt::Key_VolumeMute;

        case 0x000000a5: // KEYCODE_INFO
            return Qt::Key_Info;

        case 0x000000a6: // KEYCODE_CHANNEL_UP
            return Qt::Key_ChannelUp;

        case 0x000000a7: // KEYCODE_CHANNEL_DOWN
            return Qt::Key_ChannelDown;

        case 0x000000a8: // KEYCODE_ZOOM_IN
            return Qt::Key_ZoomIn;

        case 0x000000a9: // KEYCODE_ZOOM_OUT
            return Qt::Key_ZoomOut;

        case 0x000000aa: // KEYCODE_TV
        case 0x000000ab: // KEYCODE_WINDOW
            return 0;

        case 0x000000ac: // KEYCODE_GUIDE
            return Qt::Key_Guide;

        case 0x000000ad: // KEYCODE_DVR
            return 0;

        case 0x000000ae: // KEYCODE_BOOKMARK
            return Qt::Key_AddFavorite;

        case 0x000000af: // KEYCODE_CAPTIONS
            return Qt::Key_Subtitle;

        case 0x000000b0: // KEYCODE_SETTINGS
            return Qt::Key_Settings;

        case 0x000000b1: // KEYCODE_TV_POWER
        case 0x000000b2: // KEYCODE_TV_INPUT
        case 0x000000b3: // KEYCODE_STB_POWER
        case 0x000000b4: // KEYCODE_STB_INPUT
        case 0x000000b5: // KEYCODE_AVR_POWER
        case 0x000000b6: // KEYCODE_AVR_INPUT
            return 0;

        case 0x000000b7: // KEYCODE_PROG_RED
            return Qt::Key_Red;

        case 0x000000b8: // KEYCODE_PROG_GREEN
            return Qt::Key_Green;

        case 0x000000b9: // KEYCODE_PROG_YELLOW
            return Qt::Key_Yellow;

        case 0x000000ba: // KEYCODE_PROG_BLUE
            return Qt::Key_Blue;

        // 0x000000bb: // KEYCODE_APP_SWITCH is not sent by the Android O.S.

        // BUTTON_1--KEYCODE_BUTTON_16 0x000000bc -- 0x000000cb

        case 0x000000cc: // KEYCODE_LANGUAGE_SWITCH
        case 0x000000cd: // KEYCODE_MANNER_MODE do we need such a thing?
        case 0x000000ce: // KEYCODE_3D_MODE
        case 0x000000cf: // KEYCODE_CONTACTS
            return 0;

        case 0x000000d0: // KEYCODE_CALENDAR
            return Qt::Key_Calendar;

        case 0x000000d1: // KEYCODE_MUSIC
            return Qt::Key_Music;

        case 0x000000d2: // KEYCODE_CALCULATOR
            return Qt::Key_Calculator;

        // 0x000000d3 -- 0x000000da some japanese specific keys, someone who understand what is about should check !

        // 0x000000db: // KEYCODE_ASSIST  not delivered to applications.

        case 0x000000dc: // KEYCODE_BRIGHTNESS_DOWN
            return Qt::Key_KeyboardBrightnessDown;

        case 0x000000dd: // KEYCODE_BRIGHTNESS_UP
            return Qt::Key_KeyboardBrightnessUp;

        case 0x000000de: // KEYCODE_MEDIA_AUDIO_TRACK
            return Qt::Key_AudioCycleTrack;

        default:
            qWarning() << "Unhandled key code " << key << "!";
            return 0;
        }
    }

    // maps 0 to the empty string, and anything else to a single-character string
    static inline QString toString(jint unicode)
    {
        return unicode ? QString(QChar(unicode)) : QString();
    }

    static void keyDown(JNIEnv */*env*/, jobject /*thiz*/, jint key, jint unicode, jint modifier)
    {
        Qt::KeyboardModifiers modifiers;
        if (modifier & 1)
            modifiers |= Qt::ShiftModifier;

        if (modifier & 2)
            modifiers |= Qt::AltModifier;

        if (modifier & 4)
            modifiers |= Qt::MetaModifier;

        QWindowSystemInterface::handleKeyEvent(0,
                                               QEvent::KeyPress,
                                               mapAndroidKey(key),
                                               modifiers,
                                               toString(unicode),
                                               false);
    }

    static void keyUp(JNIEnv */*env*/, jobject /*thiz*/, jint key, jint unicode, jint modifier)
    {
        Qt::KeyboardModifiers modifiers;
        if (modifier & 1)
            modifiers |= Qt::ShiftModifier;

        if (modifier & 2)
            modifiers |= Qt::AltModifier;

        if (modifier & 4)
            modifiers |= Qt::MetaModifier;

        QWindowSystemInterface::handleKeyEvent(0,
                                               QEvent::KeyRelease,
                                               mapAndroidKey(key),
                                               modifiers,
                                               toString(unicode),
                                               false);
    }

    static void keyboardVisibilityChanged(JNIEnv */*env*/, jobject /*thiz*/, jboolean /*visibility*/)
    {
        QAndroidInputContext *inputContext = QAndroidInputContext::androidInputContext();
        if (inputContext)
            inputContext->emitInputPanelVisibleChanged();
#ifdef QT_DEBUG_ANDROID_IM_PROTOCOL
        qDebug() << "@@@ KEYBOARDVISIBILITYCHANGED" << inputContext;
#endif
    }

    static JNINativeMethod methods[] = {
        {"touchBegin","(I)V",(void*)touchBegin},
        {"touchAdd","(IIIZIIFF)V",(void*)touchAdd},
        {"touchEnd","(II)V",(void*)touchEnd},
        {"mouseDown", "(III)V", (void *)mouseDown},
        {"mouseUp", "(III)V", (void *)mouseUp},
        {"mouseMove", "(III)V", (void *)mouseMove},
        {"longPress", "(III)V", (void *)longPress},
        {"keyDown", "(III)V", (void *)keyDown},
        {"keyUp", "(III)V", (void *)keyUp},
        {"keyboardVisibilityChanged", "(Z)V", (void *)keyboardVisibilityChanged}
    };

#define GET_AND_CHECK_STATIC_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE) \
    VAR = env->GetStaticMethodID(CLASS, METHOD_NAME, METHOD_SIGNATURE); \
    if (!VAR) { \
        __android_log_print(ANDROID_LOG_FATAL, qtTagText(), methodErrorMsgFmt(), METHOD_NAME, METHOD_SIGNATURE); \
        return false; \
    }

    bool registerNatives(JNIEnv *env)
    {
        jclass appClass = QtAndroid::applicationClass();

        if (env->RegisterNatives(appClass, methods, sizeof(methods) / sizeof(methods[0])) < 0) {
            __android_log_print(ANDROID_LOG_FATAL,"Qt", "RegisterNatives failed");
            return false;
        }

        GET_AND_CHECK_STATIC_METHOD(m_showSoftwareKeyboardMethodID, appClass, "showSoftwareKeyboard", "(IIIII)V");
        GET_AND_CHECK_STATIC_METHOD(m_resetSoftwareKeyboardMethodID, appClass, "resetSoftwareKeyboard", "()V");
        GET_AND_CHECK_STATIC_METHOD(m_hideSoftwareKeyboardMethodID, appClass, "hideSoftwareKeyboard", "()V");
        GET_AND_CHECK_STATIC_METHOD(m_isSoftwareKeyboardVisibleMethodID, appClass, "isSoftwareKeyboardVisible", "()Z");
        GET_AND_CHECK_STATIC_METHOD(m_updateSelectionMethodID, appClass, "updateSelection", "(IIII)V");
        return true;
    }
}


text:
import Ember from 'ember';

import startApp from '../../tests/helpers/start-app';
import { module, test } from 'qunit';

var App;

module('Acceptance - Dummy app index page', {
  setup: function() {
    App = startApp();
  },
  teardown: function() {
    Ember.run(App, 'destroy');
  }
});

test('Load the demo page', function(assert) {
  visit('/');

  andThen(function () {
    assert.ok(true, 'If this is passing, this page has no deprecation warnings');
  });
});


text:
<?php

namespace AppBundle\Form\Transaction;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use LibBundle\Doctrine\EntityRepository;
use LibBundle\Util\ConstantValueList;
use LibBundle\Form\Type\EntityTextType;
use AppBundle\Entity\Master\Account;
use AppBundle\Entity\Transaction\ExpenseDetail;
use AppBundle\Entity\Transaction\ExpenseHeader;
use AppBundle\Entity\Transaction\PurchaseDeliveryOrder;

class ExpenseHeaderType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('transactionDate', DateType::class)
            ->add('objectiveReason')
            ->add('chequeNumber')
            ->add('note')
            ->add('transactionType', ChoiceType::class, array(
                'expanded' => true,
                'choices' => ConstantValueList::get(ExpenseHeader::class, 'TRANSACTION_TYPE'),
                'choices_as_values' => true,
            ))
            ->add('account', EntityType::class, array(
                'class' => Account::class,
                'query_builder' => function (EntityRepository $er) {
                    $qb = $er->createQueryBuilder('u');
                    return $qb->where($qb->expr()->in('IDENTITY(u.accountCategory)', array(10)));
                },
            ))
            ->add('purchaseDeliveryOrder', EntityTextType::class, array('class' => PurchaseDeliveryOrder::class))
            ->add('expenseDetails', CollectionType::class, array(
                'entry_type' => ExpenseDetailType::class,
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
                'prototype_data' => new ExpenseDetail(),
                'label' => false,
            ))
            ->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) use ($options) {
                $expenseHeader = $event->getData();
                $options['service']->initialize($expenseHeader, $options['init']);
            })
            ->addEventListener(FormEvents::SUBMIT, function(FormEvent $event) use ($options) {
                $expenseHeader = $event->getData();
                $options['service']->finalize($expenseHeader);
            })
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => ExpenseHeader::class,
        ));
        $resolver->setRequired(array('service', 'init'));
    }
}