code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
from gettext import gettext as _
ACTIVITY_NAME = _('I know America')
PRESENTATION = [
_('Hello friends...'),
_('...tomorrow I have a\ntest about America...'),
_('...and I know nothing!!!'),
_('...what do I do???'),
_('Can I ask you something?'),
_('Will you help me?')
]
PREFIX = [
_('We have to find'),
_('Now we have to find'),
_('We need to find')
]
SUFIX = [
_('Can you tell me where it is?'),
_('Where is it?'),
_('Can you show me where it is?'),
_('Can you find it?')
]
CORRECT = [
_('Very well!'),
_('Brilliant!'),
_('You found it!'),
_('Yes!')
]
WRONG = [
_('No, that is not correct'),
_('No, it is not there'),
_('No, that seems to be wrong'),
_('That is not correct')
]
BYE_C = [
_("Now I'm ready\nfor tomorrow...\nI'm going to play...\nThanks for your help!"),
_("We made it!\nI'm going to play ball...\nBye and thanks\nfor helping me!"),
_("We did it!\nI'm ready for tomorrow...\nI'm playing a while...\nUntil next time!")
]
BYE_W = [
_("Better luck next time\nI'll play a while...\nThanks!"),
_("The next time will be better\nI'm going to play ball...\nThanks!"),
_("Please try again...\nI'm going to play...\nThanks!")
]
CREDITS = [
_("Author: Alan Aguiar"),
_("Send corrections, comments or suggestions to: alanjas@hotmail.com"),
"",
_("This program is free software developed by the community"),
"",
_("This program is based on 'Conozco Uruguay' (Author: Gabriel Eirea)"),
_("Sounds downloaded from freesound.org: btn117.wav courtesy of junggle."),
_("Font: Share-Regular.ttf of urbanfonts.com")
]
| AlanJAS/iknowAmerica | recursos/comun/datos/commons.py | Python | gpl-3.0 | 1,689 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.pulsiraj.dao.object;
import com.pulsiraj.beans.LegalEntity;
import com.pulsiraj.dao.pattern.GenericDAOImpl;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
*
* @author Dejan
*/
public class LegalEntityDAO extends GenericDAOImpl<LegalEntity> {
public LegalEntityDAO() {
super((Class<LegalEntity>)new LegalEntity().getClass());
}
}
| ZeleEG/diesel2016 | src/main/java/com/pulsiraj/dao/object/LegalEntityDAO.java | Java | gpl-3.0 | 665 |
using System.Collections.Generic;
using JetBrains.Annotations;
using KataPokerHand.Logic.Interfaces.TexasHoldEm.Rules;
namespace KataPokerHand.Logic.Interfaces.TexasHoldEm.Ranking.SubRanking
{
public interface IRankByCardIndex
{
bool HasSingleWinnerAtCardIndex(
int cardIndex,
[NotNull] IPlayerHandInformation[] infos);
IEnumerable<IPlayerHandInformation> RankedByCardIndex(
int cardIndex,
[NotNull] IPlayerHandInformation[] infos);
}
} | tschroedter/csharp_examples | Katas/KataPokerHand/KataPokerHand.Logic.Interfaces/TexasHoldEm/Ranking/SubRanking/IRankByCardIndex.cs | C# | gpl-3.0 | 514 |
/*
# Copyright (C) 2005-2011 MaNGOS <http://www.getmangos.com/>
*
# Copyright (C) 2008-2011 Trinity <http://www.trinitycore.org/>
*
# Copyright (C) 2006-2011 ScriptDev2 <http://www.scriptdev2.com/>
*
# Copyright (C) 2010-2011 DarkmoonCore <http://www.darkmooncore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Boss_the_ravenian
SD%Complete: 100
SDComment:
SDCategory: Scholomance
EndScriptData */
#include "ScriptPCH.h"
#include "scholomance.h"
#define SPELL_TRAMPLE 15550
#define SPELL_CLEAVE 20691
#define SPELL_SUNDERINCLEAVE 25174
#define SPELL_KNOCKAWAY 10101
class boss_the_ravenian : public CreatureScript
{
public:
boss_the_ravenian() : CreatureScript("boss_the_ravenian") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new boss_theravenianAI (pCreature);
}
struct boss_theravenianAI : public ScriptedAI
{
boss_theravenianAI(Creature *c) : ScriptedAI(c) {}
uint32 Trample_Timer;
uint32 Cleave_Timer;
uint32 SunderingCleave_Timer;
uint32 KnockAway_Timer;
bool HasYelled;
void Reset()
{
Trample_Timer = 24000;
Cleave_Timer = 15000;
SunderingCleave_Timer = 40000;
KnockAway_Timer = 32000;
HasYelled = false;
}
void JustDied(Unit * /*killer*/)
{
InstanceScript *pInstance = me->GetInstanceScript();
if (pInstance)
{
pInstance->SetData(DATA_THERAVENIAN_DEATH, 0);
if (pInstance->GetData(TYPE_GANDLING) == IN_PROGRESS)
me->SummonCreature(1853, 180.73f, -9.43856f, 75.507f, 1.61399f, TEMPSUMMON_DEAD_DESPAWN, 0);
}
}
void EnterCombat(Unit * /*who*/)
{
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
//Trample_Timer
if (Trample_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_TRAMPLE);
Trample_Timer = 10000;
} else Trample_Timer -= diff;
//Cleave_Timer
if (Cleave_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_CLEAVE);
Cleave_Timer = 7000;
} else Cleave_Timer -= diff;
//SunderingCleave_Timer
if (SunderingCleave_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_SUNDERINCLEAVE);
SunderingCleave_Timer = 20000;
} else SunderingCleave_Timer -= diff;
//KnockAway_Timer
if (KnockAway_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_KNOCKAWAY);
KnockAway_Timer = 12000;
} else KnockAway_Timer -= diff;
DoMeleeAttackIfReady();
}
};
};
void AddSC_boss_theravenian()
{
new boss_the_ravenian();
} | DarkmoonCore/DarkmoonCore-Cataclysm | src/server/scripts/EasternKingdoms/Scholomance/boss_the_ravenian.cpp | C++ | gpl-3.0 | 3,675 |
/*
* Koekiebox CONFIDENTIAL
*
* [2012] - [2017] Koekiebox (Pty) Ltd
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains the property
* of Koekiebox and its suppliers, if any. The intellectual and
* technical concepts contained herein are proprietary to Koekiebox
* and its suppliers and may be covered by South African and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material is strictly
* forbidden unless prior written permission is obtained from Koekiebox.
*/
package com.fluidbpm.ws.client.v1.sqlutil;
import org.json.JSONObject;
import com.fluidbpm.program.api.vo.form.FormFieldListing;
import com.fluidbpm.ws.client.v1.websocket.AGenericListMessageHandler;
import com.fluidbpm.ws.client.v1.websocket.IMessageReceivedCallback;
import com.fluidbpm.ws.client.v1.websocket.WebSocketClient;
/**
* A Form Listing handler for {@code FormFieldListing}'s.
*
* @author jasonbruwer on 2018/03/01.
* @since 1.1
*/
public class GenericFormFieldListingMessageHandler extends AGenericListMessageHandler<FormFieldListing> {
/**
* Constructor for FormListing callbacks.
*
* @param messageReceivedCallbackParam The callback events.
* @param webSocketClientParam The web-socket client.
* @param compressedResponseParam Compress the SQL Result in Base-64.
*/
public GenericFormFieldListingMessageHandler(
IMessageReceivedCallback<FormFieldListing> messageReceivedCallbackParam,
WebSocketClient webSocketClientParam,
boolean compressedResponseParam
) {
super(messageReceivedCallbackParam, webSocketClientParam, compressedResponseParam);
}
/**
* Constructor for FormFieldListing callbacks.
*
* @param messageReceivedCallbackParam The callback events.
* @param webSocketClientParam The web-socket client.
*/
public GenericFormFieldListingMessageHandler(
IMessageReceivedCallback<FormFieldListing> messageReceivedCallbackParam,
WebSocketClient webSocketClientParam
) {
super(messageReceivedCallbackParam, webSocketClientParam);
}
/**
* New {@code FormFieldListing} by {@code jsonObjectParam}
*
* @param jsonObjectParam The JSON Object to parse.
* @return new {@code FormFieldListing}.
*/
@Override
public FormFieldListing getNewInstanceBy(JSONObject jsonObjectParam) {
return new FormFieldListing(jsonObjectParam);
}
}
| Koekiebox-PTY-LTD/Fluid | fluid-ws-java-client/src/main/java/com/fluidbpm/ws/client/v1/sqlutil/GenericFormFieldListingMessageHandler.java | Java | gpl-3.0 | 2,425 |
from hashlib import sha256
from django.test import Client
from requests.auth import AuthBase
SIG_KEY = "HTTP_X_SIGNATURE"
def _generate_signature(secret, path, post_data):
path = bytes(path, "utf-8")
body = post_data
secret = bytes(secret, "utf-8")
if isinstance(body, str):
body = bytes(body, "utf-8")
return sha256(path + body + secret).hexdigest()
class AliceClient(Client):
"""
Typically, requests need to have a signature added and the Django client
class doesn't exactly make that easy.
"""
SECRET = "alice_client_test_secret"
def generic(self, method, path, data='',
content_type='application/octet-stream', secure=False,
**extra):
# This is the only part that isn't copypasta from Client.post
if SIG_KEY not in extra:
extra[SIG_KEY] = self.sign(path, data)
return Client.generic(
self,
method,
path,
data=data,
content_type=content_type,
secure=secure,
**extra
)
def sign(self, path, post_data):
return _generate_signature(self.SECRET, path, post_data)
class AliceAuthenticator(AuthBase):
"""
Alice authenticator that can be used with `requests`.
>>> from alice.tests.client import AliceAuthenticator
>>> import requests
>>> requests.get('http://localhost:8000/some_path/', auth=AliceAuthenticator('SECRET!!!'))
<Response [200]>
"""
def __init__(self, secret, header='X-Signature'):
super().__init__()
self.secret = secret
self.header = header
def __call__(self, r):
sig = _generate_signature(self.secret, r.path_url, r.body or '')
r.headers[self.header] = sig
return r
| UKTradeInvestment/export-wins-data | alice/tests/client.py | Python | gpl-3.0 | 1,802 |
/*
This file is part of geometry
Copyright (C) 2011 Julien Thevenon ( julien_thevenon at yahoo.fr )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#ifndef _POINT_HPP_
#define _POINT_HPP_
#include <iostream>
namespace geometry
{
template <typename T>
class point;
template <typename T>
std::ostream & operator<<(std::ostream & p_stream, const point<T> & p_point);
template <typename T>
class point
{
friend std::ostream & operator<< <>(std::ostream & p_stream, const point<T> & p_point);
public:
inline point(const T & p_x,const T & p_y);
inline const T & get_x(void)const;
inline const T & get_y(void)const;
inline bool operator<(const point & p2)const;
inline bool operator!=(const point & p2)const;
inline bool operator==(const point & p2)const;
private:
T m_x;
T m_y;
};
//----------------------------------------------------------------------------
template <typename T>
std::ostream & operator<<(std::ostream & p_stream, const point<T> & p_point)
{
p_stream << "(" << p_point.m_x << "," << p_point.m_y << ")" ;
return p_stream;
}
//----------------------------------------------------------------------------
template <typename T>
point<T>::point(const T & p_x,const T & p_y):
m_x(p_x),
m_y(p_y)
{
}
//----------------------------------------------------------------------------
template <typename T>
const T & point<T>::get_x(void)const
{
return m_x;
}
//----------------------------------------------------------------------------
template <typename T>
const T & point<T>::get_y(void)const
{
return m_y;
}
//----------------------------------------------------------------------------
template <typename T>
bool point<T>::operator<(const point & p2)const
{
return ( m_x != p2.m_x ? m_x < p2.m_x : m_y < p2.m_y);
}
//----------------------------------------------------------------------------
template <typename T>
bool point<T>::operator!=(const point & p2)const
{
return m_x != p2.m_x || m_y != p2.m_y;
}
//----------------------------------------------------------------------------
template <typename T>
bool point<T>::operator==(const point & p2)const
{
return m_x == p2.m_x && m_y == p2.m_y;
}
}
#endif /* _POINT_HPP_ */
//EOF
| quicky2000/geometry | include/point.hpp | C++ | gpl-3.0 | 2,916 |
iris.ui(function (self) {
self.settings({
col: null
, row: null
, color: null
});
// var resource = iris.resource(iris.path.resource);
self.create = function() {
self.tmplMode(self.APPEND);
self.tmpl(iris.path.ui.king.html);
};
self.moves = function(p_squareTo) {
var
colIndex = chess.board.COLS.indexOf(self.setting("col"))
, cols = self.setting("col") === "a"
? ["a", "b"]
: self.setting("col") === "h"
? ["g", "h"]
: [chess.board.COLS[colIndex-1], chess.board.COLS[colIndex], chess.board.COLS[colIndex+1]]
, rows = self.setting("row") === 1
? [1, 2]
: self.setting("row") === 8
? [7, 8]
: [self.setting("row")-1, self.setting("row"), self.setting("row")+1]
, squares = []
, square
;
for (var i=0, I=cols.length; i<I; i++) {
for (var j=0, J=rows.length; j<J; j++) {
if (cols[i] !== self.setting("col") || rows[j] !== self.setting("row")) {
square = iris.model(
iris.path.model.square.js
, {
row: rows[j]
, col: cols[i]
}
);
if (!p_squareTo) {
squares.push({
row: rows[j]
, col: cols[i]
});
}
else if (p_squareTo.col === cols[i] && p_squareTo.row === rows[j]) {
squares.push({
row: rows[j]
, col: cols[i]
});
break;
}
}
}
}
return p_squareTo
? squares.length > 0
: squares
;
};
// self.awake = function () {
// };
// self.sleep = function () {
// };
// self.destroy = function () {
// };
},iris.path.ui.king.js);
| IGZOscarArce/chess-challenges | src/iris-front/iris/ui/king.js | JavaScript | gpl-3.0 | 1,575 |
<?php
/**
* @package Bookingforconnector
* @copyright Copyright (c)2006-2016 Ipertrade
* @license GNU General Public License version 3, or later
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
$pathbase = JPATH_BASE . DIRECTORY_SEPARATOR . 'components' . DIRECTORY_SEPARATOR . 'com_bookingforconnector' . DIRECTORY_SEPARATOR;
require_once $pathbase . 'defines.php';
require_once $pathbase . 'helpers/BFCHelper.php';
if(!empty( COM_BOOKINGFORCONNECTOR_CRAWLER )){
$listCrawler = json_decode(COM_BOOKINGFORCONNECTOR_CRAWLER , true);
foreach( $listCrawler as $key=>$crawler){
if (preg_match('/'.$crawler['pattern'].'/', $_SERVER['HTTP_USER_AGENT'])) return;
}
}
$moduleclass_sfx = htmlspecialchars($params->get('moduleclass_sfx'));
$config = JComponentHelper::getParams('com_bookingforconnector');
$XGooglePosDef = htmlspecialchars($config->get('posx', 0));
$YGooglePosDef = htmlspecialchars($config->get('posy', 0));
$startzoom = $config->get('startzoom',14);
$googlemapsapykey = $config->get('googlemapskey','');
$document = JFactory::getDocument();
$language = JFactory::getLanguage()->getTag();
$mainframe = JFactory::getApplication();
$instance['tablistSelected'] = $params->get('tablistSelected');
$instance['blockmonths'] = $params->get('blockmonths');
$instance['blockdays'] = $params->get('blockdays');
$instance['onlystay'] = $params->get('onlystay');
$instance['tabnamebooking'] = $params->get('tabnamebooking');
$instance['tabnameservices'] = $params->get('tabnameservices');
$instance['tabnameactivities'] = $params->get('tabnameactivities');
$instance['tabnameothers'] = $params->get('tabnameothers');
$instance['tabnamecatalog'] = $params->get('tabnamecatalog');
$instance['tabiconbooking'] = $params->get('tabiconbooking');
$instance['tabiconservices'] = $params->get('tabiconservices');
$instance['tabiconactivities'] = $params->get('tabiconactivities');
$instance['tabiconothers'] = $params->get('tabiconothers');
$instance['tabiconrealestate'] = $params->get('tabiconrealestate');
$instance['tabiconcatalog'] = $params->get('tabiconcatalog');
$instance['merchantcategoriesbooking'] = $params->get('merchantcategoriesbooking');
$instance['merchantcategoriesservices'] = $params->get('merchantcategoriesservices');
$instance['merchantcategoriesactivities'] = $params->get('merchantcategoriesactivities');
$instance['merchantcategoriesothers'] = $params->get('merchantcategoriesothers');
$instance['merchantcategoriesrealestate'] = $params->get('merchantcategoriesrealestate');
$instance['unitcategoriesbooking'] = $params->get('unitcategoriesbooking');
$instance['unitcategoriesservices'] = $params->get('unitcategoriesservices');
$instance['unitcategoriesactivities'] = $params->get('unitcategoriesactivities');
$instance['unitcategoriesothers'] = $params->get('unitcategoriesothers');
$instance['unitcategoriesrealestate'] = $params->get('unitcategoriesrealestate');
$instance['availabilitytypesbooking'] = $params->get('availabilitytypesbooking');
$instance['availabilitytypesservices'] = $params->get('availabilitytypesservices');
$instance['availabilitytypesactivities'] = $params->get('availabilitytypesactivities');
$instance['availabilitytypesothers'] = $params->get('availabilitytypesothers');
$instance['itemtypesbooking'] = $params->get('itemtypesbooking');
$instance['itemtypesservices'] = $params->get('itemtypesservices');
$instance['itemtypesactivities'] = $params->get('itemtypesactivities');
$instance['itemtypesothers'] = $params->get('itemtypesothers');
$instance['groupbybooking'] = $params->get('groupbybooking');
$instance['groupbyservices'] = $params->get('groupbyservices');
$instance['groupbyactivities'] = $params->get('groupbyactivities');
$instance['groupbyothers'] = $params->get('groupbyothers');
$instance['showdirection'] = $params->get('showdirection');
$instance['fixedontop'] = $params->get('fixedontop');
$instance['fixedontopcorrection'] = $params->get('fixedontopcorrection');
$instance['fixedonbottom'] = $params->get('fixedonbottom');
$instance['showLocation'] = $params->get('showLocation');
$instance['showMapIcon'] = $params->get('showMapIcon');
$instance['showSearchText'] = $params->get('showSearchText');
$instance['showAccomodations'] = $params->get('showAccomodations');
$instance['showDateRange'] = $params->get('showDateRange');
$instance['showAdult'] = $params->get('showAdult');
$instance['showChildren'] = $params->get('showChildren');
$instance['showSenior'] = $params->get('showSenior');
$instance['showServices'] = $params->get('showServices');
$instance['showOnlineBooking'] = $params->get('showOnlineBooking');
$instance['showMaxPrice'] = $params->get('showMaxPrice');
$instance['showMinFloor'] = $params->get('showMinFloor');
$instance['showContract'] = $params->get('showContract');
$instance['showResource'] = $params->get('showResource');
$instance['showSearchTextOnSell'] = $params->get('showSearchTextOnSell');
$instance['showMapIconOnSell'] = $params->get('showMapIconOnSell');
$instance['showAccomodationsOnSell'] = $params->get('showAccomodationsOnSell');
$instance['showBedRooms'] = $params->get('showBedRooms');
$instance['showRooms'] = $params->get('showRooms');
$instance['showBaths'] = $params->get('showBaths');
$instance['showOnlyNew'] = $params->get('showOnlyNew');
$instance['showServicesList'] = $params->get('showServicesList');
//Load language translation from component
$lang = JFactory::getLanguage();
$lang->load('com_bookingforconnector', $pathbase, 'en-GB', true);
$lang->load('com_bookingforconnector', $pathbase, $lang->getTag(), true);
bfi_load_scripts();
//-----------------------------------------------------------------------------------------
// implementazione css
// per uno style personalizzato usare il seguente file css nella cartella css del template
// "mod_bookingforsearchbymerchanttype.css"
//-----------------------------------------------------------------------------------------
//JHtml::_('jquery.framework');
//JHTML::script('//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js');
//
//JHTML::stylesheet('components/com_bookingforconnector/assets/css/jquery.validate.css');
//JHTML::stylesheet('components/com_bookingforconnector/assets/jquery-ui/themes/smoothness/jquery-ui.min.css');
//JHTML::stylesheet('components/com_bookingforconnector/assets/css/font-awesome.min.css');
//JHTML::stylesheet('components/com_bookingforconnector/assets/css/magnific-popup.css');
//JHTML::stylesheet('components/com_bookingforconnector/assets/js/webui-popover/jquery.webui-popover.min.css');
//JHTML::stylesheet('components/com_bookingforconnector/assets/css/bookingfor.css');
//
//JHTML::script('components/com_bookingforconnector/assets/js/jquery.blockUI.js');
//JHTML::script('components/com_bookingforconnector/assets/js/jquery.form.js');
//JHtml::script('components/com_bookingforconnector/assets/js/jquery-validation/jquery.validate.min.js');
//JHtml::script('components/com_bookingforconnector/assets/js/jquery-validation/additional-methods.min.js');
//JHtml::script('components/com_bookingforconnector/assets/js/jquery.validate.additional-custom-methods.js');
//JHtml::script('components/com_bookingforconnector/assets/js/jquery.magnific-popup.min.js');
//JHtml::script('components/com_bookingforconnector/assets/js/webui-popover/jquery.webui-popover.min.js');
//JHtml::script('components/com_bookingforconnector/assets/js/jquery.shorten.js');
//JHtml::script('components/com_bookingforconnector/assets/js/bfi.js');
//JHtml::script('components/com_bookingforconnector/assets/js/bfisearchonmap.js');
//JHtml::script('components/com_bookingforconnector/assets/js/bfi_calendar.js');
//if(substr($language,0,2)!='en'){
// JHtml::script('//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/i18n/datepicker-' . substr($language,0,2) . '.min.js?ver=1.11.4');
//}
// if($params->get("type")=='multi'){
// require JModuleHelper::getLayoutPath('mod_bookingfor', $params->get('layout', 'multi'));
// }elseif($params->get("type")=='mono'){
// require JModuleHelper::getLayoutPath('mod_bookingfor', $params->get('layout', 'mono'));
// }else{
// require JModuleHelper::getLayoutPath('mod_bookingfor', $params->get('layout', 'default'));
require JModuleHelper::getLayoutPath('mod_bookingforsearch');
//}
| Bookingfor/joomla | pkg_bookingforconnector/packages/mod_bookingforsearch/mod_bookingforsearch.php | PHP | gpl-3.0 | 8,565 |
package MMC.neocraft.container;
import MMC.neocraft.NeoCraftAchievement;
import MMC.neocraft.item.NCitem;
import MMC.neocraft.recipe.SteeperRecipes;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
public class SlotSteeper extends NCslot
{
EntityPlayer player;
private int expAmount;
public SlotSteeper(EntityPlayer player, IInventory inv, int par1, int par2, int par3)
{
super(inv, par1, par2, par3);
this.player = player;
}
@Override public boolean isItemValid(ItemStack par1ItemStack) { return false; }
@Override public ItemStack decrStackSize(int par1)
{
if (this.getHasStack()) { this.expAmount += Math.min(par1, this.getStack().stackSize); }
return super.decrStackSize(par1);
}
@Override public void onPickupFromSlot(EntityPlayer par1EntityPlayer, ItemStack par2ItemStack)
{
this.onCrafting(par2ItemStack);
super.onPickupFromSlot(par1EntityPlayer, par2ItemStack);
}
@Override protected void onCrafting(ItemStack par1ItemStack, int par2)
{
this.expAmount += par2;
this.onCrafting(par1ItemStack);
}
@Override protected void onCrafting(ItemStack par1ItemStack)
{
par1ItemStack.onCrafting(this.player.worldObj, this.player, this.expAmount);
if (!this.player.worldObj.isRemote)
{
int multiple = this.expAmount;
float exp = SteeperRecipes.steeping().getExperience(par1ItemStack);
int j;
if (exp == 0.0F) { multiple = 0; }
else if (exp < 1.0F)
{
j = MathHelper.floor_float((float)multiple * exp);
if (j < MathHelper.ceiling_float_int((float)multiple * exp) && (float)Math.random() < (float)multiple * exp - (float)j) { ++j; }
multiple = j;
}
while (multiple > 0)
{
j = EntityXPOrb.getXPSplit(multiple);
multiple -= j;
this.player.worldObj.spawnEntityInWorld(new EntityXPOrb(this.player.worldObj, this.player.posX, this.player.posY + 0.5D, this.player.posZ + 0.5D, j));
}
}
this.expAmount = 0;
if (par1ItemStack.itemID == NCitem.teaOrange.itemID)
{
this.player.addStat(NeoCraftAchievement.teaAchieve, 1);
}
}
}
| scott181182/NeoCraft | NeoCraft_common/MMC/neocraft/container/SlotSteeper.java | Java | gpl-3.0 | 2,487 |
<?php
/**
* Special page which uses an HTMLForm to handle processing.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup SpecialPage
*/
/**
* Special page which uses an HTMLForm to handle processing. This is mostly a
* clone of FormAction. More special pages should be built this way; maybe this could be
* a new structure for SpecialPages.
*
* @ingroup SpecialPage
*/
abstract class FormSpecialPage extends SpecialPage {
/**
* The sub-page of the special page.
* @var string|null
*/
protected $par = null;
/**
* @var array|null POST data preserved across re-authentication
* @since 1.32
*/
protected $reauthPostData = null;
/**
* Get an HTMLForm descriptor array
* @return array
*/
abstract protected function getFormFields();
/**
* Add pre-text to the form
* @return string HTML which will be sent to $form->addPreText()
*/
protected function preText() {
return '';
}
/**
* Add post-text to the form
* @return string HTML which will be sent to $form->addPostText()
*/
protected function postText() {
return '';
}
/**
* Play with the HTMLForm if you need to more substantially
* @param HTMLForm $form
*/
protected function alterForm( HTMLForm $form ) {
}
/**
* Get message prefix for HTMLForm
*
* @since 1.21
* @return string
*/
protected function getMessagePrefix() {
return strtolower( $this->getName() );
}
/**
* Get display format for the form. See HTMLForm documentation for available values.
*
* @since 1.25
* @return string
*/
protected function getDisplayFormat() {
return 'table';
}
/**
* Get the HTMLForm to control behavior
* @return HTMLForm|null
*/
protected function getForm() {
$context = $this->getContext();
$onSubmit = [ $this, 'onSubmit' ];
if ( $this->reauthPostData ) {
// Restore POST data
$context = new DerivativeContext( $context );
$oldRequest = $this->getRequest();
$context->setRequest( new DerivativeRequest(
$oldRequest, $this->reauthPostData + $oldRequest->getQueryValues(), true
) );
// But don't treat it as a "real" submission just in case of some
// crazy kind of CSRF.
$onSubmit = function () {
return false;
};
}
$form = HTMLForm::factory(
$this->getDisplayFormat(),
$this->getFormFields(),
$context,
$this->getMessagePrefix()
);
$form->setSubmitCallback( $onSubmit );
if ( $this->getDisplayFormat() !== 'ooui' ) {
// No legend and wrapper by default in OOUI forms, but can be set manually
// from alterForm()
$form->setWrapperLegendMsg( $this->getMessagePrefix() . '-legend' );
}
$headerMsg = $this->msg( $this->getMessagePrefix() . '-text' );
if ( !$headerMsg->isDisabled() ) {
$form->addHeaderText( $headerMsg->parseAsBlock() );
}
$form->addPreText( $this->preText() );
$form->addPostText( $this->postText() );
$this->alterForm( $form );
if ( $form->getMethod() == 'post' ) {
// Retain query parameters (uselang etc) on POST requests
$params = array_diff_key(
$this->getRequest()->getQueryValues(), [ 'title' => null ] );
$form->addHiddenField( 'redirectparams', wfArrayToCgi( $params ) );
}
// Give hooks a chance to alter the form, adding extra fields or text etc
Hooks::run( 'SpecialPageBeforeFormDisplay', [ $this->getName(), &$form ] );
return $form;
}
/**
* Process the form on POST submission.
* @param array $data
* @param HTMLForm $form
* @return bool|string|array|Status As documented for HTMLForm::trySubmit.
*/
abstract public function onSubmit( array $data /* $form = null */ );
/**
* Do something exciting on successful processing of the form, most likely to show a
* confirmation message
* @since 1.22 Default is to do nothing
*/
public function onSuccess() {
}
/**
* Basic SpecialPage workflow: get a form, send it to the user; get some data back,
*
* @param string|null $par Subpage string if one was specified
*/
public function execute( $par ) {
$this->setParameter( $par );
$this->setHeaders();
// This will throw exceptions if there's a problem
$this->checkExecutePermissions( $this->getUser() );
$securityLevel = $this->getLoginSecurityLevel();
if ( $securityLevel !== false && !$this->checkLoginSecurityLevel( $securityLevel ) ) {
return;
}
$form = $this->getForm();
if ( $form->show() ) {
$this->onSuccess();
}
}
/**
* Maybe do something interesting with the subpage parameter
* @param string|null $par
*/
protected function setParameter( $par ) {
$this->par = $par;
}
/**
* Called from execute() to check if the given user can perform this action.
* Failures here must throw subclasses of ErrorPageError.
* @param User $user
* @throws UserBlockedError
*/
protected function checkExecutePermissions( User $user ) {
$this->checkPermissions();
if ( $this->requiresUnblock() ) {
$block = $user->getBlock();
if ( $block && $block->isSitewide() ) {
throw new UserBlockedError( $block );
}
}
if ( $this->requiresWrite() ) {
$this->checkReadOnly();
}
}
/**
* Whether this action requires the wiki not to be locked
* @return bool
*/
public function requiresWrite() {
return true;
}
/**
* Whether this action cannot be executed by a blocked user
* @return bool
*/
public function requiresUnblock() {
return true;
}
/**
* Preserve POST data across reauthentication
*
* @since 1.32
* @param array $data
*/
protected function setReauthPostData( array $data ) {
$this->reauthPostData = $data;
}
}
| kylethayer/bioladder | wiki/includes/specialpage/FormSpecialPage.php | PHP | gpl-3.0 | 6,274 |
using NMoneys;
namespace polymer.api.servicestack.Serialization.NMoneys
{
internal class DefaultSurrogate : ISurrogate
{
public DefaultSurrogate(Money from)
{
Amount = from.Amount;
Currency = from.CurrencyCode;
}
public decimal Amount { get; set; }
public CurrencyIsoCode Currency { get; set; }
public Money ToMoney()
{
return new Money(Amount, Currency);
}
}
} | BrittonDigitalMedia/polymer | src/polymer.api.servicestack/Serialization/NMoneys/DefaultSurrogate.cs | C# | gpl-3.0 | 392 |
########################################################################
# File : PilotStatusAgent.py
# Author : Stuart Paterson
########################################################################
""" The Pilot Status Agent updates the status of the pilot jobs in the
PilotAgents database.
"""
__RCSID__ = "$Id$"
from DIRAC import S_OK, S_ERROR, gConfig
from DIRAC.Core.Base.AgentModule import AgentModule
from DIRAC.Core.Utilities import Time
from DIRAC.ConfigurationSystem.Client.Helpers import Registry
from DIRAC.Core.Utilities.SiteCEMapping import getSiteForCE
from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin
from DIRAC.AccountingSystem.Client.Types.Pilot import Pilot as PilotAccounting
from DIRAC.AccountingSystem.Client.DataStoreClient import gDataStoreClient
from DIRAC.WorkloadManagementSystem.Client.PilotManagerClient import PilotManagerClient
from DIRAC.WorkloadManagementSystem.DB.PilotAgentsDB import PilotAgentsDB
from DIRAC.WorkloadManagementSystem.DB.JobDB import JobDB
MAX_JOBS_QUERY = 10
MAX_WAITING_STATE_LENGTH = 3
class PilotStatusAgent(AgentModule):
"""
The specific agents must provide the following methods:
- initialize() for initial settings
- beginExecution()
- execute() - the main method called in the agent cycle
- endExecution()
- finalize() - the graceful exit of the method, this one is usually used
for the agent restart
"""
queryStateList = ['Ready', 'Submitted', 'Running', 'Waiting', 'Scheduled']
finalStateList = ['Done', 'Aborted', 'Cleared', 'Deleted', 'Failed']
def __init__(self, *args, **kwargs):
""" c'tor
"""
AgentModule.__init__(self, *args, **kwargs)
self.jobDB = None
self.pilotDB = None
self.diracadmin = None
#############################################################################
def initialize(self):
"""Sets defaults
"""
self.am_setOption('PollingTime', 120)
self.am_setOption('GridEnv', '')
self.am_setOption('PilotStalledDays', 3)
self.pilotDB = PilotAgentsDB()
self.diracadmin = DiracAdmin()
self.jobDB = JobDB()
self.clearPilotsDelay = self.am_getOption('ClearPilotsDelay', 30)
self.clearAbortedDelay = self.am_getOption('ClearAbortedPilotsDelay', 7)
self.pilots = PilotManagerClient()
return S_OK()
#############################################################################
def execute(self):
"""The PilotAgent execution method.
"""
self.pilotStalledDays = self.am_getOption('PilotStalledDays', 3)
self.gridEnv = self.am_getOption('GridEnv')
if not self.gridEnv:
# No specific option found, try a general one
setup = gConfig.getValue('/DIRAC/Setup', '')
if setup:
instance = gConfig.getValue('/DIRAC/Setups/%s/WorkloadManagement' % setup, '')
if instance:
self.gridEnv = gConfig.getValue('/Systems/WorkloadManagement/%s/GridEnv' % instance, '')
result = self.pilotDB._getConnection()
if result['OK']:
connection = result['Value']
else:
return result
# Now handle pilots not updated in the last N days (most likely the Broker is no
# longer available) and declare them Deleted.
result = self.handleOldPilots(connection)
connection.close()
result = self.pilots.clearPilots(self.clearPilotsDelay, self.clearAbortedDelay)
if not result['OK']:
self.log.warn('Failed to clear old pilots in the PilotAgentsDB')
return S_OK()
def clearWaitingPilots(self, condDict):
""" Clear pilots in the faulty Waiting state
"""
last_update = Time.dateTime() - MAX_WAITING_STATE_LENGTH * Time.hour
clearDict = {'Status': 'Waiting',
'OwnerDN': condDict['OwnerDN'],
'OwnerGroup': condDict['OwnerGroup'],
'GridType': condDict['GridType'],
'Broker': condDict['Broker']}
result = self.pilotDB.selectPilots(clearDict, older=last_update)
if not result['OK']:
self.log.warn('Failed to get the Pilot Agents for Waiting state')
return result
if not result['Value']:
return S_OK()
refList = result['Value']
for pilotRef in refList:
self.log.info('Setting Waiting pilot to Stalled: %s' % pilotRef)
result = self.pilotDB.setPilotStatus(pilotRef, 'Stalled', statusReason='Exceeded max waiting time')
return S_OK()
def clearParentJob(self, pRef, pDict, connection):
""" Clear the parameteric parent job from the PilotAgentsDB
"""
childList = pDict['ChildRefs']
# Check that at least one child is in the database
children_ok = False
for child in childList:
result = self.pilotDB.getPilotInfo(child, conn=connection)
if result['OK']:
if result['Value']:
children_ok = True
if children_ok:
return self.pilotDB.deletePilot(pRef, conn=connection)
else:
self.log.verbose('Adding children for parent %s' % pRef)
result = self.pilotDB.getPilotInfo(pRef)
parentInfo = result['Value'][pRef]
tqID = parentInfo['TaskQueueID']
ownerDN = parentInfo['OwnerDN']
ownerGroup = parentInfo['OwnerGroup']
broker = parentInfo['Broker']
gridType = parentInfo['GridType']
result = self.pilotDB.addPilotTQReference(childList, tqID, ownerDN, ownerGroup,
broker=broker, gridType=gridType)
if not result['OK']:
return result
children_added = True
for chRef, chDict in pDict['ChildDicts'].items():
result = self.pilotDB.setPilotStatus(chRef, chDict['Status'],
destination=chDict['DestinationSite'],
conn=connection)
if not result['OK']:
children_added = False
if children_added:
result = self.pilotDB.deletePilot(pRef, conn=connection)
else:
return S_ERROR('Failed to add children')
return S_OK()
def handleOldPilots(self, connection):
"""
select all pilots that have not been updated in the last N days and declared them
Deleted, accounting for them.
"""
pilotsToAccount = {}
timeLimitToConsider = Time.toString(Time.dateTime() - Time.day * self.pilotStalledDays)
result = self.pilotDB.selectPilots({'Status': self.queryStateList},
older=timeLimitToConsider,
timeStamp='LastUpdateTime')
if not result['OK']:
self.log.error('Failed to get the Pilot Agents')
return result
if not result['Value']:
return S_OK()
refList = result['Value']
result = self.pilotDB.getPilotInfo(refList)
if not result['OK']:
self.log.error('Failed to get Info for Pilot Agents')
return result
pilotsDict = result['Value']
for pRef in pilotsDict:
if pilotsDict[pRef].get('Jobs') and self._checkJobLastUpdateTime(pilotsDict[pRef]['Jobs'], self.pilotStalledDays):
self.log.debug('%s should not be deleted since one job of %s is running.' %
(str(pRef), str(pilotsDict[pRef]['Jobs'])))
continue
deletedJobDict = pilotsDict[pRef]
deletedJobDict['Status'] = 'Deleted'
deletedJobDict['StatusDate'] = Time.dateTime()
pilotsToAccount[pRef] = deletedJobDict
if len(pilotsToAccount) > 100:
self.accountPilots(pilotsToAccount, connection)
self._killPilots(pilotsToAccount)
pilotsToAccount = {}
self.accountPilots(pilotsToAccount, connection)
self._killPilots(pilotsToAccount)
return S_OK()
def accountPilots(self, pilotsToAccount, connection):
""" account for pilots
"""
accountingFlag = False
pae = self.am_getOption('PilotAccountingEnabled', 'yes')
if pae.lower() == "yes":
accountingFlag = True
if not pilotsToAccount:
self.log.info('No pilots to Account')
return S_OK()
accountingSent = False
if accountingFlag:
retVal = self.pilotDB.getPilotInfo(pilotsToAccount.keys(), conn=connection)
if not retVal['OK']:
self.log.error('Fail to retrieve Info for pilots', retVal['Message'])
return retVal
dbData = retVal['Value']
for pref in dbData:
if pref in pilotsToAccount:
if dbData[pref]['Status'] not in self.finalStateList:
dbData[pref]['Status'] = pilotsToAccount[pref]['Status']
dbData[pref]['DestinationSite'] = pilotsToAccount[pref]['DestinationSite']
dbData[pref]['LastUpdateTime'] = pilotsToAccount[pref]['StatusDate']
retVal = self.__addPilotsAccountingReport(dbData)
if not retVal['OK']:
self.log.error('Fail to retrieve Info for pilots', retVal['Message'])
return retVal
self.log.info("Sending accounting records...")
retVal = gDataStoreClient.commit()
if not retVal['OK']:
self.log.error("Can't send accounting reports", retVal['Message'])
else:
self.log.info("Accounting sent for %s pilots" % len(pilotsToAccount))
accountingSent = True
if not accountingFlag or accountingSent:
for pRef in pilotsToAccount:
pDict = pilotsToAccount[pRef]
self.log.verbose('Setting Status for %s to %s' % (pRef, pDict['Status']))
self.pilotDB.setPilotStatus(pRef,
pDict['Status'],
pDict['DestinationSite'],
pDict['StatusDate'],
conn=connection)
return S_OK()
def __addPilotsAccountingReport(self, pilotsData):
""" fill accounting data
"""
for pRef in pilotsData:
pData = pilotsData[pRef]
pA = PilotAccounting()
pA.setEndTime(pData['LastUpdateTime'])
pA.setStartTime(pData['SubmissionTime'])
retVal = Registry.getUsernameForDN(pData['OwnerDN'])
if not retVal['OK']:
userName = 'unknown'
self.log.error("Can't determine username for dn:", pData['OwnerDN'])
else:
userName = retVal['Value']
pA.setValueByKey('User', userName)
pA.setValueByKey('UserGroup', pData['OwnerGroup'])
result = getSiteForCE(pData['DestinationSite'])
if result['OK'] and result['Value'].strip():
pA.setValueByKey('Site', result['Value'].strip())
else:
pA.setValueByKey('Site', 'Unknown')
pA.setValueByKey('GridCE', pData['DestinationSite'])
pA.setValueByKey('GridMiddleware', pData['GridType'])
pA.setValueByKey('GridResourceBroker', pData['Broker'])
pA.setValueByKey('GridStatus', pData['Status'])
if 'Jobs' not in pData:
pA.setValueByKey('Jobs', 0)
else:
pA.setValueByKey('Jobs', len(pData['Jobs']))
self.log.verbose("Added accounting record for pilot %s" % pData['PilotID'])
retVal = gDataStoreClient.addRegister(pA)
if not retVal['OK']:
return retVal
return S_OK()
def _killPilots(self, acc):
for i in sorted(acc.keys()):
result = self.diracadmin.getPilotInfo(i)
if result['OK'] and i in result['Value'] and 'Status' in result['Value'][i]:
ret = self.diracadmin.killPilot(str(i))
if ret['OK']:
self.log.info("Successfully deleted: %s (Status : %s)" % (i, result['Value'][i]['Status']))
else:
self.log.error("Failed to delete pilot: ", "%s : %s" % (i, ret['Message']))
else:
self.log.error("Failed to get pilot info", "%s : %s" % (i, str(result)))
def _checkJobLastUpdateTime(self, joblist, StalledDays):
timeLimitToConsider = Time.dateTime() - Time.day * StalledDays
ret = False
for jobID in joblist:
result = self.jobDB.getJobAttributes(int(jobID))
if result['OK']:
if 'LastUpdateTime' in result['Value']:
lastUpdateTime = result['Value']['LastUpdateTime']
if Time.fromString(lastUpdateTime) > timeLimitToConsider:
ret = True
self.log.debug(
'Since %s updates LastUpdateTime on %s this does not to need to be deleted.' %
(str(jobID), str(lastUpdateTime)))
break
else:
self.log.error("Error taking job info from DB", result['Message'])
return ret
| andresailer/DIRAC | WorkloadManagementSystem/Agent/PilotStatusAgent.py | Python | gpl-3.0 | 12,315 |
package com.alipay.api.response;
import java.util.List;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
import com.alipay.api.domain.QueryInstBillInfo;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.ebpp.bill.search response.
*
* @author auto create
* @since 1.0, 2017-04-07 17:13:40
*/
public class AlipayEbppBillSearchResponse extends AlipayResponse {
private static final long serialVersionUID = 5782884364812795467L;
/**
* 已经缓存的的key
*/
@ApiField("cachekey")
private String cachekey;
/**
* 实时查询欠费单返回对象
*/
@ApiListField("inst_bill_info_list")
@ApiField("query_inst_bill_info")
private List<QueryInstBillInfo> instBillInfoList;
public void setCachekey(String cachekey) {
this.cachekey = cachekey;
}
public String getCachekey( ) {
return this.cachekey;
}
public void setInstBillInfoList(List<QueryInstBillInfo> instBillInfoList) {
this.instBillInfoList = instBillInfoList;
}
public List<QueryInstBillInfo> getInstBillInfoList( ) {
return this.instBillInfoList;
}
}
| zeatul/poc | e-commerce/e-commerce-ecom-pay-service/src/main/java/com/alipay/api/response/AlipayEbppBillSearchResponse.java | Java | gpl-3.0 | 1,118 |
#!/usr/bin/env python3
goblin_attack = 40
goblin1_alive = True
goblin2_alive = True
goblins_alive = 2
goblin1_stunned = False
goblin2_stunned = False
goblin1_health = 30
goblin2_health = 30
rat_alive = True
rat_health = 15
fists = True
sword = False
shield = False
armor = False
end = False
room = 1
defense = 0
health = 50
weapon = 10
emerald = False
emerald_bribe = False
rope_cut = False
print("Welcome to the Poorly-Coded-Dungeon!")
print("What is your name, player?")
player = input("> ")
print("Well,", player, "you start...IN A DUNGEON!! (big surprise)")
while not end:
#starting room
if room == 1:
print("What do you want to do?")
action = input("> ")
if action == "look around":
if sword:
print("Looking around, there is nothing else of interest; just a way in either direction.")
else:
print("Looking around, you spot a sword. There are also ways out going in any direction.")
elif action == "grab sword":
print("You grab the sword and equip it.")
sword = True
weapon += 5
elif action == "take sword":
print("You take and equip the sword.")
sword = True
weapon += 5
elif action == "help":
print("Your commands are 'look around', 'move forward', 'move left', 'move right', 'move back', 'stats', 'take *item*', 'inspect *item and/or monster*, and 'attack *monster name*'")
elif action == "stats":
print("Health:", health, "Attack:", weapon, "Defense:", defense)
elif action == "move forward":
print("You move forward.")
print("This room is empty. There is only a way forwards and the way you came.")
print("The way forwards leads outside!")
print("You hear some chattering in the distance.")
room = 2
elif action == "move back":
print("You move back.")
print("This room is filled with a lot of discarded items.")
room = 3
elif action == "move left":
print("You move to the left.")
print("You spring a trap!")
health -= 5
print("Don't you know anything about scrolling videogames?")
print("Always go to the RIGHT!")
print("Also, you're not alone in here.")
room = 4
elif action == "move right":
print("You move to the right.")
room = 5
if emerald == False:
if rope_cut == True:
print("This room is mostly empty, save for an emerald that you left in the dead-center of the room")
print("You could easily grab this emerald now.")
else:
print("This room is mostly empty, save for an emerald in the dead-center of the room.")
else:
print("This room is completely empty now. Nothing left of interest.")
else:
print("Sorry, try a different command.")
#Room 2
if room == 2:
print("What do you want to do?")
action = input("> ")
if action == "move back":
print("You move back to the starting room")
room = 1
elif action == "move forward":
print("You move forwards, outside of the dungeon! It's dark outside.")
room = 6
if goblins_alive == 2:
if emerald == True:
print("It seems the chattering you heard was two goblins! They spot you and wield their weapons!")
print("They are about to step forward to attack, but suddenly stop, noticing your shiny emerald.")
else:
print("It seems the chattering you heard was two goblins! They spot you and wield their weapons!")
else:
print("There is nothing left in this room.")
else:
print("Sorry, try a different command.")
#Room 3
if room == 3:
print("What do you want to do?")
action = input("> ")
if action == "search items":
print("Searching through the rabble, you find a shield!")
print("Take shield with you?")
action = input("(yes/no) ")
if action == "yes":
print("You take the shield and put it on")
defense += 10
shield = True
else:
print("You leave the shield as it is.")
elif action == "inspect items":
print("Searching through the rabble, you find a shield!")
print("Take shield with you?")
action = input("> ")
if action == "yes":
print("You take the shield and put it on")
defense += 10
shield = True
else:
print("You leave the shield as it is.")
elif action == "move forward":
print("You go back to the starting room.")
room = 1
elif action == "look around":
print("Several unuseable items are thrown about all over the place.")
print("Who knows why for.")
print("There may be a chance some of it may be useable, but you'd have to get your hands dirty and search.")
else:
print("I'm sorry, please try a different command.")
# Room 4
if room == 4:
print("What do you want to do?")
action = input("> ")
if action == "look around":
if rat_alive == True:
print("You spot a giant rat!")
print("Or rather, he spots you!")
print("Why, oh WHY does EVERY MMORPG start you off killing rats for experience!?")
print("This rat has", rat_health, "health")
else:
print("With the rat dead, you see he was guarding something shiny")
print("Inspect shiny?")
action = input("> ")
if action == "yes":
print("It's a plate of armor!")
print("Take with you?")
action = input("> ")
if action == "yes":
print("You take the armor with you!")
armor = True
defense += 20
else:
print("You leave the armor be")
else:
print("You leave shiny be. Could have been something heavy anyway.")
elif action == "attack rat":
print("You strike at the rat!")
if sword == True:
print("In one mighty blow, you take off it's head!")
rat_alive = False
rat_health = 0
print("You get the sense that the rat was guarding something.")
else:
print("You hit the rat with your fist! The rat takes damage!")
rat_health -= 5
if rat_health == 0:
print("The rat is dead!")
rat_alive = False
print("You get the sense that the rat was guarding something.")
else:
print("The rat fights back! Gnawing at your injured foot!")
health -= 5
if health <= 0:
print("You have died!")
print("---GAME OVER---")
end = True
elif action == "inspect rat":
print("The rat's health is", rat_health)
elif action == "stats":
print("Health:", health, "Attack:", weapon, "Defense:", defense)
elif action == "move back":
if rat_alive == True:
print("You start to move back, but the rat prevents escape and attacks!")
health -=10
if health <= 0:
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("You move back.")
room = 1
else:
print("Sorry, please try a different command.")
#Room 5
if room == 5:
print("What would you like to do?")
action = input("> ")
if action == "take emerald":
if emerald == True:
print("There is no emerald, you took it already.")
print("Greedy.")
else:
if rope_cut == True:
print("You easily take the emerald you left here earlier")
emerald = True
else:
print("You attempt to take the emerald, but find that it pulls a rope in the ground.")
print("The floor gives way and you fall down an endless pit")
print("Congratulations, you now have eternity to think on how your greed was the end of you!")
print("---GAME OVER---")
end = True
elif action == "inspect emerald":
if emerald == True:
print("There is no emerald, you took it already.")
print("You're just full of greed, aren't ya?")
else:
if rope_cut == True:
print("What's there to inspect? It's just the emerald you left here earlier.")
else:
print("Upon inspection, you see that there is a rope attatched to the bottom of the emerald.")
print("Try to cut rope?")
answer = input("(yes/no) ")
if answer == "yes":
if sword == True:
print("You take your sword and Cut the Rope! The emerald is free!")
rope_cut = True
print("Take emerald?")
choice = input("(yes/no) ")
if choice == "no":
print("Well, that seemed rather pointless then.")
elif choice == "yes":
print("You take the emerald with you.")
emerald = True
else:
print("How difficult is it to type in 'yes' or 'no'?")
else:
print("You try with all your might, but you can't Cut the Rope!")
elif answer == "no":
print("Alright....you leave it as it is.")
else:
print("Your options are 'yes' and 'no'. No more have been coded in")
elif action == "move back":
print("You move back")
room = 1
elif action== "stats":
print("Health:", health, "Attack", attack, "Defense", defense)
else:
print("Sorry, try another command.")
#Room 6
if room == 6:
print("What do you want to do?")
action = input("> ")
if action == "attack goblin":
if goblin1_alive == False:
if goblin2_alive == False:
print("There are no more goblins alive.")
print("You killed them both.")
goblins_alive = 0
room = 7
else:
print("You attack the second goblin!")
room = 9
elif goblin2_alive == False:
if goblin1_alive == False:
print("There are no more goblins alive.")
print("You killed them both.")
goblins_alive = 0
room = 7
else:
print("You attack the first goblin!")
room = 10
else:
print("Which Goblin?")
choice = input("1/2: ")
if choice == "1":
print("Attack Goblin", choice, "with what?")
choice2 = input("shield/weapon: ")
if choice2 == "shield":
if shield == True:
print("You bash the first goblin with your shield!")
print("Goblin", choice, "takes 1 damage!")
goblin1_health -=1
print("Goblin", choice, "is stunned!")
goblin1_stunned = True
if goblin2_alive == True:
if goblin2_stunned == True:
print("The second goblin skips out on attacking and regains control!")
print("The second goblin is no longer stunned!")
goblin2_stunned = False
else:
print("The second goblin attacks!")
if defense == 30:
print("The goblin hits you for 10 damage!")
health -=10
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 20:
print("The goblin hits you for 20 damage!")
health -= 20
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 10:
print("The goblin hits you for 30 damage!")
health -= 30
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The goblin hits you full force!")
health -= 40
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("Get ready for the next round!")
else:
print("You don't have the shield!")
elif choice2 == "weapon":
print("You take your weapon and strike at the first goblin!")
goblin1_health -= weapon
if goblin1_health <= 0:
print("The first goblin died!")
goblin1_alive = False
if goblin2_alive == False:
print("You've killed both goblins!")
goblins_alive = 0
room = 7
else:
goblins_alive = 1
elif goblin1_stunned == False:
print("The goblin fights back!")
if defense == 30:
print("The goblin hits you for 10 damage!")
health -=10
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif goblin2_alive == False:
print("Get ready for the next round!")
else:
if goblin2_stunned == True:
print("The second goblin skips out on attacking and regains control!")
print("The second goblin is no longer stunned!")
else:
print("The second goblin attacks!")
if defense == 30:
print("The goblin hits you for 10 damage!")
health -=10
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 20:
print("The goblin hits you for 20 damage!")
health -= 20
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 10:
print("The goblin hits you for 30 damage!")
health -= 30
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The goblin hits you full force!")
health -= 40
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 20:
print("The goblin hits you for 20 damage!")
health -= 20
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif goblin2_alive == False:
print("Get ready for the next round!")
else:
if goblin2_stunned == True:
print("The second goblin skips out on attacking and regains control!")
print("The second goblin is no longer stunned!")
else:
print("The second goblin attacks!")
if defense == 30:
print("The goblin hits you for 10 damage!")
health -=10
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 20:
print("The goblin hits you for 20 damage!")
health -= 20
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 10:
print("The goblin hits you for 30 damage!")
health -= 30
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The goblin hits you full force!")
health -= 40
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 10:
print("The goblin hits you for 30 damage!")
health -= 30
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif goblin2_alive == False:
print("Get ready for the next round!")
else:
if goblin2_stunned == True:
print("The second goblin skips out on attacking and regains control!")
print("The second goblin is no longer stunned!")
else:
print("The second goblin attacks!")
if defense == 30:
print("The goblin hits you for 10 damage!")
health -=10
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 20:
print("The goblin hits you for 20 damage!")
health -= 20
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 10:
print("The goblin hits you for 30 damage!")
health -= 30
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The goblin hits you full force!")
health -= 40
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The goblin hits you full force!")
health -= 40
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif goblin2_alive == False:
print("Get ready for the next round!")
else:
if goblin2_stunned == True:
print("The second goblin skips out on attacking and regains control!")
print("The second goblin is no longer stunned!")
else:
print("The second goblin attacks!")
if defense == 30:
print("The goblin hits you for 10 damage!")
health -=10
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 20:
print("The goblin hits you for 20 damage!")
health -= 20
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 10:
print("The goblin hits you for 30 damage!")
health -= 30
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The goblin hits you full force!")
health -= 40
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The first goblin skips out on attacking and regains control!")
print("The first goblin is no longer stunned!")
goblin1_stunned = False
if goblin2_alive == False:
print("Get ready for the next round!")
else:
if goblin2_stunned == True:
print("The second goblin skips out on attacking and regains control!")
print("The second goblin is no longer stunned!")
else:
print("The second goblin attacks!")
if defense == 30:
print("The goblin hits you for 10 damage!")
health -=10
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 20:
print("The goblin hits you for 20 damage!")
health -= 20
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 10:
print("The goblin hits you for 30 damage!")
health -= 30
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The goblin hits you full force!")
health -= 40
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif choice == "2":
print("Attack Goblin", choice, "with what?")
choice2 = input("shield/weapon: ")
if choice2 == "shield":
if shield == True:
print("You bash the second goblin with your shield!")
print("Goblin", choice, "takes 1 damage!")
goblin2_health -=1
print("Goblin", choice, "is stunned!")
goblin2_stunned = True
if goblin1_alive == True:
if goblin1_stunned == True:
print("The first goblin skips out on attacking and regains control!")
print("The first goblin is no longer stunned!")
goblin1_stunned = False
else:
print("The first goblin attacks!")
if defense == 30:
print("The goblin hits you for 10 damage!")
health -=10
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 20:
print("The goblin hits you for 20 damage!")
health -= 20
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 10:
print("The goblin hits you for 30 damage!")
health -= 30
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The goblin hits you full force!")
health -= 40
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("Get ready for the next round!")
else:
print("You don't have the shield!")
elif choice2 == "weapon":
print("You take your weapon and strike at the second goblin!")
goblin2_health -= weapon
if goblin2_health <= 0:
print("The second goblin died!")
goblin2_alive = False
if goblin1_alive == False:
print("You've killed both goblins!")
goblins_alive = 0
room = 7
else:
goblins_alive = 1
elif goblin2_stunned == False:
print("The goblin fights back!")
if defense == 30:
print("The goblin hits you for 10 damage!")
health -=10
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif goblin1_alive == False:
print("Get ready for the next round!")
else:
if goblin1_stunned == True:
print("The first goblin skips out on attacking and regains control!")
print("The first goblin is no longer stunned!")
else:
print("The first goblin attacks!")
if defense == 30:
print("The goblin hits you for 10 damage!")
health -=10
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 20:
print("The goblin hits you for 20 damage!")
health -= 20
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 10:
print("The goblin hits you for 30 damage!")
health -= 30
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The goblin hits you full force!")
health -= 40
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 20:
print("The goblin hits you for 20 damage!")
health -= 20
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif goblin1_alive == False:
print("Get ready for the next round!")
else:
if goblin1_stunned == True:
print("The first goblin skips out on attacking and regains control!")
print("The first goblin is no longer stunned!")
else:
print("The first goblin attacks!")
if defense == 30:
print("The goblin hits you for 10 damage!")
health -=10
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 20:
print("The goblin hits you for 20 damage!")
health -= 20
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 10:
print("The goblin hits you for 30 damage!")
health -= 30
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The goblin hits you full force!")
health -= 40
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 10:
print("The goblin hits you for 30 damage!")
health -= 30
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif goblin1_alive == False:
print("Get ready for the next round!")
else:
if goblin1_stunned == True:
print("The first goblin skips out on attacking and regains control!")
print("The first goblin is no longer stunned!")
else:
print("The first goblin attacks!")
if defense == 30:
print("The goblin hits you for 10 damage!")
health -=10
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 20:
print("The goblin hits you for 20 damage!")
health -= 20
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 10:
print("The goblin hits you for 30 damage!")
health -= 30
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The goblin hits you full force!")
health -= 40
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The goblin hits you full force!")
health -= 40
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif goblin1_alive == False:
print("Get ready for the next round!")
else:
if goblin1_stunned == True:
print("The first goblin skips out on attacking and regains control!")
print("The first goblin is no longer stunned!")
else:
print("The first goblin attacks!")
if defense == 30:
print("The goblin hits you for 10 damage!")
health -=10
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 20:
print("The goblin hits you for 20 damage!")
health -= 20
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 10:
print("The goblin hits you for 30 damage!")
health -= 30
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The goblin hits you full force!")
health -= 40
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The second goblin skips out on attacking and regains control!")
print("The second goblin is no longer stunned!")
goblin2_stunned = False
if goblin1_alive == False:
print("Get ready for the next round!")
else:
if goblin1_stunned == True:
print("The first goblin skips out on attacking and regains control!")
print("The first goblin is no longer stunned!")
else:
print("The first goblin attacks!")
if defense == 30:
print("The goblin hits you for 10 damage!")
health -=10
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 20:
print("The goblin hits you for 20 damage!")
health -= 20
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 10:
print("The goblin hits you for 30 damage!")
health -= 30
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The goblin hits you full force!")
health -= 40
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("Sorry, please type 'weapon' or 'shield'")
else:
print("Sorry, please type '1' or '2'")
elif action == "inspect goblin":
print("Which goblin?")
choice = input("1/2 ")
if choice == "1":
print("The first goblin's health is:", goblin1_health)
elif choice == "2":
print("The second goblin's health is:", goblin2_health)
else:
print("Sorry, please choose '1' or '2'")
elif action == "stats":
print("Health:", health, "Attack:", weapon, "Defense:", defense)
elif action == "inspect goblin 1":
print("The first goblin's health is:", goblin1_health)
elif action == "inspect goblin 2":
print("The second goblin's health is:", goblin2_health)
elif action == "bribe goblins":
if emerald == True:
print("You wave your pretty emerald in front of their greedy little faces, they are entranced by it's beauty.")
print("Throw emerald at them?")
action2 = input("(yes/no) ")
if action2 == "yes":
print("You throw the emerald at them and they immediately jump for it!")
print("One of them grabs it and the other starts fighting for it.")
print("It seems whoever has the emerald tries running from the other.")
print("Soon enough, both goblins are gone, and the fighting continues elsewhere.")
print("You are safe, and both goblins are gone!")
goblins_alive = 0
goblin1_alive = False
goblin2_alive = False
emerald = False
emerald_bribe = True
room = 7
elif action2 == "no":
print("Turns out, flashing the emerald at them wasn't such a good idea.")
print("They jump for it, scratching, clawing, biting, and slicing at you until it's in their grasp.")
print("Through their determination, speed, and the fact that they are both on you, you are unable to attack or push them back.")
print("They soon realize that you are the one holding the emerald up and slice your throat.")
print("With you dead, the goblins take the emerald and fight over it themselves, running from one another when it is in their grasp.")
print("The goblins have killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("I don't know what you typed in...the coder didn't put any other options, sooo...")
else:
print("You don't have anything they want!")
elif action == "look around":
print("What do you want? There are goblins in front of you! Nothing to aid your combat either!")
elif action == "move back":
print("You can't escape!")
else:
print("You don't have any other options, just follow the script.")
#Room 7
if room == 7:
if emerald_bribe == True:
print("Well, you survived the cave, got a cool sword, bribed the goblins, and are here alive!")
print("But is that really all there is to this game? Is there any more? What happens next?")
print("Just as you ask yourself these questions, you hear leaves rustling in the distance.")
print("Investigate?")
action = input("(yes/no) ")
if action == "yes":
print("You move forward to investigate...")
room = 8
elif action == "no":
print("Okay....there's nothing left to do here...soo.....The end I guess?")
print("You decide to stand around for eternity!")
print("Turns out that you need things like food, water, movement, etc. to live!")
print("You have died!")
print("---GAME OVER---")
end = True
elif emerald == True:
print("Well, you survived the cave, got a shiny emerald, defeated two goblins, and are here alive!")
print("But is that really all there is to this game? Is there any more? What happens next?")
print("Just as you ask yourself these questions, you hear leaves rustling in the distance.")
print("Investigate?")
action = input("(yes/no) ")
if action == "yes":
print("You move forward to investigate...")
room = 8
elif action == "no":
print("Okay....there's nothing left to do here...soo.....The end I guess?")
print("You decide to stand around for eternity!")
print("Turns out that you need things like food, water, movement, etc. to live!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("Well, you survived the cave, defeated two goblins, and are here alive!")
print("But is that really all there is to this game? Is there any more? What happens next?")
print("Just as you ask yourself these questions, you hear leaves rustling in the distance.")
print("Investigate?")
action = input("(yes/no) ")
if action == "yes":
print("You move forward to investigate...")
room = 8
elif action == "no":
print("Okay....there's nothing left to do here...soo.....The end I guess?")
print("You decide to stand around for eternity!")
print("Turns out that you need things like food, water, movement, etc. to live!")
print("You have died!")
print("---GAME OVER---")
end = True
#Room 8 Final room
if room == 8:
print("The path goes on and it gets brighter and brighter. Before long, you have to shield your eyes.")
print("By the time the path stops you can barely see anything. Suddenly, all the lights turn dim enough for you to be able to see.")
print("It takes a few moments, of course, for your eyes to adjust. When they do, you finally see that...")
print("before you stands a creature of Light! It is completely white, save for it's golden-yellow eyes!")
print("It takes you a few moments more to realize that this creature looks exactly like you!")
print("Save for the fact that it's made out of Light, of course.")
print("It simply stares menacingly at you. Almost as if expecting you to do something.")
print("Provoke the creature?")
answer = input("(yes/no) ")
if answer == "yes":
print("Immediately, you are lifted in the air; your Light doppleganger simply stares at you as you flail around.")
print("Suddenly, everything ends. The last thing you hear is a deep male voice coming from behind you, saying only...")
print("'You shouldn't have done that.'")
print("---GAME OVER---")
end = True
elif answer == "no":
print("You decide against attacking the Light creature; it /is/ quite the good looking person, if you do say so yourself.")
print("A deep male voice speaks from behind you; saying 'You are very wise,", player,"'")
print("Turning around, you see a tall, pale man dressed in a formal, victorian era, suit, wearing his overcoat like a cape.")
print("The man speaks: 'The final battle with the goblins already got this poorly-coded game past 1000 lines of code.'")
print("'If The Creator had simply known what he was doing, we may have had a good run, this game.'")
print("'But there is still a chance that The Creator will make another, more decently coded, game...'")
print("'Should that occur, we may meet again. Until then...consider this game 'won' '")
print("The man lifts his arm, saying: 'Congratulations,", player,"'")
print("The man snaps his fingers. Both him and your doppleganger vanish!")
print("Congratulations! You have beaten the game!!")
print("---GAME OVER---")
end = True
else:
print("A deep male voice comes from behind you, saying 'I will take none of your nonsense!'")
print("Suddenly, everything stops.")
print("The last thing you hear is that voice, saying 'You shouldn't have done that!'")
print("You have died!")
print("---GAME OVER---")
end = True
#Room 9 (goblin 2 attack)
if room == 9:
print("Attack the second goblin with what?")
choice2 = input("shield/weapon: ")
if choice2 == "shield":
if shield == True:
print("You bash the second goblin with your shield!")
print("Goblin 2 takes 1 damage!")
goblin2_health -=1
print("Goblin 2 is stunned!")
goblin2_stunned = True
else:
print("You don't have the shield!")
elif choice2 == "weapon":
print("You take your weapon and strike at the second goblin!")
goblin2_health -= weapon
if goblin2_health <= 0:
print("The second goblin died!")
goblin2_alive = False
if goblin1_alive == False:
print("You've killed both goblins!")
goblins_alive = 0
room = 7
else:
goblins_alive = 1
elif goblin2_stunned == False:
print("The goblin fights back!")
if defense == 30:
print("The goblin hits you for 10 damage!")
health -=10
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 20:
print("The goblin hits you for 20 damage!")
health -= 20
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 10:
print("The goblin hits you for 30 damage!")
health -= 30
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The goblin hits you full force!")
health -= 40
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif goblin2_stunned == True:
print("The goblin skips out on attacking and regains control!")
print("The goblin is no longer stunned!")
goblin2_stunned = False
else:
print("Sorry, please type 'weapon' or 'shield'")
#Room 10 (goblin 1 attack)
if room == 10:
print("Attack the first goblin with what?")
choice2 = input("shield/weapon: ")
if choice2 == "shield":
if shield == True:
print("You bash the first goblin with your shield!")
print("Goblin 1 takes 1 damage!")
goblin1_health -=1
print("Goblin 1 is stunned!")
goblin1_stunned = True
else:
print("You don't have the shield!")
elif choice2 == "weapon":
print("You take your weapon and strike at the first goblin!")
goblin1_health -= weapon
if goblin1_health <= 0:
print("The first goblin died!")
goblin1_alive = False
if goblin2_alive == False:
print("You've killed both goblins!")
goblins_alive = 0
room = 7
else:
goblins_alive = 1
elif goblin1_stunned == False:
print("The goblin fights back!")
if defense == 30:
print("The goblin hits you for 10 damage!")
health -=10
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 20:
print("The goblin hits you for 20 damage!")
health -= 20
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif defense == 10:
print("The goblin hits you for 30 damage!")
health -= 30
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
else:
print("The goblin hits you full force!")
health -= 40
if health <= 0:
print("The goblin killed you!")
print("You have died!")
print("---GAME OVER---")
end = True
elif goblin1_stunned == True:
print("The goblin skips out on attacking and regains control!")
print("The goblin is no longer stunned!")
goblin1_stunned = False
else:
print("Sorry, please type 'weapon' or 'shield'")
| CoderLune/First-projects | dungeon.py | Python | gpl-3.0 | 50,140 |
<?php
$languageNames = [
'aa' => 'Qafar',
];
$countryNames = [
'DJ' => 'Yabuuti',
'ER' => 'Eretria',
'ET' => 'Otobbia',
];
| Facerafter/starcitizen-tools | extensions/cldr/CldrNames/CldrNamesAa.php | PHP | gpl-3.0 | 129 |
/*
Copyright (C) 2013 by Rafał Soszyński <rsoszynski121 [at] gmail [dot] com>
This file is part of The Chronicles Of Andaria Project.
The Chronicles of Andaria Project is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The Chronicles of Andaria Project is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with The Chronicles Of Andaria. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Game/Windows/MarketWindow.h"
MarketWindow::MarketWindow(Player *player, PlayerWindow *playerWindow, const QList <const Item *> &wares)
: player_(player), playerWindow_(playerWindow), wares_(wares)
{
QVBoxLayout *mainLayout = new QVBoxLayout(this);
setWindowTitle("Bazar");
QLabel *playerItemsLabel = new QLabel("Twoje przedmioty");
playerItemList = new QListWidget();
playerItemList->setToolTip(QString::fromUtf8("Lista posiadanych przedmiotów."));
QLabel *availableWaresLabel = new QLabel(QString::fromUtf8("Przedmioty dostępne na bazarze"));
wareList = new QListWidget();
wareList->setToolTip(QString::fromUtf8("Lista towarów dostępnych do kupienia na bazarze."));
populateListWidgets();
QVBoxLayout *leftPartLayout = new QVBoxLayout();
leftPartLayout->addWidget(playerItemsLabel);
leftPartLayout->addWidget(playerItemList);
leftPartLayout->addWidget(availableWaresLabel);
leftPartLayout->addWidget(wareList);
QHBoxLayout *upperPartLayout = new QHBoxLayout();
upperPartLayout->addLayout(leftPartLayout);
itemDescriptionWidget = new QTextBrowser();
itemDescriptionWidget->setToolTip(QString::fromUtf8("opis aktualnie zaznaczonego przedmiotu."));
upperPartLayout->addWidget(itemDescriptionWidget);
mainLayout->addLayout(upperPartLayout);
QLabel *smallPotionIcon = new QLabel();
smallPotionIcon->setPixmap(DataManager::pixmap(TCOA::Paths::ICON_SMALL_HEALTH_MIXTURE));
smallPotionCountLabel = new QLabel(QString::number(player->equipment()->smallPotions()));
smallPotionButton = new QPushButton(QString("Kup(") +
QString::number(CENA_MALEJ_MIKSTURY) +
QString(")"));
smallPotionButton->setEnabled(player->gold() >= CENA_MALEJ_MIKSTURY);
QLabel *largePotionIcon = new QLabel();
largePotionIcon->setPixmap(DataManager::pixmap(TCOA::Paths::ICON_BIG_HEALTH_MIXTURE));
largePotionCountLabel = new QLabel(QString::number(player->equipment()->largePotions()));
largePotionButton = new QPushButton(QString("Kup(") +
QString::number(CENA_DUZEJ_MIKSTURY) +
QString(")"));
largePotionButton->setEnabled(player->gold() >= CENA_DUZEJ_MIKSTURY);
buyButton = new QPushButton();
buyButton->setToolTip(QString::fromUtf8("Zależnie od okoliczności, przycisk pozwala na kupno albo sprzedaż aktualnie zaznaczonego przedmiotu."));
buyButton->setVisible(false);
equipButton = new QPushButton();
equipButton->setToolTip(QString::fromUtf8("Zależnie od okoliczności, przycisk pozwala na założenie albo zdjęcie aktualnie zaznaczonego przedmiotu z Twojej postaci."));
equipButton->setVisible(false);
confirmButton = new QPushButton("Ok");
QHBoxLayout *bottomPartLayout = new QHBoxLayout();
bottomPartLayout->addWidget(smallPotionIcon);
bottomPartLayout->addWidget(smallPotionCountLabel);
bottomPartLayout->addWidget(smallPotionButton);
bottomPartLayout->addWidget(largePotionIcon);
bottomPartLayout->addWidget(largePotionCountLabel);
bottomPartLayout->addWidget(largePotionButton);
bottomPartLayout->addStretch();
bottomPartLayout->addWidget(buyButton);
bottomPartLayout->addWidget(equipButton);
bottomPartLayout->addWidget(confirmButton);
mainLayout->addLayout(bottomPartLayout);
connect(wareList, SIGNAL(clicked(const QModelIndex &)), this, SLOT(displayMarketItem(const QModelIndex &)));
connect(playerItemList, SIGNAL(clicked(const QModelIndex &)), this, SLOT(displayPlayerItem(const QModelIndex &)));
connect(smallPotionButton, SIGNAL(clicked()), this, SLOT(buySmallPotion()));
connect(largePotionButton, SIGNAL(clicked()), this, SLOT(buyLargePotion()));
connect(confirmButton, SIGNAL(clicked()), this, SLOT(close()));
connect(equipButton, SIGNAL(clicked()), this, SLOT(equip()));
connect(buyButton, SIGNAL(clicked()), this, SLOT(buy()));
}
/**
* @brief OknoBazaru::wypelnijListy Wypełnia listę przedmiotów własnych i do kupienia odpowiednimi namemi.
*/
void MarketWindow::populateListWidgets()
{
const Equipment *equipment = player_->equipment();
const QList <const Item *> &backpack = equipment->backpack();
playerItemList->clear();
for (const Item *item : backpack)
playerItemList->addItem(item->name());
wareList->clear();
for (const Item *item : wares_)
wareList->addItem(item->name());
}
/**
* @brief OknoBazaru::wyswietlOpisDlaGracza Wyświetla opis przedmiotu z listy posiadanych przez gracza
* @param element dane wpisu, który został wybrany.
*/
void MarketWindow::displayPlayerItem(const QModelIndex &index)
{
wareList->setCurrentRow(-1);
buyButton->setText(sellText);
buyButton->setVisible(true);
buyButton->setEnabled(true);
const Item *item = player_->equipment()->backpack().at(index.row());
equipButton->setVisible(true);
if (isEquipped(item, player_))
equipButton->setText(unequipText);
else
equipButton->setText(equipText);
equipButton->setEnabled(isPermitted(item, player_));
generateDescription(item, player_, itemDescriptionWidget);
}
/**
* @brief OknoBazaru::wyswietlOpisDlaBazaru Wyświetla opis przedmiotu z listy dostępnych na bazarze.
* @param element dane wpisu, który został wybrany
*/
void MarketWindow::displayMarketItem(const QModelIndex& element)
{
playerItemList->setCurrentRow(-1);
const Item *item = wares_.at(element.row());
equipButton->setVisible(false);
buyButton->setVisible(true);
buyButton->setText(buyText);
buyButton->setEnabled(player_->gold() >= item->value());
generateDescription(item, player_, itemDescriptionWidget);
}
/**
* @brief OknoBazaru::kupMalaMiksture Przeprowadza kupno małej mikstury zdrowia.
*/
void MarketWindow::buySmallPotion()
{
Equipment *equipment = player_->equipment();
equipment->setSmallPotions(equipment->smallPotions() + 1);
player_->setGold(player_->gold() - CENA_MALEJ_MIKSTURY);
playerWindow_->update();
smallPotionCountLabel->setText(QString::number(player_->equipment()->smallPotions()));
largePotionButton->setEnabled(player_->gold() >= CENA_DUZEJ_MIKSTURY);
smallPotionButton->setEnabled(player_->gold() >= CENA_MALEJ_MIKSTURY);
}
/**
* @brief OknoBazaru::kupDuzaMiksture Przeprowadza kupno dużej mikstury zdrowia.
*/
void MarketWindow::buyLargePotion()
{
Equipment *equipment = player_->equipment();
equipment->setLargePotions(equipment->largePotions() + 1);
player_->setGold(player_->gold() - CENA_DUZEJ_MIKSTURY);
playerWindow_->update();
smallPotionCountLabel->setText(QString::number(player_->equipment()->largePotions()));
largePotionButton->setEnabled(player_->gold() >= CENA_DUZEJ_MIKSTURY);
smallPotionButton->setEnabled(player_->gold() >= CENA_MALEJ_MIKSTURY);
}
/**
* @brief OknoBazaru::zaloz Odpowiednio zakłada lub zdejmuje aktualnie zaznaczony przedmiot z listy przedmiotów gracza
*/
void MarketWindow::equip()
{
const QList <const Item *> backpack = player_->equipment()->backpack();
const Item *item = backpack.at(playerItemList->currentRow());
if (equipButton->text() == unequipText) //NOTE do I really want string comparision? Maybe boolean flag?
unequipItem(item, player_);
else
equipItem(item, player_);
generateDescription(item, player_, itemDescriptionWidget);
playerWindow_->update();
if (isEquipped(item, player_))
equipButton->setText(unequipText);
else
equipButton->setText(equipText);
}
/**
* @brief OknoBazaru::kup Kupuje lub sprzedaje aktualnie zaznaczony przedmiot z listy przedmiotów na bazarze.
*/
void MarketWindow::buy()
{
Equipment *equipment = player_->equipment();
if (buyButton->text() == sellText) {
const Item *item = equipment->backpack().at(playerItemList->currentRow());
unequipItem(item, player_);
equipment->removeItem(item);
wares_.push_back(item);
player_->setGold(player_->gold() + item->value() / 2);
} else {
const Item *item = wares_.at(wareList->currentRow());
if (player_->gold() < item->value())
return;
equipment->addItem(item);
wares_.removeAt(wares_.indexOf(item));
player_->setGold(player_->gold() - item->value());
}
populateListWidgets();
playerWindow_->update();
largePotionButton->setEnabled(player_->gold() >= CENA_DUZEJ_MIKSTURY);
smallPotionButton->setEnabled(player_->gold() >= CENA_MALEJ_MIKSTURY);
}
| Soszu/TheChroniclesOfAndaria | src/Game/Windows/MarketWindow.cpp | C++ | gpl-3.0 | 9,030 |
<?php
namespace Fisharebest\Localization\Script;
/**
* Class ScriptCyrl - Representation of the Cyrillic script.
*
* @author Greg Roach <greg@subaqua.co.uk>
* @copyright (c) 2020 Greg Roach
* @license GPLv3+
*/
class ScriptCyrl extends AbstractScript implements ScriptInterface
{
public function code()
{
return 'Cyrl';
}
public function number()
{
return '220';
}
public function unicodeName()
{
return 'Cyrillic';
}
}
| fisharebest/localization | src/Script/ScriptCyrl.php | PHP | gpl-3.0 | 495 |
/*
Copyright (C) 2010,2011,2012,2013,2014,2015,2016 The ESPResSo project
Copyright (C) 2002,2003,2004,2005,2006,2007,2008,2009,2010
Max-Planck-Institute for Polymer Research, Theory Group
This file is part of ESPResSo.
ESPResSo is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ESPResSo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** \file reaction.cpp
*
*/
#include "swimmer_reaction.hpp"
#include "cells.hpp"
#include "errorhandling.hpp"
#include "forces.hpp"
#include "initialize.hpp"
#include "utils.hpp"
#include "random.hpp"
#include "communication.hpp"
#include "integrate.hpp"
#include "grid.hpp"
#include <algorithm>
#include <random>
#include <vector>
reaction_struct reaction;
#ifdef SWIMMER_REACTIONS
void reactions_sanity_checks() {
if (reaction.ct_rate != 0.0) {
if (!cell_structure.use_verlet_list || cell_structure.type != CELL_STRUCTURE_DOMDEC) {
runtimeErrorMsg() << "The SWIMMER_REACTIONS feature requires verlet "
"lists and domain decomposition";
}
if (max_cut < reaction.range) {
runtimeErrorMsg() << "Reaction range of " << reaction.range
<< " exceeds maximum cutoff of " << max_cut;
}
}
}
void local_setup_reaction() {
/* Make available the various reaction parameters */
MPI_Bcast(&reaction.reactant_type, 1, MPI_INT, 0, comm_cart);
MPI_Bcast(&reaction.product_type, 1, MPI_INT, 0, comm_cart);
MPI_Bcast(&reaction.catalyzer_type, 1, MPI_INT, 0, comm_cart);
MPI_Bcast(&reaction.range, 1, MPI_DOUBLE, 0, comm_cart);
MPI_Bcast(&reaction.ct_rate, 1, MPI_DOUBLE, 0, comm_cart);
MPI_Bcast(&reaction.eq_rate, 1, MPI_DOUBLE, 0, comm_cart);
MPI_Bcast(&reaction.sing_mult, 1, MPI_INT, 0, comm_cart);
MPI_Bcast(&reaction.swap, 1, MPI_INT, 0, comm_cart);
/* Create the various reaction related types (categories) */
make_particle_type_exist(reaction.catalyzer_type);
make_particle_type_exist(reaction.product_type);
make_particle_type_exist(reaction.reactant_type);
/* Make ESPResSo aware that reactants and catalyst are interacting species */
IA_parameters *data =
get_ia_param_safe(reaction.reactant_type, reaction.catalyzer_type);
/* Used for the range of the verlet lists */
data->REACTION_range = reaction.range;
/* Broadcast interaction parameters */
mpi_bcast_ia_params(reaction.reactant_type, reaction.catalyzer_type);
}
void integrate_reaction_noswap() {
double dist2, vec21[3], ct_ratexp, eq_ratexp, rand, bernoulli;
if (reaction.ct_rate > 0.0) {
/* Determine the reaction rate */
ct_ratexp = exp(-time_step * reaction.ct_rate);
on_observable_calc();
for (int c = 0; c < local_cells.n; c++) {
/* Take into account only those cell neighbourhoods for which
the central cell contains a catalyzer particle */
auto check_catalyzer = 0;
auto cell = local_cells.cell[c];
auto p1 = cell->part;
auto np = cell->n;
for (int i = 0; i < np; i++) {
if (p1[i].p.type == reaction.catalyzer_type) {
check_catalyzer = 1;
break;
}
}
/* If the central cell contains a catalyzer particle, ...*/
if (check_catalyzer != 0) {
for (auto &pair : cell->m_verlet_list) {
auto p1 = pair.first; // pointer to particle 1
auto p2 = pair.second; // pointer to particle 2
if ((p1->p.type == reaction.reactant_type &&
p2->p.type == reaction.catalyzer_type) ||
(p2->p.type == reaction.reactant_type &&
p1->p.type == reaction.catalyzer_type)) {
get_mi_vector(vec21, p1->r.p, p2->r.p);
dist2 = sqrlen(vec21);
/* Count the number of times a reactant particle is
checked against a catalyst */
if (dist2 < reaction.range * reaction.range) {
if (p1->p.type == reaction.reactant_type) {
p1->p.catalyzer_count++;
} else {
p2->p.catalyzer_count++;
}
}
}
}
}
}
/* Now carry out the reaction on the particles which are tagged */
for (int c = 0; c < local_cells.n; c++) {
auto cell = local_cells.cell[c];
auto p1 = cell->part;
auto np = cell->n;
for (int i = 0; i < np; i++) {
if (p1[i].p.type == reaction.reactant_type) {
if (p1[i].p.catalyzer_count > 0) {
if (reaction.sing_mult == 0) {
rand = d_random();
bernoulli = pow(ct_ratexp, p1[i].p.catalyzer_count);
if (rand > bernoulli) {
p1[i].p.type = reaction.product_type;
}
} else /* We only consider each reactant once */
{
rand = d_random();
if (rand > ct_ratexp) {
p1[i].p.type = reaction.product_type;
}
}
p1[i].p.catalyzer_count = 0;
}
}
}
}
/* We only need to do something when the equilibrium
reaction rate constant is nonzero */
if (reaction.eq_rate > 0.0) {
eq_ratexp = exp(-time_step * reaction.eq_rate);
for (int c = 0; c < local_cells.n; c++) {
auto cell = local_cells.cell[c];
auto p1 = cell->part;
auto np = cell->n;
/* Convert products into reactants and vice versa
according to the specified rate constant */
for (int i = 0; i < np; i++) {
if (p1[i].p.type == reaction.product_type) {
rand = d_random();
if (rand > eq_ratexp) {
p1[i].p.type = reaction.reactant_type;
}
} else if (p1[i].p.type == reaction.reactant_type) {
rand = d_random();
if (rand > eq_ratexp) {
p1[i].p.type = reaction.product_type;
}
}
}
}
}
on_particle_change();
}
}
#ifdef ROTATION
bool in_lower_half_space(Particle p1, Particle p2) {
// This function determines whether the particle p2 is in the lower
// half space of particle p1
auto const distvec = get_mi_vector(p1.r.p, p2.r.p);
double dot = p1.r.quatu * distvec;
int sgn = Utils::sign(dot);
return (sgn + 1) / 2;
}
void integrate_reaction_swap() {
int np;
Particle *p_local, *p_neigh;
Cell *cell;
double dist2, vec21[3], ct_ratexp, rand;
int n_reactions;
#ifdef ELECTROSTATICS
double product_q = 0.0, reactant_q = 0.0;
#endif
std::vector<int> catalyzers, reactants, products;
// To randomize the lists of cells below we need a random number
// engine. In previous versions of C++ this was a single function
// std::random_shuffle, which is unfortunately deprecated in C++17
// and discouraged from C++11 on.
std::random_device rd; // non-deterministic random number generator
// using hardware entropy source
std::mt19937 rng(rd()); // Mersenne Twister by Matsumoto and Nishimura
// If multiple catalyzers get close to each other, they might eat up
// each others reactants. If we traverse the cells in a sorted
// manner, then catalyzers in the upper left will use up all the
// reactants of the catalyzers which are below right of them. This
// process is biased. To rectify this issue we set up a vector
// which goes through the cells in a randomized manner.
std::vector<int> rand_cells(local_cells.n);
for (int i = 0; i < local_cells.n; i++)
rand_cells[i] = i;
std::shuffle(rand_cells.begin(), rand_cells.end(), rng);
if (reaction.ct_rate > 0.0) {
// Determine the reaction rate
ct_ratexp = exp(-time_step * reaction.ct_rate);
on_observable_calc();
// Iterate over all the local cells
for (std::vector<int>::iterator c = rand_cells.begin();
c != rand_cells.end(); c++) {
// Take into account only those cell neighborhoods for which
// the central cell contains a catalyzer particle
cell = local_cells.cell[*c];
p_local = cell->part;
np = cell->n;
// We find all catalyzers in a cell and then randomize their ids
// for the same reason as above and then start the catalytic
// reaction procedure
catalyzers.clear();
for (int i = 0; i < np; i++) {
if (p_local[i].p.type == reaction.catalyzer_type)
catalyzers.push_back(i);
}
std::shuffle(catalyzers.begin(), catalyzers.end(), rng);
// Loop cell neighbors
for (int n = 0; n < cells.size(); n++) {
cell = &cells[n];
p_neigh = cell->part;
np = cell->n;
// We loop over all the catalyzer particles
for (std::vector<int>::iterator id = catalyzers.begin();
id != catalyzers.end(); id++) {
reactants.clear();
products.clear();
// Particle list loop
for (int i = 0; i < np; i++) {
// Get the distance between a catalyst and another particle
get_mi_vector(vec21, p_local[*id].r.p, p_neigh[i].r.p);
dist2 = sqrlen(vec21);
// Check if the distance is within the reaction range and
// check if no reaction has taken place on the particle in
// the current step
if (dist2 < reaction.range * reaction.range &&
p_neigh[i].p.catalyzer_count == 0) {
// If the particle is of correct type AND resides in the
// correct half space, append it to the lists of viable
// reaction candidates
if (p_neigh[i].p.type == reaction.reactant_type &&
in_lower_half_space(p_local[*id], p_neigh[i])) {
reactants.push_back(i);
#ifdef ELECTROSTATICS
reactant_q = p_neigh[i].p.q;
#endif // ELECTROSTATICS
}
if (p_neigh[i].p.type == reaction.product_type &&
!in_lower_half_space(p_local[*id], p_neigh[i]))
products.push_back(i);
#ifdef ELECTROSTATICS
product_q = p_neigh[i].p.q;
#endif // ELECTROSTATICS
}
}
// If reactants and products were found, perform the reaction
if (reactants.size() > 0 && products.size() > 0) {
// There cannot be more reactions than the minimum of
// the number of reactants and products. Hence we need
// to determine which number is smaller and also count
// the number of reactions.
n_reactions = 0;
// If there are more products than reactants...
if (reactants.size() <= products.size()) {
// ...iterate the reactant...
for (std::vector<int>::iterator rt = reactants.begin();
rt < reactants.end(); rt++) {
// ...draw a random number number and compare to the
// reaction rate...
rand = d_random();
if (rand > ct_ratexp) {
// ...tag the particle for modification...
p_neigh[*rt].p.catalyzer_count = 1;
n_reactions++;
}
}
// ...tag as many products as there will be reactions
// at random
std::shuffle(products.begin(), products.end(), rng);
for (int p = 0; p < n_reactions; p++)
p_neigh[products[p]].p.catalyzer_count = 1;
} else {
// Same as above, but for the case that the number of
// reactants is greater than the number of products
for (std::vector<int>::iterator pt = products.begin();
pt < products.end(); pt++) {
rand = d_random();
if (rand > ct_ratexp) {
p_neigh[*pt].p.catalyzer_count = 1;
n_reactions++;
}
}
std::shuffle(reactants.begin(), reactants.end(), rng);
for (int p = 0; p < n_reactions; p++)
p_neigh[reactants[p]].p.catalyzer_count = 1;
}
}
}
}
}
// Apply the changes to the tagged particles. Therefore, again
// loop over all cells
for (std::vector<int>::iterator c = rand_cells.begin();
c != rand_cells.end(); c++) {
cell = local_cells.cell[*c];
p_local = cell->part;
np = cell->n;
// Particle list loop
for (int i = 0; i < np; i++) {
// If the particle has been tagged we perform the changes
if (p_local[i].p.catalyzer_count != 0) {
// Flip type and charge
if (p_local[i].p.type == reaction.reactant_type) {
p_local[i].p.type = reaction.product_type;
#ifdef ELECTROSTATICS
p_local[i].p.q = product_q;
#endif // ELECTROSTATICS
} else {
p_local[i].p.type = reaction.reactant_type;
#ifdef ELECTROSTATICS
p_local[i].p.q = reactant_q;
#endif // ELECTROSTATICS
}
// Reset the tag for the next step
p_local[i].p.catalyzer_count = 0;
}
}
}
on_particle_change();
}
}
#endif // ROTATION
void integrate_reaction() {
#ifdef ROTATION
if (reaction.swap)
integrate_reaction_swap();
else
#endif // ROTATION
integrate_reaction_noswap();
}
#endif
| KonradBreitsprecher/espresso | src/core/swimmer_reaction.cpp | C++ | gpl-3.0 | 13,787 |
#include "Component.h"
namespace EntitySystem
{
ComponentType Component::m_unique = 0; // initialize m_unique
} | GarrettFleischer/EntityFramework | EntityFramework/Component.cpp | C++ | gpl-3.0 | 113 |
#include <bits/stdc++.h>
#define sp << " " <<
#define tb << "\t" <<
#define all(x) x.begin(),x.end()
#define PB push_back
#define sz(x) (int)x.size()
#define MP make_pair
#define X first
#define Y second
#define _xx(_1, _2, _3, _4, name, ...) name
#define rep2(i, n) rep3(i, 0, n)
#define rep3(i, a, b) rep4(i, a, b, 1)
#define rep4(i, a, b, c) for (int i = int(a); i < int(b); i += int(c))
#define rep(...) _xx(__VA_ARGS__, rep4, rep3, rep2, _)(__VA_ARGS__)
using namespace std;
const int mod = 1e9+7;
int m;
const int M=8;
using i64 = long long;
using u32 = unsigned;
using u64 = unsigned long long;
using bits = bitset<M>;
using pi = pair<u32, u32>;
using pp = pair<pi, pi>;
using vi = vector<int>;
using vpp = vector<pp>;
const vector<vector<vi> > orient {
{{}},
{{},{1,1}},
{{},{2,1,1,2},{1,2,2,1},{1,1,2,2}},
{{},{3,2,2,1,1,3},{2,1,1,3,3,2},{2,1,1,2,3,3},{1,3,3,2,2,1},{1,2,3,3,2,1},{1,1,2,3,3,2},{3,2,1,1,2,3},{1,1,3,2,2,3},
{1,2,2,1,3,3},{1,3,3,1,2,2}, {2,2,3,1,1,3},{3,1,2,2,1,3},{1,3,2,2,3,1},{1,1,2,2,3,3}},
{{},
{4,3,3,2,2,1,1,4},
{3,2,2,1,1,4,4,3},
{3,2,2,1,1,3,4,4},{4,2,3,3,2,1,1,4},{2,3,3,2,1,1,4,4},
{2,1,1,4,4,3,3,2},
{2,1,1,3,4,4,3,2},{2,1,1,3,3,2,4,4},{4,1,2,3,3,2,1,4},
{2,1,1,2,3,4,4,3},{2,2,3,1,1,4,4,3},{2,1,1,4,4,2,3,3},
{2,1,1,2,3,3,4,4},{2,2,3,3,4,1,1,4},{2,2,3,1,1,3,4,4},
{1,4,4,3,3,2,2,1},
{1,3,4,4,3,2,2,1},{1,3,3,2,2,1,4,4},{1,3,3,2,4,4,2,1},
{1,2,3,4,4,3,2,1},{1,2,2,1,3,4,4,3},{1,4,4,2,2,1,3,3},
{1,2,3,3,4,4,2,1},{1,2,3,3,2,1,4,4},{1,1,3,2,2,3,4,4},{1,1,4,2,3,3,2,4},{1,1,3,3,4,2,2,4},
{1,1,2,4,4,3,3,2},{1,4,4,3,3,1,2,2},{1,4,4,1,2,3,3,2},{1,4,2,3,3,2,4,1},
{1,1,2,3,4,4,3,2},{1,3,4,4,3,1,2,2},{1,1,2,3,3,2,4,4},{1,3,3,1,2,2,4,4},
{1,1,2,2,3,4,4,3},{1,1,2,4,4,2,3,3},{1,4,4,1,2,2,3,3},
{1,1,2,2,3,3,4,4} }
};
template<typename T>
class AddSpace {
private:
T const& ref;
public:
AddSpace(T const& r) : ref(r) {}
friend ostream& operator<<(ostream& os, AddSpace<T> s) {
return os << s.ref << ' ';
}
};
template<typename... Args>
void print(Args... args) {
(cout << ... << AddSpace(args)) << '\n';
}
template <typename T>
void printcoll (T const& coll) {
typename T::const_iterator pos; // iterator to iterate over coll
typename T::const_iterator end(coll.end()); // end position
for (pos=coll.begin(); pos!=end; ++pos) {
cout << *pos ;//<< ' ';
}
//cout << '\n';
}
template <typename I>
I mult(const I a, const I b) {
return ((__int128) a*b)%mod;
}
template <typename I>
I add(const I a, const I b) {
return (a+b)%mod;
}
template <typename I>
I power_mod(I base, unsigned long exp) {
I result = 1;
while (exp > 0) {
if (exp&1) result = mult(result,base);//(result*base)%mod;
base = mult(base,base);//(base*base)%mod;
exp >>=1;
}
return result;
}
template <typename A>
A power_accumulate_semigroup(A r, A a, unsigned long n) {
if (n==0) return r;
while (true) {
if (n&1) {
r = r*a;
if (n==1) return r;
}
n>>=1;
a = a*a;
}
}
template <typename A>
A power_semigroup(A a, unsigned long n) {
// precondition(n > 0);
while(!(n&1)) {
a = a*a;
n>>=1;
}
if (n == 1) return a;
return power_accumulate_semigroup
(a, a*a, (n-1)>>1);
}
template <typename I>
I inverse(I a) {
return power_semigroup(a, mod-2);
}
template <typename T>
class matrix {
size_t size;
public:
vector<vector<T> > data;
matrix(size_t n) : size(n) {
for (size_t i=0;i<n;++i) {
data.push_back(vector<T>(n));
data[i] = vector<T>(n, T{0});
}
}
T operator()(size_t i, size_t j) const {return data[i][j];}
T& operator()(size_t i, size_t j) {return data[i][j];}
matrix operator*(const matrix& b) {
matrix a(size);
for (size_t i=0;i<size;++i)
for (size_t j=0;j<size;++j) {
vector<T> column;
for (size_t k=0;k<size;++k) column.push_back(b.data[k][j]);
a.data[i][j] = inner_product(all(data[i]),begin(column),(T)0,add<T>,mult<T>);
}
return a;
}
matrix operator+(const matrix& b) {
matrix a(size);
for (size_t i=0;i<size;++i)
for (size_t j=0;j<size;++j) {
a.data[i][j] = add(data[i][j],b.data[i][j]);
}
return a;
}
matrix operator-(const matrix& b) {
matrix a(size);
for (size_t i=0;i<size;++i)
for (size_t j=0;j<size;++j) {
a.data[i][j] = add(data[i][j],mod-b.data[i][j]);
}
return a;
}
void identity() {
for (size_t i=0;i<size;++i) data[i][i]=1;
}
void printMatrix() {
for (size_t i=0;i<size;++i) {
for (size_t j=0;j<size;++j)
cout << data[i][j] << ' ';
cout << endl;
}
cout << endl;
}
matrix geom_sum(long n) {
if (n==1) return *this;
matrix<int> S2 = (*this)*(*this) + (*this);
if (n==2) return S2;
matrix<int> m(3*size);
for (size_t i=0;i<size;++i) {
m.data[i][2*size+i] = 1;
for (size_t j=0;j<size;++j) {
m.data[i][j] = data[i][j];
m.data[size+j][j] = 1;
m.data[2*size+j][2*size+j] = 1;
}
}
m = power_semigroup(m, n-2);
matrix<int> S00(size);
matrix<int> S01(size);
matrix<int> S02(size);
for (size_t i=0;i<size;++i)
for (size_t j=0;j<size;++j) {
S00.data[i][j] = m.data[i][j];
S01.data[i][j] = m.data[i][size+j];
S02.data[i][j] = m.data[i][2*size+j];
}
return S00*S2 + S01*(*this) + S02*(*this);
}
};
string binrep(int a) {
return string(bits(a).to_string(), 9-m);
}
bits hor(bits a) {
return bits(a ^ (a<<1));
}
int lines(bits a) {
return hor(a).count()>>1;
}
bool f(bits a, bits b) {
bool w, x, y, z;
w = a[0]; x = a[1]; y = b[0]; z = b[1];
return ((w==x) & (w==y) & (y==z)) | ((w^x) & (w^y) & (y^z));
}
bool forbidden(bits a, bits b) {
if ((~a[m-2] & ~b[m-2]) | (~a[0] & ~b[0]) | (a & b).none()) return true;
rep(i, m-1) {
if (f(a>>i, b>>i)) return true;
}
return false;
}
int get_nzpos(const bits& v, int p) {
int a{m-1}, b{0};
while (true) {
while (!v[a]) {a--;}
if (b == p) {return a;}
b++; a--;
}
return a;
}
bool in_between(int old, int cur, const bits& v1, const bits& v2) {
int p1 = get_nzpos(v1, old);
int p2 = get_nzpos(v1, cur);
if (v2[p1] || v2[p2]) return true;
rep(i, min(p1,p2)+1, max(p1,p2)) if (v2[i] || v1[i]) return true;
return false;
}
bool in_between2(int cur_p, int cur_q, const bits& v1, const bits& v2) {
int p1 = get_nzpos(v1, cur_p);
int p2 = get_nzpos(v2, cur_q);
rep(i, min(p1,p2)+1, max(p1,p2)) if (v2[i] || v1[i]) return true;
return false;
}
int next(int pos, const vi& ori, int io) {
int cur;
if (pos == -1) cur = 1;
else cur = ori[pos]+1;
auto it = find(all(ori), cur);
if (it != end(ori) && io ^ (distance(begin(ori), it)&1)) it = find(it+1, end(ori), cur);
return distance(begin(ori), it);
}
int same(int pos, const vi& ori, int io) {
int cur = ori[pos];
auto it = find(all(ori), cur);
if (it != end(ori) && io ^ (distance(begin(ori), it)&1)) it = find(it+1, end(ori), cur);
return distance(begin(ori), it);
}
bool match_states (bits p, bits q, const vi& ori_p, const vi& ori_q) {
int cur_p{-1}, cur_q{-1};
bits pict_p = hor(p);
bits pict_q = hor(q);
while (true) {
cur_p = next(cur_p, ori_p, 0);
cur_q = next(cur_q, ori_q, 0);
while (cur_p != sz(ori_p)) {
if (cur_q!=sz(ori_q) && !in_between2(cur_p, cur_q, pict_p, pict_q)) {
break;
}
int old_p = cur_p;
cur_p = same(cur_p, ori_p, 1);
if (in_between(old_p, cur_p, pict_p, pict_q)) {return false;}
cur_p = next(cur_p, ori_p, 0);
}
if (cur_p == sz(ori_p) && cur_q != sz(ori_q)) return false;
if (cur_q == sz(ori_q) && cur_p == sz(ori_p)) return true;
//we come from the break
cur_q = same(cur_q, ori_q, 1);
cur_p = same(cur_p, ori_p, 1);
while (cur_q != sz(ori_q)) {
if (!in_between2(cur_q, cur_p, pict_q, pict_p)) {break;}
int old_q = cur_q;
cur_q = next(cur_q, ori_q, 0);
if (in_between(old_q, cur_q, pict_q, pict_p)) return false;
cur_q = same(cur_q, ori_q, 1);
}
if (cur_q == sz(ori_q) && cur_p != sz(ori_p)) return false;
if (cur_q == sz(ori_q) && cur_p == sz(ori_p)) return true;
}
return false;
}
void print_state(pi e) {
cout << binrep(e.X) sp '(';
printcoll(orient[lines(e.X)][e.Y]);
cout << ')';
}
int main() {
cin >> m;
int nr_pos = (1<<(m-1))-1;
cout << "p\tq\tor(p)\tor(q)\n";
rep(p, 1, nr_pos+1) {
int lp = lines(p);
rep(q, 1, nr_pos+1) {
if (!forbidden(p, q)) {
int lq = lines(q);
cout << binrep(p) tb binrep(q);
rep(o, 1, sz(orient[lp])) {
cout << "\n\t\t";
printcoll(orient[lp][o]);
cout << '\t';
rep(r, 1, sz(orient[lq])) {
printcoll(orient[lq][r]);
if (match_states(p, q, orient[lp][o], orient[lq][r])) cout << '*';
cout << '\t';
}
}
cout << '\n';
}
}
}
}
| frits-scholer/pr | pr237/transitions.cpp | C++ | gpl-3.0 | 8,863 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.watabou.pixeldungeon.scenes;
import android.content.Intent;
import com.nyrds.pixeldungeon.ml.R;
import com.nyrds.platform.game.Game;
import com.nyrds.platform.game.RemixedDungeon;
import com.nyrds.platform.input.Touchscreen.Touch;
import com.nyrds.platform.util.StringsManager;
import com.nyrds.util.GuiProperties;
import com.watabou.noosa.Camera;
import com.watabou.noosa.Image;
import com.watabou.noosa.Scene;
import com.watabou.noosa.Text;
import com.watabou.noosa.TouchArea;
import com.watabou.pixeldungeon.effects.Flare;
import com.watabou.pixeldungeon.ui.Archs;
import com.watabou.pixeldungeon.ui.ExitButton;
import com.watabou.pixeldungeon.ui.Icons;
import com.watabou.pixeldungeon.ui.Window;
public class AboutScene extends PixelScene {
private static String getTXT() {
return StringsManager.getVar(R.string.AboutScene_Txt_Intro) + "\n\n"
+ StringsManager.getVar(R.string.AboutScene_Code) + " " + StringsManager.getVar(R.string.AboutScene_Code_Names) + "\n\n"
+ StringsManager.getVar(R.string.AboutScene_Graphics) + " " + StringsManager.getVar(R.string.AboutScene_Graphics_Names) + "\n\n"
+ StringsManager.getVar(R.string.AboutScene_Music) + " " + StringsManager.getVar(R.string.AboutScene_Music_Names) + "\n\n"
+ StringsManager.getVar(R.string.AboutScene_Sound) + " " + StringsManager.getVar(R.string.AboutScene_Sound_Names) + "\n\n"
+ StringsManager.getVar(R.string.AboutScene_Thanks) + " " + StringsManager.getVar(R.string.AboutScene_Thanks_Names) + "\n\n"
+ StringsManager.getVar(R.string.AboutScene_Email_Us);
}
private static String getTRN() {
return StringsManager.getVar(R.string.AboutScene_Translation) + "\n\t" + StringsManager.getVar(R.string.AboutScene_Translation_Names);
}
private Text createTouchEmail(final String address, Text text2)
{
Text text = createText(address, text2);
text.hardlight( Window.TITLE_COLOR );
TouchArea area = new TouchArea( text ) {
@Override
protected void onClick( Touch touch ) {
Intent intent = new Intent( Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{address} );
intent.putExtra(Intent.EXTRA_SUBJECT, StringsManager.getVar(R.string.app_name));
Game.instance().startActivity( Intent.createChooser(intent, StringsManager.getVar(R.string.AboutScene_Snd)) );
}
};
add(area);
return text;
}
private Text createTouchLink(final String address, Text visit)
{
Text text = createText(address, visit);
text.hardlight( Window.TITLE_COLOR );
TouchArea area = new TouchArea( text ) {
@Override
protected void onClick( Touch touch ) {
Game.instance().openUrl(StringsManager.getVar(R.string.AboutScene_OurSite), address);
}
};
add(area);
return text;
}
private void placeBellow(Text elem, Text upper)
{
elem.x = upper.x;
elem.y = upper.y + upper.height();
}
private Text createText(String text, Text upper)
{
Text multiline = createMultiline( text, GuiProperties.regularFontSize() );
multiline.maxWidth(Camera.main.width * 5 / 6);
add( multiline );
if(upper!=null){
placeBellow(multiline, upper);
}
return multiline;
}
@Override
public void create() {
super.create();
Text text = createText(getTXT(), null );
text.camera = uiCamera;
text.x = align( (Camera.main.width - text.width()) / 2 );
text.y = align( (Camera.main.height - text.height()) / 3 );
Text email = createTouchEmail(StringsManager.getVar(R.string.AboutScene_Mail), text);
Text visit = createText(StringsManager.getVar(R.string.AboutScene_OurSite), email);
Text site = createTouchLink(StringsManager.getVar(R.string.AboutScene_Lnk), visit);
createText("\n"+ getTRN(), site);
Image nyrdie = Icons.NYRDIE.get();
nyrdie.x = align( text.x + (text.width() - nyrdie.width) / 2 );
nyrdie.y = text.y - nyrdie.height - 8;
add( nyrdie );
TouchArea area = new TouchArea( nyrdie ) {
private int clickCounter = 0;
@Override
protected void onClick( Touch touch ) {
clickCounter++;
if(clickCounter > 11) {
return;
}
if(clickCounter>10) {
Game.toast("Levels test mode enabled");
Scene.setMode("levelsTest");
return;
}
if(clickCounter>7) {
Game.toast("Are you sure?");
return;
}
if(clickCounter>3) {
Game.toast("%d", clickCounter);
}
}
};
add(area);
new Flare( 7, 64 ).color( 0x332211, true ).show( nyrdie, 0 ).angularSpeed = -20;
Archs archs = new Archs();
archs.setSize( Camera.main.width, Camera.main.height );
addToBack( archs );
ExitButton btnExit = new ExitButton();
btnExit.setPos( Camera.main.width - btnExit.width(), 0 );
add( btnExit );
fadeIn();
}
@Override
protected void onBackPressed() {
RemixedDungeon.switchNoFade( TitleScene.class );
}
}
| NYRDS/pixel-dungeon-remix | RemixedDungeon/src/main/java/com/watabou/pixeldungeon/scenes/AboutScene.java | Java | gpl-3.0 | 5,609 |
/**
* @file oglplus/text/pango_cairo/layout.hpp
* @brief Pango/Cairo-based text rendering - layout.
*
* @author Matus Chochlik
*
* Copyright 2010-2013 Matus Chochlik. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#pragma once
#ifndef OGLPLUS_TEXT_PANGO_CAIRO_LAYOUT_HPP
#define OGLPLUS_TEXT_PANGO_CAIRO_LAYOUT_HPP
#include <oglplus/config.hpp>
#include <oglplus/vector.hpp>
#include <oglplus/text/common.hpp>
#include <oglplus/text/pango_cairo/fwd.hpp>
#include <oglplus/text/pango_cairo/handle.hpp>
#include <oglplus/text/pango_cairo/layout_storage.hpp>
#include <oglplus/texture.hpp>
namespace oglplus {
namespace text {
class PangoCairoLayout
{
private:
friend class PangoCairoRenderer;
PangoCairoRendering& _parent;
PangoCairoFont _font;
const GLsizei _capacity;
int _curr_width;
int _width;
int _height;
Vec4f _log_coords, _tex_coords;
PangoCairoHandle< ::cairo_surface_t*> _surface;
PangoCairoLayoutData _data;
PangoCairoLayout(const PangoCairoLayout&);
public:
PangoCairoLayout(
PangoCairoRendering& parent,
const PangoCairoFont& font,
GLsizei capacity
): _parent(parent)
, _font(font)
, _capacity(capacity)
, _curr_width(0)
, _width(font._essence->ApproxGlyphWidth()*_capacity*1.2f)
, _height(font._essence->Height())
, _surface(
::cairo_image_surface_create(CAIRO_FORMAT_A8, _width, _height),
::cairo_surface_destroy
)
{
PangoCairoAllocateLayoutData(_parent, _data, _width, _height);
}
PangoCairoLayout(PangoCairoLayout&& tmp)
: _parent(tmp._parent)
, _font(std::move(tmp._font))
, _capacity(tmp._capacity)
, _curr_width(tmp._curr_width)
, _width(tmp._width)
, _height(tmp._height)
, _surface(std::move(tmp._surface))
, _data(std::move(tmp._data))
{ }
~PangoCairoLayout(void)
{
PangoCairoDeallocateLayoutData(_parent, _data);
}
TextureUnitSelector Use(void) const
{
return PangoCairoUseLayoutData(_parent, _data);
}
GLsizei Capacity(void) const
{
return _capacity;
}
GLfloat Width(void) const
{
return GLfloat(_curr_width) / GLfloat(_height);
}
void Set(const char* c_str, const std::size_t size)
{
// create a cairo renderer
PangoCairoHandle< ::cairo_t*> cairo(
::cairo_create(_surface),
::cairo_destroy
);
// clear the surface
::cairo_save(cairo);
::cairo_set_source_rgba(cairo, 0, 0, 0, 0);
::cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);
::cairo_paint(cairo);
::cairo_restore(cairo);
// if the new text string is empty, quit
if(size == 0) return;
// create a layout
PangoCairoHandle< ::PangoLayout*, ::gpointer> layout(
::pango_cairo_create_layout(cairo),
::g_object_unref
);
// set the text
::pango_layout_set_text(layout, c_str, size);
::pango_layout_set_font_description(
layout,
_font._essence->_font_desc
);
// check the required layout dimensions
int req_width = 0;
int req_height = 0;
{
::PangoRectangle ink_rect, log_rect;
::pango_layout_get_extents(
layout,
&ink_rect,
&log_rect
);
req_width = log_rect.width/PANGO_SCALE;
req_height = log_rect.height/PANGO_SCALE;
_curr_width = req_width;
}
// resize if necessary
if((_width < req_width) || (_height < req_height))
{
_width = req_width;
_height = req_height;
_surface.replace(
::cairo_image_surface_create(
CAIRO_FORMAT_A8,
_width,
_height
)
);
cairo.replace(::cairo_create(_surface));
layout.replace(::pango_cairo_create_layout(cairo));
PangoCairoDeallocateLayoutData(_parent, _data);
PangoCairoAllocateLayoutData(
_parent,
_data,
_width,
_height
);
}
int baseline = pango_layout_get_baseline(layout)/PANGO_SCALE;
_log_coords = Vec4f(
0.0f, // left bearing
GLfloat(_curr_width)/GLfloat(_height), // right bearing
GLfloat(baseline)/GLfloat(_height), // ascent
GLfloat(_height-baseline)/GLfloat(_height) // descent
);
_tex_coords = Vec4f(
0.0f, // origin x
0.0f, // origin y
_curr_width, // width
_height // height
);
// render the text
::cairo_new_path(cairo);
::cairo_move_to(cairo, 0, 0);
::cairo_set_line_width(cairo, 0.5);
::pango_cairo_update_layout(cairo, layout);
::pango_cairo_layout_path(cairo, layout);
::cairo_fill(cairo);
::cairo_surface_flush(_surface);
// update the data
PangoCairoInitializeLayoutData(
_parent,
_data,
::cairo_image_surface_get_width(_surface),
::cairo_image_surface_get_height(_surface),
::cairo_image_surface_get_data(_surface)
);
}
void Set(const StrLit& string_literal)
{
Set(string_literal.c_str(), string_literal.size());
}
void Set(const String& string)
{
Set(string.c_str(), string.size());
}
void Set(const CodePoint* code_points, const GLsizei length)
{
std::vector<char> str;
CodePointsToUTF8(code_points, length, str);
Set(str.data(), str.size());
}
};
} // namespace text
} // namespace oglplus
#endif // include guard
| zolkko/roboface | third_party/oglplus/text/pango_cairo/layout.hpp | C++ | gpl-3.0 | 5,029 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the strings used by backup
*
* @package moodlecore
* @copyright 2010 Eloy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['autoactivedisabled'] = 'Disabled';
$string['autoactiveenabled'] = 'Enabled';
$string['autoactivemanual'] = 'Manual';
$string['autoactivedescription'] = 'Choose whether or not to do automated backups. If manual is selected automated backups will be possible only by through the automated backups CLI script. This can be done either manually on the command line or through cron.';
$string['automatedbackupschedule'] = 'Schedule';
$string['automatedbackupschedulehelp'] = 'Choose which days of the week to perform automated backups.';
$string['automatedbackupsinactive'] = 'Automated backups haven\'t been enabled by the site admin';
$string['automatedbackupstatus'] = 'Automated backup status';
$string['automatedsetup'] = 'Automated backup setup';
$string['automatedsettings'] = 'Automated backup settings';
$string['automatedstorage'] = 'Automated backup storage';
$string['automatedstoragehelp'] = 'Choose the location where you want backups to be stored when they are automatically created.';
$string['backupactivity'] = 'Backup activity: {$a}';
$string['backupcourse'] = 'Backup course: {$a}';
$string['backupcoursedetails'] = 'Course details';
$string['backupcoursesection'] = 'Section: {$a}';
$string['backupcoursesections'] = 'Course sections';
$string['backupdate'] = 'Date taken';
$string['backupdetails'] = 'Backup details';
$string['backupdetailsnonstandardinfo'] = 'The selected file is not a standard Moodle backup file. The restore process will try to convert the backup file into the standard format and then restore it.';
$string['backupformat'] = 'Format';
$string['backupformatmoodle1'] = 'Moodle 1';
$string['backupformatmoodle2'] = 'Moodle 2';
$string['backupformatimscc1'] = 'IMS Common Cartridge 1.0';
$string['backupformatimscc11'] = 'IMS Common Cartridge 1.1';
$string['backupformatunknown'] = 'Unknown format';
$string['backupmode'] = 'Mode';
$string['backupmode10'] = 'General';
$string['backupmode20'] = 'Import';
$string['backupmode30'] = 'Hub';
$string['backupmode40'] = 'Same site';
$string['backupmode50'] = 'Automated';
$string['backupmode60'] = 'Converted';
$string['backupsection'] = 'Backup course section: {$a}';
$string['backupsettings'] = 'Backup settings';
$string['backupsitedetails'] = 'Site details';
$string['backupstage1action'] = 'Next';
$string['backupstage2action'] = 'Next';
$string['backupstage4action'] = 'Perform backup';
$string['backupstage8action'] = 'Continue';
$string['backupstage16action'] = 'Continue';
$string['backuptype'] = 'Type';
$string['backuptypeactivity'] = 'Activity';
$string['backuptypecourse'] = 'Course';
$string['backupversion'] = 'Backup version';
$string['cannotfindassignablerole'] = 'The {$a} role in the backup file cannot be mapped to any of the roles that you are allowed to assign.';
$string['choosefilefromcoursebackup'] = 'Course backup area';
$string['choosefilefromcoursebackup_help'] = 'When backup courses using default settings, backup files will be stored here';
$string['choosefilefromuserbackup'] = 'User private backup area';
$string['choosefilefromuserbackup_help'] = 'When backup courses with "Anonymize user information" option ticked, backup files will be stored here';
$string['choosefilefromactivitybackup'] = 'Activity backup area';
$string['choosefilefromactivitybackup_help'] = 'When backup activities using default settings, backup files will be stored here';
$string['choosefilefromautomatedbackup'] = 'Automated backups';
$string['choosefilefromautomatedbackup_help'] = 'Contains automatically generated backups.';
$string['configgeneralactivities'] = 'Sets the default for including activities in a backup.';
$string['configgeneralanonymize'] = 'If enabled all information pertaining to users will be anonymised by default.';
$string['configgeneralblocks'] = 'Sets the default for including blocks in a backup.';
$string['configgeneralcomments'] = 'Sets the default for including comments in a backup.';
$string['configgeneralfilters'] = 'Sets the default for including filters in a backup.';
$string['configgeneralhistories'] = 'Sets the default for including user history within a backup.';
$string['configgenerallogs'] = 'If enabled logs will be included in backups by default.';
$string['configgeneralroleassignments'] = 'If enabled by default roles assignments will also be backed up.';
$string['configgeneraluserscompletion'] = 'If enabled user completion information will be included in backups by default.';
$string['configgeneraluserfiles'] = 'Sets the default for whether user files will be included in backups.';
$string['configgeneralusers'] = 'Sets the default for whether to include users in backups.';
$string['confirmcancel'] = 'Cancel backup';
$string['confirmcancelquestion'] = 'Are you sure you wish to cancel?
Any information you have entered will be lost.';
$string['confirmcancelyes'] = 'Cancel';
$string['confirmcancelno'] = 'Stay';
$string['confirmnewcoursecontinue'] = 'New course warning';
$string['confirmnewcoursecontinuequestion'] = 'A temporary (hidden) course will be created by the course restoration process. To abort restoration click cancel. Do not close the browser while restoring.';
$string['coursecategory'] = 'Category the course will be restored into';
$string['courseid'] = 'Original ID';
$string['coursesettings'] = 'Course settings';
$string['coursetitle'] = 'Title';
$string['currentstage1'] = 'Initial settings';
$string['currentstage2'] = 'Schema settings';
$string['currentstage4'] = 'Confirmation and review';
$string['currentstage8'] = 'Perform backup';
$string['currentstage16'] = 'Complete';
$string['dependenciesenforced'] = 'Your settings have been altered due to unmet dependencies';
$string['enterasearch'] = 'Enter a search';
$string['errorfilenamerequired'] = 'You must enter a valid filename for this backup';
$string['errorfilenamemustbezip'] = 'The filename you enter must be a ZIP file and have the .mbz extension';
$string['errorminbackup20version'] = 'This backup file has been created with one development version of Moodle backup ({$a->backup}). Minimum required is {$a->min}. Cannot be restored.';
$string['errorrestorefrontpage'] = 'Restoring over front page is not allowed.';
$string['errorinvalidformat'] = 'Unknown backup format';
$string['errorinvalidformatinfo'] = 'The selected file is not a valid Moodle backup file and can\'t be restored.';
$string['executionsuccess'] = 'The backup file was successfully created.';
$string['filename'] = 'Filename';
$string['generalactivities'] = 'Include activities';
$string['generalanonymize'] = 'Anonymise information';
$string['generalbackdefaults'] = 'General backup defaults';
$string['generalblocks'] = 'Include blocks';
$string['generalcomments'] = 'Include comments';
$string['generalfilters'] = 'Include filters';
$string['generalhistories'] = 'Include histories';
$string['generalgradehistories'] = 'Include histories';
$string['generallogs'] = 'Include logs';
$string['generalroleassignments'] = 'Include role assignments';
$string['generaluserscompletion'] = 'Include user completion information';
$string['generaluserfiles'] = 'Include user files';
$string['generalusers'] = 'Include users';
$string['importfile'] = 'Import a backup file';
$string['importbackupstage1action'] = 'Next';
$string['importbackupstage2action'] = 'Next';
$string['importbackupstage4action'] = 'Perform import';
$string['importbackupstage8action'] = 'Continue';
$string['importbackupstage16action'] = 'Continue';
$string['importcurrentstage0'] = 'Course selection';
$string['importcurrentstage1'] = 'Initial settings';
$string['importcurrentstage2'] = 'Schema settings';
$string['importcurrentstage4'] = 'Confirmation and review';
$string['importcurrentstage8'] = 'Perform import';
$string['importcurrentstage16'] = 'Complete';
$string['importsuccess'] = 'Import complete. Click continue to return to the course.';
$string['includeactivities'] = 'Include:';
$string['includeditems'] = 'Included items:';
$string['includesection'] = 'Section {$a}';
$string['includeuserinfo'] = 'User data';
$string['locked'] = 'Locked';
$string['lockedbypermission'] = 'You don\'t have sufficient permissions to change this setting';
$string['lockedbyconfig'] = 'This setting has been locked by the default backup settings';
$string['lockedbyhierarchy'] = 'Locked by dependencies';
$string['managefiles'] = 'Manage backup files';
$string['moodleversion'] = 'Moodle version';
$string['moreresults'] = 'There are too many results, enter a more specific search.';
$string['nomatchingcourses'] = 'There are no courses to display';
$string['norestoreoptions'] = 'There are no categories or existing courses you can restore to.';
$string['originalwwwroot'] = 'URL of backup';
$string['previousstage'] = 'Previous';
$string['qcategory2coursefallback'] = 'The questions category "{$a->name}", originally at system/course category context in backup file, will be created at course context by restore';
$string['qcategorycannotberestored'] = 'The questions category "{$a->name}" cannot be created by restore';
$string['question2coursefallback'] = 'The questions category "{$a->name}", originally at system/course category context in backup file, will be created at course context by restore';
$string['questionegorycannotberestored'] = 'The questions "{$a->name}" cannot be created by restore';
$string['restoreactivity'] = 'Restore activity';
$string['restorecourse'] = 'Restore course';
$string['restorecoursesettings'] = 'Course settings';
$string['restoreexecutionsuccess'] = 'The course was restored successfully, clicking the continue button below will take you to view the course you restored.';
$string['restorenewcoursefullname'] = 'New course name';
$string['restorenewcourseshortname'] = 'New course short name';
$string['restorenewcoursestartdate'] = 'New start date';
$string['restorerootsettings'] = 'Restore settings';
$string['restoresection'] = 'Restore section';
$string['restorestage1'] = 'Confirm';
$string['restorestage1action'] = 'Next';
$string['restorestage2'] = 'Destination';
$string['restorestage2action'] = 'Next';
$string['restorestage4'] = 'Settings';
$string['restorestage4action'] = 'Next';
$string['restorestage8'] = 'Schema';
$string['restorestage8action'] = 'Next';
$string['restorestage16'] = 'Review';
$string['restorestage16action'] = 'Perform restore';
$string['restorestage32'] = 'Process';
$string['restorestage32action'] = 'Continue';
$string['restorestage64'] = 'Complete';
$string['restorestage64action'] = 'Continue';
$string['restoretarget'] = 'Restore target';
$string['restoretocourse'] = 'Restore to course: ';
$string['restoretocurrentcourse'] = 'Restore into this course';
$string['restoretocurrentcourseadding'] = 'Merge the backup course into this course';
$string['restoretocurrentcoursedeleting'] = 'Delete the contents of this course and then restore';
$string['restoretoexistingcourse'] = 'Restore into an existing course';
$string['restoretoexistingcourseadding'] = 'Merge the backup course into the existing course';
$string['restoretoexistingcoursedeleting'] = 'Delete the contents of the existing course and then restore';
$string['restoretonewcourse'] = 'Restore as a new course';
$string['restoringcourse'] = 'Course restoration in progress';
$string['restoringcourseshortname'] = 'restoring';
$string['restorerolemappings'] = 'Restore role mappings';
$string['rootsettings'] = 'Backup settings';
$string['rootsettingusers'] = 'Include enrolled users';
$string['rootsettinganonymize'] = 'Anonymize user information';
$string['rootsettingroleassignments'] = 'Include user role assignments';
$string['rootsettinguserfiles'] = 'Include user files';
$string['rootsettingactivities'] = 'Include activities';
$string['rootsettingblocks'] = 'Include blocks';
$string['rootsettingfilters'] = 'Include filters';
$string['rootsettingcomments'] = 'Include comments';
$string['rootsettinguserscompletion'] = 'Include user completion details';
$string['rootsettinglogs'] = 'Include course logs';
$string['rootsettinggradehistories'] = 'Include grade history';
$string['rootsettingimscc1'] = 'Convert to IMS Common Cartridge 1.0';
$string['rootsettingimscc11'] = 'Convert to IMS Common Cartridge 1.1';
$string['storagecourseonly'] = 'Course backup filearea';
$string['storagecourseandexternal'] = 'Course backup filearea and the specified directory';
$string['storageexternalonly'] = 'Specified directory for automated backups';
$string['sectionincanduser'] = 'Included in backup along with user information';
$string['sectioninc'] = 'Included in backup (no user information)';
$string['sectionactivities'] = 'Activities';
$string['selectacategory'] = 'Select a category';
$string['selectacourse'] = 'Select a course';
$string['setting_overwriteconf'] = 'Overwrite course configuration';
$string['setting_course_fullname'] = 'Course name';
$string['setting_course_shortname'] = 'Course short name';
$string['setting_course_startdate'] = 'Course startdate';
$string['totalcategorysearchresults'] = 'Total categories: {$a}';
$string['totalcoursesearchresults'] = 'Total courses: {$a}';
| bourey/moodle | lang/en/backup.php | PHP | gpl-3.0 | 13,893 |
package au.com.jc.weather.lga;
/**
* Represents an air mass.
* Just holds temp currently, but should hold humidity etc.
* Created by john on 20/03/16.
*/
public class Mass {
public double temp=20;
}
| jacrify/weather | src/main/java/au/com/jc/weather/lga/Mass.java | Java | gpl-3.0 | 211 |
package info.guardianproject.louder;
/**
* Created by n8fr8 on 1/30/17.
* From here: http://stackoverflow.com/questions/17503409/stream-audio-from-internal-microphone-to-3-5mm-headphone-jack
*/
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder.AudioSource;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class TOnePlayer extends Thread {
private Thread T1;
public boolean Okay = true;
public AudioTrack aud;
private static int[] mSampleRates = new int[] { 22050 };
private final static int DEFAULT_RATE = 22050;
private final static int BUFFER = 100;
private byte[] buffer = new byte[100];
// private static int MIN_BUFFER_SIZE = DEFAULT_RATE;
private boolean isPlayer = false;
private ByteArrayInputStream bais;
public TOnePlayer (ByteArrayInputStream bais)
{
this.bais = bais;
}
@Override
public void run() {
Log.e("Play Audio", "Start");
aud = new AudioTrack(AudioManager.STREAM_MUSIC, DEFAULT_RATE,
AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, AudioTrack.getMinBufferSize(DEFAULT_RATE, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT), AudioTrack.MODE_STREAM);
if (aud.getState() != AudioTrack.STATE_INITIALIZED) {
aud = new AudioTrack(AudioManager.STREAM_MUSIC, DEFAULT_RATE,
AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, AudioTrack.getMinBufferSize(DEFAULT_RATE, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT), AudioTrack.MODE_STREAM);
}
aud.play();
while(Okay){
try {
int len = bais.read(buffer);
if (len != -1)
aud.write(buffer, 0, len);
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
aud.flush();
}
public void stopTone ()
{
Okay = false;
}
} | n8fr8/LittleBitLouder | app/src/main/java/info/guardianproject/louder/TOnePlayer.java | Java | gpl-3.0 | 2,228 |
package fi.otavanopisto.pyramus.ui.base;
import org.junit.Test;
import fi.otavanopisto.pyramus.SqlAfter;
import fi.otavanopisto.pyramus.SqlBefore;
import fi.otavanopisto.pyramus.ui.AbstractUITest;
public class SystemPagesStudentPermissionsTestsBase extends AbstractUITest {
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testPluginsPagePermission() throws InterruptedException{
assertStudentDenied("/system/plugins.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testReindexHibernateObjectsPagePermission() throws InterruptedException{
assertStudentDenied("/system/reindexhibernateobjects.page");
}
// TODO: Wot m8?
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testInitialDataPagePermission() throws InterruptedException{
assertStudentDenied("/system/initialdata.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testImportCsvPagePermission() throws InterruptedException{
assertStudentDenied("/system/importcsv.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testImportDataPagePermission() throws InterruptedException{
assertStudentDenied("/system/importdata.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testImportScriptedDataPagePermission() throws InterruptedException{
assertStudentDenied("/system/importscripteddata.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testImportReportPagePermission() throws InterruptedException{
assertStudentDenied("/system/importreport.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardAdminPasswordPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/adminpassword.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardAcademictermsPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/academicterms.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardIndexPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/index.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardContactTypesPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/contacttypes.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardExaminationTypesPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/examinationtypes.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardCourseParticipationTypesPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/courseparticipationtypes.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardCourseStatesPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/coursesstate.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardEducationSubTypesPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/educationsubtypes.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardEducationTypesPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/educationtypes.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardLanguagesPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/languages.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardMunicipalitiesPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/municipalities.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardNationalitiesPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/nationalities.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardSchoolFieldsPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/schoolfields.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardSchoolsPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/schools.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardStudentActivityTypesPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/studentactivity.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardStudentEducationalLevelsPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/studenteducationallevels.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardStudyEndReasonsPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/studyendreasons.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardStudyProgrammeCategoriesPagePermission() throws InterruptedException{
assertStudentDenied("system/setupwizard/studyprogrammecategories.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardStudyProgrammesPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/studyprogrammes.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardSubjectsPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/subjects.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardTimeUnitsPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/timeunits.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSetupWizardFinalPagePermission() throws InterruptedException{
assertStudentDenied("/system/setupwizard/final.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testElementCheatSheetPagePermission() throws InterruptedException{
assertStudentDenied("/system/elementcheatsheet.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testDebugDataPagePermission() throws InterruptedException{
assertStudentDenied("/system/debugdata.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testSettingsPagePermission() throws InterruptedException{
assertStudentDenied("/system/systemsettings.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testInfoPagePermission() throws InterruptedException{
assertStudentDenied("/system/systeminfo.page");
}
@Test
@SqlBefore ("sql/basic-before.sql")
@SqlAfter ("sql/basic-after.sql")
public void testClientapplicationsPagePermission() throws InterruptedException{
assertStudentDenied("/system/clientapplications.page");
}
}
| otavanopisto/pyramus | pyramus/src/test/java/fi/otavanopisto/pyramus/ui/base/SystemPagesStudentPermissionsTestsBase.java | Java | gpl-3.0 | 8,267 |
<?php
/************************************************************************
* This file is part of FoxCRM.
*
* FoxCRM - Open Source CRM application.
* Copyright (C) 2014-2015 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko
* Website: http://www.espocrm.com
*
* FoxCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FoxCRM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FoxCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
namespace Fox\Repositories;
use Fox\ORM\Entity;
class Import extends \Fox\Core\ORM\Repositories\RDB
{
public function findRelated(Entity $entity, $link, $selectParams)
{
$entityType = $entity->get('entityType');
$selectParams['customJoin'] .= $this->getRelatedJoin($entity, $link);
return $this->getEntityManager()->getRepository($entityType)->find($selectParams);
}
protected function getRelatedJoin(Entity $entity, $link)
{
$entityType = $entity->get('entityType');
$pdo = $this->getEntityManager()->getPDO();
$table = $this->getEntityManager()->getQuery()->toDb($entityType);
$part = "0";
switch ($link) {
case 'imported':
$part = "import_entity.is_imported = 1";
break;
case 'duplicates':
$part = "import_entity.is_duplicate = 1";
break;
case 'updated':
$part = "import_entity.is_updated = 1";
break;
}
$sql = "
JOIN import_entity ON
import_entity.import_id = " . $pdo->quote($entity->id) . " AND
import_entity.entity_type = " . $pdo->quote($entity->get('entityType')) . " AND
import_entity.entity_id = " . $table . ".id AND
".$part."
";
return $sql;
}
public function countRelated(Entity $entity, $link, $selectParams)
{
$entityType = $entity->get('entityType');
$selectParams['customJoin'] .= $this->getRelatedJoin($entity, $link);
return $this->getEntityManager()->getRepository($entityType)->count($selectParams);
}
protected function afterRemove(Entity $entity, array $options)
{
if ($entity->get('fileId')) {
$attachment = $this->getEntityManager()->getEntity('Attachment', $entity->get('fileId'));
if ($attachment) {
$this->getEntityManager()->removeEntity($attachment);
}
}
$pdo = $this->getEntityManager()->getPDO();
$sql = "DELETE FROM import_entity WHERE import_id = :importId";
$sth = $pdo->prepare($sql);
$sth->bindValue(':importId', $entity->id);
$sth->execute();
parent::afterRemove($entity, $options);
}
}
| ilovefox8/cc2crm | application/Fox/Repositories/Import.php | PHP | gpl-3.0 | 3,312 |
<?php
/**
* PHP version 5.5
*
* @category DataFixtures
* @package Core
* @author Maxence Perrin <mperrin@darkmira.fr>
* @license Darkmira <darkmira@darkmira.fr>
* @link www.darkmira.fr
*/
namespace ZCEPracticeTest\Core\DataFixtures\Test;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use ZCEPracticeTest\Core\Entity\Quiz;
class QuizLoad extends AbstractFixture implements OrderedFixtureInterface
{
/**
* Load default dataset of question
* @param \Doctrine\Common\Persistence\ObjectManager $objectManager
*/
public function load(ObjectManager $objectManager)
{
for ($i = 0; $i < 2; $i++) {
$o = new Quiz();
$this->setReference('quiz-'.$i, $o);
$objectManager->persist($o);
}
$objectManager->flush();
}
/**
* @return int
*/
public function getOrder()
{
return 0;
}
}
| Antione7/ZCEPracticeTest | src/ZCEPracticeTest/Core/DataFixtures/Test/QuizLoad.php | PHP | gpl-3.0 | 1,020 |
namespace GamesReviews.Console.Client
{
public class UseCaseTwo
: BaseUseCase
{
public void Run()
{
System.Console.WriteLine("\n2. As a gamer I want to vote for my favorite games.\n");
System.Console.WriteLine("Todo: Need to clarify what 'to vote for' means?");
}
}
} | tschroedter/csharp_examples | InterviewTests/Asl/GamesReviews.Console/Client/UseCaseTwo.cs | C# | gpl-3.0 | 339 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Primitive
long
Description
A long integer
SourceFiles
longIO.C
\*---------------------------------------------------------------------------*/
#ifndef long_H
#define long_H
#include "word.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
class Istream;
class Ostream;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
//- Return a string representation of a long
word name(long);
// * * * * * * * * * * * * * * * IOstream Operators * * * * * * * * * * * * //
long readLong(Istream&);
Istream& operator>>(Istream&, long&);
Ostream& operator<<(Ostream&, const long);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| OpenFOAM/OpenFOAM-2.0.x | src/OpenFOAM/primitives/ints/long/long.H | C++ | gpl-3.0 | 2,018 |
/*************************************************************************
* Copyright 2009-2013 Eucalyptus Systems, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
* Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
* CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need
* additional information or have any questions.
************************************************************************/
package com.eucalyptus.auth;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.NoSuchElementException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import org.bouncycastle.util.encoders.Base64;
import com.eucalyptus.auth.entities.ServerCertificateEntity;
import com.eucalyptus.auth.principal.Account;
import com.eucalyptus.auth.principal.User;
import com.eucalyptus.auth.principal.UserFullName;
import com.eucalyptus.component.auth.SystemCredentials;
import com.eucalyptus.component.id.Euare;
import com.eucalyptus.crypto.Ciphers;
import com.eucalyptus.crypto.Crypto;
import com.eucalyptus.crypto.util.PEMFiles;
import com.eucalyptus.entities.Entities;
import com.eucalyptus.entities.TransactionResource;
import com.eucalyptus.util.EucalyptusCloudException;
import com.eucalyptus.util.Exceptions;
import com.eucalyptus.util.OwnerFullName;
import com.eucalyptus.util.RestrictedTypes.Resolver;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
/**
* @author Sang-Min Park
*
*/
public class ServerCertificates {
public static boolean isCertValid(final String certBody, final String pk, final String certChain){
try{
final X509Certificate cert = PEMFiles.getCert(certBody.getBytes( Charsets.UTF_8 ));
if(cert==null)
throw new EucalyptusCloudException("Malformed cert");
final KeyPair kp = PEMFiles.getKeyPair(pk.getBytes( Charsets.UTF_8 ));
if(kp == null)
throw new EucalyptusCloudException("Malformed pk");
}catch(final Exception ex){
return false;
}
return true;
}
@Resolver( ServerCertificateEntity.class )
public enum Lookup implements Function<String, ServerCertificateEntity> {
INSTANCE;
@Override
public ServerCertificateEntity apply( final String arn ) {
try{
//String.format("arn:aws:iam::%s:server-certificate%s%s", this.owningAccount.getAccountNumber(), path, this.certName);
// extract account id from arn and find account
if(!arn.startsWith("arn:aws:iam::"))
throw new EucalyptusCloudException("malformed arn");
// get admin name of the account
String token = arn.substring("arn:aws:iam::".length());
String acctId = token.substring(0, token.indexOf(":server-certificate"));
final Account acct = Accounts.lookupAccountById(acctId);
final User adminUser = acct.lookupAdmin();
// get certname of the arn
final String prefix =
String.format("arn:aws:iam::%s:server-certificate", acctId);
if(!arn.startsWith(prefix))
throw new EucalyptusCloudException("malformed arn");
String pathAndName = arn.replace(prefix, "");
String certName = pathAndName.substring(pathAndName.lastIndexOf("/")+1);
ServerCertificateEntity found = null;
try ( final TransactionResource db = Entities.transactionFor( ServerCertificateEntity.class ) ) {
found =
Entities.uniqueResult(ServerCertificateEntity.named(UserFullName.getInstance(adminUser), certName));
db.rollback();
} catch(final NoSuchElementException ex){
;
} catch(final Exception ex){
throw ex;
}
return found;
}catch(final Exception ex){
throw Exceptions.toUndeclared(ex);
}
}
}
public enum ToServerCertificate implements
Function<ServerCertificateEntity, ServerCertificate> {
INSTANCE;
@Override
public ServerCertificate apply(ServerCertificateEntity entity) {
try {
final ServerCertificate cert = new ServerCertificate(
Accounts.lookupAccountById(entity.getOwnerAccountNumber()),
entity.getCertName(), entity.getCreationTimestamp());
cert.setCertificatePath(entity.getCertPath());
cert.setCertificateBody(entity.getCertBody());
cert.setCertificateChain(entity.getCertChain());
cert.setCertificateId(entity.getCertId());
byte[] encText = Base64.decode(entity.getPrivateKey());
byte[] iv = Arrays.copyOfRange(encText, 0, 32);
byte[] encPk = Arrays.copyOfRange(encText, 32, encText.length);
byte[] symKeyWrapped = Base64.decode(entity.getSessionKey());
// get session key
final PrivateKey euarePk = SystemCredentials.lookup(Euare.class)
.getPrivateKey();
Cipher cipher = Ciphers.RSA_PKCS1.get();
cipher.init(Cipher.UNWRAP_MODE, euarePk, Crypto.getSecureRandomSupplier().get( ));
SecretKey sessionKey = (SecretKey) cipher.unwrap(symKeyWrapped,
"AES/GCM/NoPadding", Cipher.SECRET_KEY);
cipher = Ciphers.AES_GCM.get();
cipher.init(Cipher.DECRYPT_MODE, sessionKey, new IvParameterSpec(iv), Crypto.getSecureRandomSupplier( ).get( ) );
cert.setPrivateKey(new String(cipher.doFinal(encPk)));
return cert;
} catch (final Exception ex) {
throw Exceptions.toUndeclared(ex);
}
}
}
/// TODO: should think about impact to services using the certificate
public static void updateServerCertificate(final OwnerFullName user,
final String certName, final String newCertName, final String newCertPath)
throws NoSuchElementException, AuthException {
try ( final TransactionResource db = Entities.transactionFor( ServerCertificateEntity.class ) ) {
final ServerCertificateEntity found = Entities.uniqueResult(ServerCertificateEntity.named(user, certName));
try {
if (newCertName != null && newCertName.length() > 0
&& !certName.equals(newCertName))
found.setCertName(newCertName);
} catch (final Exception ex) {
throw new AuthException(AuthException.INVALID_SERVER_CERT_NAME);
}
try {
if (newCertPath != null && newCertPath.length() > 0)
found.setCertPath(newCertPath);
} catch (final Exception ex) {
throw new AuthException(AuthException.INVALID_SERVER_CERT_PATH);
}
Entities.persist(found);
db.commit();
} catch (final Exception ex) {
throw Exceptions.toUndeclared(ex);
}
}
}
| davenpcj5542009/eucalyptus | clc/modules/authentication/src/main/java/com/eucalyptus/auth/ServerCertificates.java | Java | gpl-3.0 | 7,286 |
/*
* Copyright (C) 2015 ikonstas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package pltag.parser.performance;
import edu.stanford.nlp.international.Languages;
import edu.stanford.nlp.international.Languages.Language;
import edu.stanford.nlp.parser.lexparser.TreebankLangParserParams;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.trees.TreeTransformer;
/**
*
* @author konstas
*/
public class BracketPerformance<Widget> extends Performance<String>
{
private final EvalbImpl evalb;
private final TreeTransformer treeCollinizer;
private double totalEvalbF1;
public BracketPerformance()
{
evalb = new EvalbImpl("Evalb LP/LR", true);
TreebankLangParserParams tlpp = Languages.getLanguageParams(Language.English);
tlpp.setInputEncoding("UTF-8");
treeCollinizer = tlpp.collinizer();
}
@Override
public double getAccuracy()
{
return totalEvalbF1;
}
@Override
public double[] add(String predAnalysis, String goldStandard, String name)
{
Tree evalGuess = treeCollinizer.transformTree(Tree.valueOf(predAnalysis));
Tree evalGold = treeCollinizer.transformTree(Tree.valueOf(goldStandard));
// if (evalGold == null || evalGuess == null)
// {
// LogInfo.error(name + ": Cannot compare against a null gold or guess tree!\n");
// return 0.0d;
//
// }
// if (evalGuess.yield().size() != evalGold.yield().size())
// {
// try
// {
// evalGuess = Utils.removeEmptyNodes(evalGuess);
// }
// catch(Exception e)
// {
// LogInfo.error("Example " + name);
// e.printStackTrace();
// }
// }
evalb.evaluate(evalGuess, evalGold, name);
totalEvalbF1 = evalb.getEvalbF1();
return new double[] {evalb.getLastF1()};
}
@Override
public String output()
{
return evalb.summary();
}
}
| sinantie/PLTAG | src/pltag/parser/performance/BracketPerformance.java | Java | gpl-3.0 | 2,696 |
<?php
/* ==========================================================================
remove query strings from static resources
========================================================================== */
function _remove_script_version( $src ){
$parts = explode( '?', $src );
return $parts[0];
}
add_filter( 'script_loader_src', '_remove_script_version', 15, 1 );
add_filter( 'style_loader_src', '_remove_script_version', 15, 1 );
/* ==========================================================================
Async or Defer enqueued scripts
========================================================================== */
// Async load
function async_scripts($url)
{
if ( strpos( $url, '#asyncload') === false )
return $url;
else if ( is_admin() )
return str_replace( '#asyncload', '', $url );
else
return str_replace( '#asyncload', '', $url )."' async='async";
}
add_filter( 'clean_url', 'async_scripts', 11, 1 );
// Defer load
function defer_scripts($url)
{
if ( strpos( $url, '#deferload') === false )
return $url;
else if ( is_admin() )
return str_replace( '#deferload', '', $url );
else
return str_replace( '#deferload', '', $url )."' defer='defer";
}
add_filter( 'clean_url', 'defer_scripts', 11, 1 );
// Example code
function site_scripts() {
global $wp_styles; // Call global $wp_styles variable to add conditional wrapper around ie stylesheet the WordPress way
// Adding Foundation scripts file in the footer
wp_enqueue_script( 'foundation-js', get_template_directory_uri() . '/assets/js/foundation.min.js#deferload', array( 'jquery' ), '6.2.3', true );
// Adding scripts file in the footer
wp_enqueue_script( 'site-js', get_template_directory_uri() . '/assets/js/scripts.min.js#deferload', array( 'jquery' ), '', true );
}
?> | blueocto/code-snippets | wordpress/function-snippets/scripts.php | PHP | gpl-3.0 | 1,846 |
import Box from "./Box";
import Template from "../core/Template";
import Room from "./Room";
export default class Dialog extends Box {
private static instance: Dialog;
private dom: HTMLDivElement;
static get() {
return Dialog.instance;
}
static init() {
if (Dialog.instance) {
return;
}
Dialog.instance = new Dialog();
}
private constructor() {
super();
this.dom = <HTMLDivElement>document.getElementById("dialog-box");
}
showFileDialog(type: "image" | "audio" | "other", fileList: File[]): void {
let template: Template;
switch (type) {
case "image":
template = new Template("dialog/image-file-drop");
break;
case "audio":
template = new Template("dialog/music-file-drop");
template.addLocals("fileNames", fileList.map((v) => v.name));
template.addLocals("acceptable", Room.get().myData.master);
break;
case "other":
template = new Template("dialog/other-file-drop");
break;
}
template.addLocals("fileNames", fileList.map((v) => v.name));
const dialog = template.outputSingleElement();
dialog.getElementsByClassName("ok")[0].addEventListener("click", (event) => {
event.preventDefault();
dialog.classList.remove("enabled");
});
dialog.addEventListener("transitionend", (event) => {
if (Number(window.getComputedStyle(dialog).opacity) === 0
|| Number(window.getComputedStyle(dialog).width) === 0
|| Number(window.getComputedStyle(dialog).height) === 0) {
this.dom.removeChild(dialog);
this.dom.classList.remove("enabled");
}
});
this.dom.appendChild(dialog);
window.getComputedStyle(dialog);
dialog.classList.add("enabled");
this.dom.classList.add("enabled");
}
setTitle(title: string): void {
}
setMessage(message: string): void {
}
} | keika299/soupbowl | assets/scripts/ts/box/Dialog.ts | TypeScript | gpl-3.0 | 2,146 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ********************************************************************************
# Copyright © 2019 jianglin
# File Name: __init__.py
# Author: jianglin
# Email: mail@honmaple.com
# Created: 2019-05-13 16:36:40 (CST)
# Last Update: Wednesday 2019-07-10 19:22:40 (CST)
# By:
# Description:
# ********************************************************************************
from flask import Blueprint
from maple.extension import csrf
from maple.utils import lazyconf
from . import api, config
from .router import FileShowView
site = Blueprint('storage', __name__)
site.add_url_rule(
"/",
defaults={"filename": "default/index.html"},
view_func=FileShowView.as_view("index"),
)
site.add_url_rule(
"/<path:filename>",
view_func=FileShowView.as_view("show"),
)
def init_app(app):
lazyconf(app, config, "STORAGE")
csrf.exempt(site)
api.init_api(site)
app.register_blueprint(site, subdomain=config.SUBDOMAIN)
| honmaple/maple-blog | maple/storage/__init__.py | Python | gpl-3.0 | 1,001 |
package com.neurondigital.nudge;
import android.graphics.Canvas;
import android.view.MotionEvent;
public class Instance {
public float x, y, speedx = 0, speedy = 0, accelerationx = 0, accelerationy = 0;
public Sprite sprite;
Screen screen;
Physics physics = new Physics();
boolean world = true;
/**
* Create new instance
*
* @param sprite
* sprite to draw on screen
* @param x
* x-coordinate to draw instance
* @param y
* y-coordinate to draw instance
* @param screen
* A reference to the main nudge engine screen instance
* @param world
* true if you wish to draw the instance relative to the camera or false if you wish to draw it relative to screen
*/
public Instance(Sprite sprite, float x, float y, Screen screen, boolean world) {
this.sprite = sprite;
this.screen = screen;
this.x = x;
this.y = y;
this.world = world;
}
//update the Object
public void Update() {
x += speedx;
y += speedy;
speedx += accelerationx;
speedy += accelerationy;
}
public void rotate(float direction) {
sprite.rotate(direction);
}
public float getDirection() {
return sprite.getDirection();
}
public int getHeight() {
return sprite.getHeight();
}
public int getWidth() {
return sprite.getWidth();
}
//draw the sprite to screen
public void draw(Canvas canvas) {
//draw image
if (world)
sprite.draw(canvas, screen.ScreenX((int) x), screen.ScreenY((int) y));
else
sprite.draw(canvas, x, y);
if (screen.debug_mode)
physics.drawDebug(canvas);
}
public boolean isTouched(MotionEvent event) {
if (world)
return physics.intersect(screen.ScreenX((int) x), screen.ScreenY((int) y), sprite.getWidth(), (int) sprite.getHeight(), (int) event.getX(), (int) event.getY());
else
return physics.intersect((int) x, (int) y, sprite.getWidth(), (int) sprite.getHeight(), (int) event.getX(), (int) event.getY());
}
public boolean CollidedWith(Instance b) {
if (world)
return physics.intersect(screen.ScreenX((int) x), screen.ScreenY((int) y), sprite.getWidth(), (int) sprite.getHeight(), screen.ScreenX((int) b.x), screen.ScreenY((int) b.y), b.sprite.getWidth(), (int) b.sprite.getHeight());
else
return physics.intersect((int) x, (int) y, sprite.getWidth(), (int) sprite.getHeight(), (int) b.x, (int) b.y, b.sprite.getWidth(), (int) b.sprite.getHeight());
}
}
| Pritesh1G/Dorajump | Jumper/src/com/neurondigital/nudge/Instance.java | Java | gpl-3.0 | 2,405 |
/*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import {DefaultWorkspaceDto} from './default-workspace.dto';
export interface UserDto {
id?: string;
name?: string;
email: string;
groups: {[organizationId: string]: string[]};
defaultWorkspace?: DefaultWorkspaceDto;
agreement?: boolean;
agreementDate?: number;
newsletter?: boolean;
wizardDismissed?: boolean;
lastLoggedIn?: number;
}
| livthomas/Lumeer-web-ui | src/app/core/dto/user.dto.ts | TypeScript | gpl-3.0 | 1,144 |
package com.doctusoft.dsw.client.mvp;
/*
* #%L
* dsweb
* %%
* Copyright (C) 2014 Doctusoft Ltd.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import java.io.Serializable;
import lombok.Getter;
import com.google.common.base.Objects;
/**
* This ties Presenter and AbstractPlace, as known for the GWT MVP framework. In GWT's solution,
* Activities and Places are decoupled. A history tokenizer maps uri fragments to Places, and then an
* activity mapper maps Places to activities. That gives more freedom, but that's not currently necessary
* for our basic needs.
*
* The design of this AbstractPlace class has another flaw. The parametric constructor is used by the actual Presenters to define their places.
* The default constructor is used by the {@link NavigationHandler} to create these places, and it then invokes
* {@link AbstractPlace#parseFragment(String)} to handle any possible parameters.
* GWT MVP uses a Tokenizer for the latter.
*/
public abstract class AbstractPlace<Presenter extends com.doctusoft.dsw.client.mvp.Presenter<Presenter>> implements Serializable {
protected String fragment;
@Getter
private Class<Presenter> presenterClass;
@Getter
private String fragmentRoot;
public void parseFragment(String fragment) {
// do nothing by default
}
public String generateFragment() {
return fragmentRoot;
}
public AbstractPlace(String fragmentRoot, Class<Presenter> presenterClass) {
this.fragmentRoot = fragmentRoot;
this.presenterClass = presenterClass;
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (!obj.getClass().equals(getClass()))
return false;
return Objects.equal(generateFragment(), ((AbstractPlace)obj).generateFragment());
}
}
| Doctusoft/dsweb | dsweb/src/main/java/com/doctusoft/dsw/client/mvp/AbstractPlace.java | Java | gpl-3.0 | 2,384 |
package tor
//----------------------------------------------------------------------
// This file is part of Gospel.
// Copyright (C) 2011-2021 Bernd Fix
//
// Gospel is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// Gospel is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL3.0-or-later
//----------------------------------------------------------------------
import (
"fmt"
"net"
"strconv"
"strings"
"time"
"github.com/bfix/gospel/network"
)
//======================================================================
// Tor connectivity functions
//======================================================================
// Error codes
var (
ErrTorInvalidProto = fmt.Errorf("Only TCP protocol allowed")
)
// Dial a Tor-based connection
func (s *Service) Dial(netw, address string, flags ...string) (net.Conn, error) {
return s.DialTimeout(netw, address, 0, flags...)
}
// DialTimeout to establish a Tor-based connection with timeout
func (s *Service) DialTimeout(netw, address string, timeout time.Duration, flags ...string) (net.Conn, error) {
// check protocol
if netw != "tcp" {
return nil, ErrTorInvalidProto
}
// split address
host, portS, err := net.SplitHostPort(address)
if err != nil {
return nil, err
}
port, err := strconv.ParseInt(portS, 10, 32)
if err != nil {
return nil, err
}
// determine best proxy port
socks, err := s.GetSocksPort(flags...)
if err != nil {
return nil, err
}
if strings.LastIndex(socks, ":") != -1 {
_, socks, err = net.SplitHostPort(socks)
if err != nil {
return nil, err
}
}
proxy := fmt.Sprintf("socks5://%s:%s", s.host, socks)
// connect through Tor proxy
return network.Socks5ConnectTimeout(netw, host, int(port), proxy, timeout)
}
| bfix/gospel | network/tor/conn.go | GO | gpl-3.0 | 2,294 |
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use App\Common\Roles;
class Admin
{
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
* @return void
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest() || (!$this->auth->guest() && $this->auth->user()->role_id != Roles::ROLE_ADMIN)) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
if ($this->auth->check() && $this->auth->user()->role_id != Roles::ROLE_ADMIN) {
return redirect('admin/dashboard');
}
return redirect('auth/login');
}
}
return $next($request);
}
} | jigs1212/iams | app/Http/Middleware/Admin.php | PHP | gpl-3.0 | 1,128 |
'use strict';
define(
[
'lodash',
'forge/object/base'
], function(
lodash,
Base
)
{
/**
* BBCode parser
*
* @param {Object} codes
* @param {Object} options
*/
function BBCode(codes, options)
{
this.codes = {};
Base.call(this, options);
this.setCodes(codes);
}
// prototype
BBCode.prototype = Object.create(Base.prototype,
{
/**
* all codes in structure.
*
* @var {Object}
*/
codes:
{
value: null,
enumerable: false,
configurable: false,
writable: true
}
});
/**
* set bb codes
*
* @param {Object} codes
* @returns {BBCode}
*/
BBCode.prototype.setCodes = function(codes)
{
this.codes = lodash.map(codes, function(replacement, regex)
{
return {
regexp: new RegExp(regex.slice(1, regex.lastIndexOf('#')), 'igm'),
replacement: replacement
};
});
return this;
};
/**
* parse
*
* @param {String} text
* @returns {String}
*/
BBCode.prototype.parse = function(text)
{
return lodash.reduce(this.codes, function(text, code)
{
return text.replace(code.regexp, code.replacement);
}, text);
};
return BBCode;
}); | DasRed/forge | bbCode.js | JavaScript | gpl-3.0 | 1,128 |
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
public class GestionClesRsa {
public static void sauvegardeClePublic(PublicKey clePublic, String nomFichier) {
RSAPublicKeySpec specification = null;
try {
KeyFactory usine = KeyFactory.getInstance("RSA");
specification = usine.getKeySpec(clePublic, RSAPublicKeySpec.class);
ObjectOutputStream fichier = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(nomFichier)));
fichier.writeObject(specification.getModulus());
fichier.writeObject(specification.getPublicExponent());
fichier.close();
} catch(Exception e) {
System.out.println("erreur sauvegarde cle public rsa : "+e);
}
}
public static void sauvegardeClePrivee(PrivateKey clePrivee, String nomFichier) {
RSAPrivateKeySpec specification = null;
try {
KeyFactory usine = KeyFactory.getInstance("RSA");
specification = usine.getKeySpec(clePrivee, RSAPrivateKeySpec.class);
ObjectOutputStream fichier = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(nomFichier)));
fichier.writeObject(specification.getModulus());
fichier.writeObject(specification.getPrivateExponent());
fichier.close();
} catch(Exception e) {
System.out.println("erreur sauvegarde cle privée rsa : "+e);
}
}
public static PrivateKey lectureClePrivee(String nomFichier){
BigInteger modulo = null;
BigInteger exposant = null;
PrivateKey clePrivee = null;
try {
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(nomFichier)));
modulo = (BigInteger) ois.readObject();
exposant = (BigInteger) ois.readObject();
RSAPrivateKeySpec specification = new RSAPrivateKeySpec(modulo, exposant);
KeyFactory usine = KeyFactory.getInstance("RSA");
clePrivee = usine.generatePrivate(specification);
} catch(Exception e) {
System.out.println("erreur lecture cle privée rsa : "+e);
}
return clePrivee;
}
public static PublicKey lectureClePublic(String nomFichier) {
BigInteger modulo = null;
BigInteger exposant = null;
PublicKey clePublique = null;
try {
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(nomFichier)));
modulo = (BigInteger) ois.readObject();
exposant = (BigInteger) ois.readObject();
RSAPublicKeySpec specification = new RSAPublicKeySpec(modulo, exposant);
KeyFactory usine = KeyFactory.getInstance("RSA");
clePublique = usine.generatePublic(specification);
} catch(Exception e) {
System.out.println("erreur lecture cle public rsa : "+e);
}
return clePublique;
}
} | baudryo/Palantir | src/GestionClesRsa.java | Java | gpl-3.0 | 3,126 |
/*
* Copyright (C) 2016 SeqWare
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sourceforge.seqware.common.dto;
import java.time.ZonedDateTime;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import ca.on.oicr.gsi.provenance.model.LimsKey;
import net.sourceforge.seqware.common.model.adapters.DateTimeAdapter;
/**
*
* @author mlaszloffy
*/
public class LimsKeyDto implements LimsKey {
private String provider;
private String id;
private String version;
private ZonedDateTime lastModified;
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
@XmlJavaTypeAdapter(DateTimeAdapter.class)
public ZonedDateTime getLastModified() {
return lastModified;
}
public void setLastModified(ZonedDateTime lastModified) {
this.lastModified = lastModified;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((lastModified == null) ? 0 : lastModified.toInstant().hashCode());
result = prime * result + ((provider == null) ? 0 : provider.hashCode());
result = prime * result + ((version == null) ? 0 : version.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
LimsKeyDto other = (LimsKeyDto) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (lastModified == null) {
if (other.lastModified != null)
return false;
} else if (!lastModified.toInstant().equals(other.lastModified == null ? null : other.lastModified.toInstant()))
return false;
if (provider == null) {
if (other.provider != null)
return false;
} else if (!provider.equals(other.provider))
return false;
if (version == null) {
if (other.version != null)
return false;
} else if (!version.equals(other.version))
return false;
return true;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}
| oicr-gsi/niassa | seqware-common/src/main/java/net/sourceforge/seqware/common/dto/LimsKeyDto.java | Java | gpl-3.0 | 3,134 |
# Visualisation tools
#
# Copyright (C) Andrew Bartlett 2015, 2018
#
# by Douglas Bagnall <douglas.bagnall@catalyst.net.nz>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import os
import sys
from collections import defaultdict
import tempfile
import samba
import samba.getopt as options
from samba.netcmd import Command, SuperCommand, CommandError, Option
from samba.samdb import SamDB
from samba.graph import dot_graph
from samba.graph import distance_matrix, COLOUR_SETS
from ldb import SCOPE_BASE, SCOPE_SUBTREE, LdbError
import time
from samba.kcc import KCC
from samba.kcc.kcc_utils import KCCError
from samba.compat import text_type
COMMON_OPTIONS = [
Option("-H", "--URL", help="LDB URL for database or target server",
type=str, metavar="URL", dest="H"),
Option("-o", "--output", help="write here (default stdout)",
type=str, metavar="FILE", default=None),
Option("--dot", help="Graphviz dot output", dest='format',
const='dot', action='store_const'),
Option("--distance", help="Distance matrix graph output (default)",
dest='format', const='distance', action='store_const'),
Option("--utf8", help="Use utf-8 Unicode characters",
action='store_true'),
Option("--color", help="use color (yes, no, auto)",
choices=['yes', 'no', 'auto']),
Option("--color-scheme", help=("use this colour scheme "
"(implies --color=yes)"),
choices=list(COLOUR_SETS.keys())),
Option("-S", "--shorten-names",
help="don't print long common suffixes",
action='store_true', default=False),
Option("-r", "--talk-to-remote", help="query other DCs' databases",
action='store_true', default=False),
Option("--no-key", help="omit the explanatory key",
action='store_false', default=True, dest='key'),
]
TEMP_FILE = '__temp__'
class GraphCommand(Command):
"""Base class for graphing commands"""
synopsis = "%prog [options]"
takes_optiongroups = {
"sambaopts": options.SambaOptions,
"versionopts": options.VersionOptions,
"credopts": options.CredentialsOptions,
}
takes_options = COMMON_OPTIONS
takes_args = ()
def get_db(self, H, sambaopts, credopts):
lp = sambaopts.get_loadparm()
creds = credopts.get_credentials(lp, fallback_machine=True)
samdb = SamDB(url=H, credentials=creds, lp=lp)
return samdb
def get_kcc_and_dsas(self, H, lp, creds):
"""Get a readonly KCC object and the list of DSAs it knows about."""
unix_now = int(time.time())
kcc = KCC(unix_now, readonly=True)
kcc.load_samdb(H, lp, creds)
dsa_list = kcc.list_dsas()
dsas = set(dsa_list)
if len(dsas) != len(dsa_list):
print("There seem to be duplicate dsas", file=sys.stderr)
return kcc, dsas
def write(self, s, fn=None, suffix='.dot'):
"""Decide whether we're dealing with a filename, a tempfile, or
stdout, and write accordingly.
:param s: the string to write
:param fn: a destination
:param suffix: suffix, if destination is a tempfile
If fn is None or "-", write to stdout.
If fn is visualize.TEMP_FILE, write to a temporary file
Otherwise fn should be a filename to write to.
"""
if fn is None or fn == '-':
# we're just using stdout (a.k.a self.outf)
print(s, file=self.outf)
return
if fn is TEMP_FILE:
fd, fn = tempfile.mkstemp(prefix='samba-tool-visualise',
suffix=suffix)
f = open(fn, 'w')
os.close(fd)
else:
f = open(fn, 'w')
f.write(s)
f.close()
return fn
def calc_output_format(self, format, output):
"""Heuristics to work out what output format was wanted."""
if not format:
# They told us nothing! We have to work it out for ourselves.
if output and output.lower().endswith('.dot'):
return 'dot'
else:
return 'distance'
return format
def calc_distance_color_scheme(self, color, color_scheme, output):
"""Heuristics to work out the colour scheme for distance matrices.
Returning None means no colour, otherwise it sould be a colour
from graph.COLOUR_SETS"""
if color == 'no':
return None
if color == 'auto':
if isinstance(output, str) and output != '-':
return None
if not hasattr(self.outf, 'isatty'):
# not a real file, perhaps cStringIO in testing
return None
if not self.outf.isatty():
return None
if color_scheme is None:
if '256color' in os.environ.get('TERM', ''):
return 'xterm-256color-heatmap'
return 'ansi'
return color_scheme
def colour_hash(x):
"""Generate a randomish but consistent darkish colour based on the
given object."""
from hashlib import md5
tmp_str = str(x)
if isinstance(tmp_str, text_type):
tmp_str = tmp_str.encode('utf8')
c = int(md5(tmp_str).hexdigest()[:6], base=16) & 0x7f7f7f
return '#%06x' % c
def get_partition_maps(samdb):
"""Generate dictionaries mapping short partition names to the
appropriate DNs."""
base_dn = samdb.domain_dn()
short_to_long = {
"DOMAIN": base_dn,
"CONFIGURATION": str(samdb.get_config_basedn()),
"SCHEMA": "CN=Schema,%s" % samdb.get_config_basedn(),
"DNSDOMAIN": "DC=DomainDnsZones,%s" % base_dn,
"DNSFOREST": "DC=ForestDnsZones,%s" % base_dn
}
long_to_short = {}
for s, l in short_to_long.items():
long_to_short[l] = s
return short_to_long, long_to_short
class cmd_reps(GraphCommand):
"repsFrom/repsTo from every DSA"
takes_options = COMMON_OPTIONS + [
Option("-p", "--partition", help="restrict to this partition",
default=None),
]
def run(self, H=None, output=None, shorten_names=False,
key=True, talk_to_remote=False,
sambaopts=None, credopts=None, versionopts=None,
mode='self', partition=None, color=None, color_scheme=None,
utf8=None, format=None):
# We use the KCC libraries in readonly mode to get the
# replication graph.
lp = sambaopts.get_loadparm()
creds = credopts.get_credentials(lp, fallback_machine=True)
local_kcc, dsas = self.get_kcc_and_dsas(H, lp, creds)
unix_now = local_kcc.unix_now
# Allow people to say "--partition=DOMAIN" rather than
# "--partition=DC=blah,DC=..."
short_partitions, long_partitions = get_partition_maps(local_kcc.samdb)
if partition is not None:
partition = short_partitions.get(partition.upper(), partition)
if partition not in long_partitions:
raise CommandError("unknown partition %s" % partition)
# nc_reps is an autovivifying dictionary of dictionaries of lists.
# nc_reps[partition]['current' | 'needed'] is a list of
# (dsa dn string, repsFromTo object) pairs.
nc_reps = defaultdict(lambda: defaultdict(list))
guid_to_dnstr = {}
# We run a new KCC for each DSA even if we aren't talking to
# the remote, because after kcc.run (or kcc.list_dsas) the kcc
# ends up in a messy state.
for dsa_dn in dsas:
kcc = KCC(unix_now, readonly=True)
if talk_to_remote:
res = local_kcc.samdb.search(dsa_dn,
scope=SCOPE_BASE,
attrs=["dNSHostName"])
dns_name = res[0]["dNSHostName"][0]
print("Attempting to contact ldap://%s (%s)" %
(dns_name, dsa_dn),
file=sys.stderr)
try:
kcc.load_samdb("ldap://%s" % dns_name, lp, creds)
except KCCError as e:
print("Could not contact ldap://%s (%s)" % (dns_name, e),
file=sys.stderr)
continue
kcc.run(H, lp, creds)
else:
kcc.load_samdb(H, lp, creds)
kcc.run(H, lp, creds, forced_local_dsa=dsa_dn)
dsas_from_here = set(kcc.list_dsas())
if dsas != dsas_from_here:
print("found extra DSAs:", file=sys.stderr)
for dsa in (dsas_from_here - dsas):
print(" %s" % dsa, file=sys.stderr)
print("missing DSAs (known locally, not by %s):" % dsa_dn,
file=sys.stderr)
for dsa in (dsas - dsas_from_here):
print(" %s" % dsa, file=sys.stderr)
for remote_dn in dsas_from_here:
if mode == 'others' and remote_dn == dsa_dn:
continue
elif mode == 'self' and remote_dn != dsa_dn:
continue
remote_dsa = kcc.get_dsa('CN=NTDS Settings,' + remote_dn)
kcc.translate_ntdsconn(remote_dsa)
guid_to_dnstr[str(remote_dsa.dsa_guid)] = remote_dn
# get_reps_tables() returns two dictionaries mapping
# dns to NCReplica objects
c, n = remote_dsa.get_rep_tables()
for part, rep in c.items():
if partition is None or part == partition:
nc_reps[part]['current'].append((dsa_dn, rep))
for part, rep in n.items():
if partition is None or part == partition:
nc_reps[part]['needed'].append((dsa_dn, rep))
all_edges = {'needed': {'to': [], 'from': []},
'current': {'to': [], 'from': []}}
for partname, part in nc_reps.items():
for state, edgelists in all_edges.items():
for dsa_dn, rep in part[state]:
short_name = long_partitions.get(partname, partname)
for r in rep.rep_repsFrom:
edgelists['from'].append(
(dsa_dn,
guid_to_dnstr[str(r.source_dsa_obj_guid)],
short_name))
for r in rep.rep_repsTo:
edgelists['to'].append(
(guid_to_dnstr[str(r.source_dsa_obj_guid)],
dsa_dn,
short_name))
# Here we have the set of edges. From now it is a matter of
# interpretation and presentation.
if self.calc_output_format(format, output) == 'distance':
color_scheme = self.calc_distance_color_scheme(color,
color_scheme,
output)
header_strings = {
'from': "RepsFrom objects for %s",
'to': "RepsTo objects for %s",
}
for state, edgelists in all_edges.items():
for direction, items in edgelists.items():
part_edges = defaultdict(list)
for src, dest, part in items:
part_edges[part].append((src, dest))
for part, edges in part_edges.items():
s = distance_matrix(None, edges,
utf8=utf8,
colour=color_scheme,
shorten_names=shorten_names,
generate_key=key)
s = "\n%s\n%s" % (header_strings[direction] % part, s)
self.write(s, output)
return
edge_colours = []
edge_styles = []
dot_edges = []
dot_vertices = set()
used_colours = {}
key_set = set()
for state, edgelist in all_edges.items():
for direction, items in edgelist.items():
for src, dest, part in items:
colour = used_colours.setdefault((part),
colour_hash((part,
direction)))
linestyle = 'dotted' if state == 'needed' else 'solid'
arrow = 'open' if direction == 'to' else 'empty'
dot_vertices.add(src)
dot_vertices.add(dest)
dot_edges.append((src, dest))
edge_colours.append(colour)
style = 'style="%s"; arrowhead=%s' % (linestyle, arrow)
edge_styles.append(style)
key_set.add((part, 'reps' + direction.title(),
colour, style))
key_items = []
if key:
for part, direction, colour, linestyle in sorted(key_set):
key_items.append((False,
'color="%s"; %s' % (colour, linestyle),
"%s %s" % (part, direction)))
key_items.append((False,
'style="dotted"; arrowhead="open"',
"repsFromTo is needed"))
key_items.append((False,
'style="solid"; arrowhead="open"',
"repsFromTo currently exists"))
s = dot_graph(dot_vertices, dot_edges,
directed=True,
edge_colors=edge_colours,
edge_styles=edge_styles,
shorten_names=shorten_names,
key_items=key_items)
self.write(s, output)
class NTDSConn(object):
"""Collects observation counts for NTDS connections, so we know
whether all DSAs agree."""
def __init__(self, src, dest):
self.observations = 0
self.src_attests = False
self.dest_attests = False
self.src = src
self.dest = dest
def attest(self, attester):
self.observations += 1
if attester == self.src:
self.src_attests = True
if attester == self.dest:
self.dest_attests = True
class cmd_ntdsconn(GraphCommand):
"Draw the NTDSConnection graph"
def run(self, H=None, output=None, shorten_names=False,
key=True, talk_to_remote=False,
sambaopts=None, credopts=None, versionopts=None,
color=None, color_scheme=None,
utf8=None, format=None):
lp = sambaopts.get_loadparm()
creds = credopts.get_credentials(lp, fallback_machine=True)
local_kcc, dsas = self.get_kcc_and_dsas(H, lp, creds)
local_dsa_dn = local_kcc.my_dsa_dnstr.split(',', 1)[1]
vertices = set()
attested_edges = []
for dsa_dn in dsas:
if talk_to_remote:
res = local_kcc.samdb.search(dsa_dn,
scope=SCOPE_BASE,
attrs=["dNSHostName"])
dns_name = res[0]["dNSHostName"][0]
try:
samdb = self.get_db("ldap://%s" % dns_name, sambaopts,
credopts)
except LdbError as e:
print("Could not contact ldap://%s (%s)" % (dns_name, e),
file=sys.stderr)
continue
ntds_dn = samdb.get_dsServiceName()
dn = samdb.domain_dn()
else:
samdb = self.get_db(H, sambaopts, credopts)
ntds_dn = 'CN=NTDS Settings,' + dsa_dn
dn = dsa_dn
vertices.add(ntds_dn)
# XXX we could also look at schedule
res = samdb.search(dn,
scope=SCOPE_SUBTREE,
expression="(objectClass=nTDSConnection)",
attrs=['fromServer'],
# XXX can't be critical for ldif test
#controls=["search_options:1:2"],
controls=["search_options:0:2"],
)
for msg in res:
msgdn = str(msg.dn)
dest_dn = msgdn[msgdn.index(',') + 1:]
attested_edges.append((msg['fromServer'][0],
dest_dn, ntds_dn))
# now we overlay all the graphs and generate styles accordingly
edges = {}
for src, dest, attester in attested_edges:
k = (src, dest)
if k in edges:
e = edges[k]
else:
e = NTDSConn(*k)
edges[k] = e
e.attest(attester)
if self.calc_output_format(format, output) == 'distance':
color_scheme = self.calc_distance_color_scheme(color,
color_scheme,
output)
if not talk_to_remote:
# If we are not talking to remote servers, we list all
# the connections.
graph_edges = edges.keys()
title = 'NTDS Connections known to %s' % local_dsa_dn
epilog = ''
else:
# If we are talking to the remotes, there are
# interesting cases we can discover. What matters most
# is that the destination (i.e. owner) knowns about
# the connection, but it would be worth noting if the
# source doesn't. Another strange situation could be
# when a DC thinks there is a connection elsewhere,
# but the computers allegedly involved don't believe
# it exists.
#
# With limited bandwidth in the table, we mark the
# edges known to the destination, and note the other
# cases in a list after the diagram.
graph_edges = []
source_denies = []
dest_denies = []
both_deny = []
for e, conn in edges.items():
if conn.dest_attests:
graph_edges.append(e)
if not conn.src_attests:
source_denies.append(e)
elif conn.src_attests:
dest_denies.append(e)
else:
both_deny.append(e)
title = 'NTDS Connections known to each destination DC'
epilog = []
if both_deny:
epilog.append('The following connections are alleged by '
'DCs other than the source and '
'destination:\n')
for e in both_deny:
epilog.append(' %s -> %s\n' % e)
if dest_denies:
epilog.append('The following connections are alleged by '
'DCs other than the destination but '
'including the source:\n')
for e in dest_denies:
epilog.append(' %s -> %s\n' % e)
if source_denies:
epilog.append('The following connections '
'(included in the chart) '
'are not known to the source DC:\n')
for e in source_denies:
epilog.append(' %s -> %s\n' % e)
epilog = ''.join(epilog)
s = distance_matrix(sorted(vertices), graph_edges,
utf8=utf8,
colour=color_scheme,
shorten_names=shorten_names,
generate_key=key)
self.write('\n%s\n%s\n%s' % (title, s, epilog), output)
return
dot_edges = []
edge_colours = []
edge_styles = []
edge_labels = []
n_servers = len(dsas)
for k, e in sorted(edges.items()):
dot_edges.append(k)
if e.observations == n_servers or not talk_to_remote:
edge_colours.append('#000000')
edge_styles.append('')
elif e.dest_attests:
edge_styles.append('')
if e.src_attests:
edge_colours.append('#0000ff')
else:
edge_colours.append('#cc00ff')
elif e.src_attests:
edge_colours.append('#ff0000')
edge_styles.append('style=dashed')
else:
edge_colours.append('#ff0000')
edge_styles.append('style=dotted')
key_items = []
if key:
key_items.append((False,
'color="#000000"',
"NTDS Connection"))
for colour, desc in (('#0000ff', "missing from some DCs"),
('#cc00ff', "missing from source DC")):
if colour in edge_colours:
key_items.append((False, 'color="%s"' % colour, desc))
for style, desc in (('style=dashed', "unknown to destination"),
('style=dotted',
"unknown to source and destination")):
if style in edge_styles:
key_items.append((False,
'color="#ff0000; %s"' % style,
desc))
if talk_to_remote:
title = 'NTDS Connections'
else:
title = 'NTDS Connections known to %s' % local_dsa_dn
s = dot_graph(sorted(vertices), dot_edges,
directed=True,
title=title,
edge_colors=edge_colours,
edge_labels=edge_labels,
edge_styles=edge_styles,
shorten_names=shorten_names,
key_items=key_items)
self.write(s, output)
class cmd_visualize(SuperCommand):
"""Produces graphical representations of Samba network state"""
subcommands = {}
for k, v in globals().items():
if k.startswith('cmd_'):
subcommands[k[4:]] = v()
| sathieu/samba | python/samba/netcmd/visualize.py | Python | gpl-3.0 | 23,538 |
// This file is part of the thin-provisioning-tools source.
//
// thin-provisioning-tools is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// thin-provisioning-tools is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with thin-provisioning-tools. If not, see
// <http://www.gnu.org/licenses/>.
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
#include <getopt.h>
#include <vector>
#include <fstream>
#include "persistent-data/data-structures/btree.h"
#include "persistent-data/data-structures/simple_traits.h"
#include "persistent-data/file_utils.h"
#include "persistent-data/space-maps/core.h"
#include "persistent-data/space-maps/disk_structures.h"
#include "thin-provisioning/metadata.h"
#include "thin-provisioning/superblock.h"
#include "thin-provisioning/commands.h"
#include "version.h"
using namespace boost;
using namespace std;
using namespace thin_provisioning;
//----------------------------------------------------------------
namespace {
bool check_flags(uint32_t flags) {
flags &= 0x3;
if (flags == INTERNAL_NODE || flags == LEAF_NODE)
return true;
return false;
}
// extracted from btree_damage_visitor.h
template <typename node>
bool check_block_nr(node const &n) {
if (n.get_location() != n.get_block_nr()) {
return false;
}
return true;
}
// extracted from btree_damage_visitor.h
template <typename node>
bool check_max_entries(node const &n) {
size_t elt_size = sizeof(uint64_t) + n.get_value_size();
if (elt_size * n.get_max_entries() + sizeof(node_header) > MD_BLOCK_SIZE) {
return false;
}
if (n.get_max_entries() % 3) {
return false;
}
return true;
}
// extracted from btree_damage_visitor.h
template <typename node>
bool check_nr_entries(node const &n, bool is_root) {
if (n.get_nr_entries() > n.get_max_entries()) {
return false;
}
block_address min = n.get_max_entries() / 3;
if (!is_root && (n.get_nr_entries() < min)) {
return false;
}
return true;
}
// extracted from btree_damage_visitor.h
template <typename node>
bool check_ordered_keys(node const &n) {
unsigned nr_entries = n.get_nr_entries();
if (nr_entries == 0)
return true; // can only happen if a root node
uint64_t last_key = n.key_at(0);
for (unsigned i = 1; i < nr_entries; i++) {
uint64_t k = n.key_at(i);
if (k <= last_key) {
return false;
}
last_key = k;
}
return true;
}
}
namespace {
uint32_t const SUPERBLOCK_CSUM_SEED = 160774;
uint32_t const BITMAP_CSUM_XOR = 240779;
uint32_t const INDEX_CSUM_XOR = 160478;
uint32_t const BTREE_CSUM_XOR = 121107;
enum metadata_block_type {
UNKNOWN = 0,
ZERO,
SUPERBLOCK,
INDEX_BLOCK,
BITMAP_BLOCK,
BTREE_NODE
};
// For UNKNOWN and ZERO
class block_range {
public:
block_range()
: begin_(0),
end_(0),
type_(UNKNOWN),
is_valid_(false),
ref_count_(-1) {
}
block_range(block_range const &rhs)
: begin_(rhs.begin_),
end_(rhs.end_),
type_(rhs.type_),
is_valid_(rhs.is_valid_),
ref_count_(rhs.ref_count_) {
}
virtual ~block_range() {}
virtual void reset(int type,
typename block_manager::read_ref &rr,
int64_t ref_count) {
begin_ = rr.get_location();
end_ = begin_ + 1;
type_ = type;
ref_count_ = ref_count;
is_valid_ = false;
}
virtual std::unique_ptr<block_range> clone() const {
return std::unique_ptr<block_range>(new block_range(*this));
}
inline uint64_t size() const {
return (end_ > begin_) ? (end_ - begin_) : 0;
}
// returns true if r is left or right-adjacent
bool is_adjacent_to(block_range const &r) const {
if (begin_ < r.begin_)
return is_adjacent_to_(r);
return r.is_adjacent_to_(*this);
}
bool concat(block_range const &r) {
if (!is_adjacent_to(r))
return false;
begin_ = std::min(begin_, r.begin_);
end_ = std::max(end_, r.end_);
return true;
}
virtual char const *type_name() const {
switch (type_) {
case ZERO:
return "zero";
default:
return "unknown";
}
}
virtual void print(std::ostream &out) const {
uint64_t s = size();
if (s > 1) {
out << "<range_block type=\"" << type_name()
<< "\" location_begin=\"" << begin_
<< "\" length=\"" << s
<< "\" ref_count=\"" << ref_count_
<< "\" is_valid=\"" << is_valid_
<< "\"/>";
} else if (s == 1) {
out << "<single_block type=\"" << type_name()
<< "\" location=\"" << begin_
<< "\" ref_count=\"" << ref_count_
<< "\" is_valid=\"" << is_valid_
<< "\"/>";
}
}
friend ostream &operator<<(std::ostream &out, block_range const &r);
protected:
// return true is rhs is right-adjacent
virtual bool is_adjacent_to_(block_range const &rhs) const {
if (type_ != rhs.type_)
return false;
if (rhs.begin_ != end_)
return false;
if (ref_count_ != rhs.ref_count_ ||
is_valid_ != rhs.is_valid_)
return false;
return true;
}
uint64_t begin_;
uint64_t end_; // one-pass-the-end. end_ == begin_ indicates an empty range.
int type_;
bool is_valid_;
int64_t ref_count_; // ref_count in metadata space map
};
// For SUPERBLOCK, INDEX_BLOCK and BITMAP_BLOCK
class meta_block_range: public block_range {
public:
meta_block_range()
: block_range(),
blocknr_begin_(0) {
}
meta_block_range(meta_block_range const &rhs)
: block_range(rhs),
blocknr_begin_(rhs.blocknr_begin_) {
}
virtual void reset(int type,
typename block_manager::read_ref &rr,
int64_t ref_count) {
using namespace persistent_data;
using namespace sm_disk_detail;
using namespace superblock_detail;
begin_ = rr.get_location();
end_ = begin_ + 1;
type_ = type;
ref_count_ = ref_count;
switch (type) {
case SUPERBLOCK:
blocknr_begin_ = to_cpu<uint64_t>(reinterpret_cast<superblock_disk const *>(rr.data())->blocknr_);
break;
case BITMAP_BLOCK:
blocknr_begin_ = to_cpu<uint64_t>(reinterpret_cast<bitmap_header const *>(rr.data())->blocknr);
break;
case INDEX_BLOCK:
blocknr_begin_ = to_cpu<uint64_t>(reinterpret_cast<metadata_index const *>(rr.data())->blocknr_);
break;
default:
blocknr_begin_ = 0;
}
is_valid_ = (blocknr_begin_ == begin_) ? true : false;
}
virtual std::unique_ptr<block_range> clone() const {
return std::unique_ptr<block_range>(new meta_block_range(*this));
}
virtual char const *type_name() const {
switch (type_) {
case SUPERBLOCK:
return "superblock";
case INDEX_BLOCK:
return "index_block";
case BITMAP_BLOCK:
return "bitmap_block";
default:
return "unknown";
}
}
virtual void print(std::ostream &out) const {
uint64_t s = size();
if (s > 1) {
out << "<range_block type=\"" << type_name()
<< "\" location_begin=\"" << begin_
<< "\" blocknr_begin=\"" << blocknr_begin_
<< "\" length=\"" << s
<< "\" ref_count=\"" << ref_count_
<< "\" is_valid=\"" << is_valid_
<< "\"/>";
} else if (s == 1) {
out << "<single_block type=\"" << type_name()
<< "\" location=\"" << begin_
<< "\" blocknr=\"" << blocknr_begin_
<< "\" ref_count=\"" << ref_count_
<< "\" is_valid=\"" << is_valid_
<< "\"/>";
}
}
protected:
virtual bool is_adjacent_to_(block_range const &rhs) const {
if (!block_range::is_adjacent_to_(rhs))
return false;
meta_block_range const &r = dynamic_cast<meta_block_range const &>(rhs);
if (r.blocknr_begin_ < blocknr_begin_)
return false;
if (r.blocknr_begin_ - blocknr_begin_ != r.begin_ - begin_)
return false;
return true;
}
block_address blocknr_begin_; // block number in header
};
// For BTREE_NODE
class btree_block_range: public meta_block_range {
public:
btree_block_range()
: meta_block_range(),
flags_(0),
value_size_(0) {
}
btree_block_range(btree_block_range const &rhs)
: meta_block_range(rhs),
flags_(rhs.flags_),
value_size_(rhs.value_size_) {
}
virtual void reset(int type,
typename block_manager::read_ref &rr,
int64_t ref_count) {
node_ref<uint64_traits> n = btree_detail::to_node<uint64_traits>(rr);
begin_ = rr.get_location();
end_ = begin_ + 1;
type_ = type;
ref_count_ = ref_count;
blocknr_begin_ = n.get_block_nr();
flags_ = to_cpu<uint32_t>(n.raw()->header.flags);
value_size_ = n.get_value_size();
if (check_flags(flags_) &&
check_block_nr(n) &&
check_max_entries(n) &&
check_nr_entries(n, true) &&
check_ordered_keys(n))
is_valid_ = true;
else
is_valid_ = false;
}
virtual std::unique_ptr<block_range> clone() const {
return std::unique_ptr<block_range>(new btree_block_range(*this));
}
virtual char const *type_name() const {
if ((flags_ & INTERNAL_NODE) && !(flags_ & LEAF_NODE))
return "btree_internal";
else if (flags_ & LEAF_NODE)
return "btree_leaf";
else
return "btree_unknown";
};
virtual void print(std::ostream &out) const {
uint64_t s = size();
if (s > 1) {
out << "<range_block type=\"" << type_name()
<< "\" location_begin=\"" << begin_
<< "\" blocknr_begin=\"" << blocknr_begin_
<< "\" length=\"" << s
<< "\" ref_count=\"" << ref_count_
<< "\" is_valid=\"" << is_valid_
<< "\" value_size=\"" << value_size_
<< "\"/>";
} else if (s == 1) {
out << "<single_block type=\"" << type_name()
<< "\" location=\"" << begin_
<< "\" blocknr=\"" << blocknr_begin_
<< "\" ref_count=\"" << ref_count_
<< "\" is_valid=\"" << is_valid_
<< "\" value_size=\"" << value_size_
<< "\"/>";
}
}
protected:
virtual bool is_adjacent_to_(block_range const &rhs) const {
if (!meta_block_range::is_adjacent_to_(rhs))
return false;
btree_block_range const &r = dynamic_cast<btree_block_range const &>(rhs);
if ((flags_ & 0x3) != (r.flags_ & 0x3))
return false;
if (value_size_ != r.value_size_)
return false;
return true;
}
uint32_t flags_;
size_t value_size_;
};
ostream &operator<<(std::ostream &out, block_range const &r) {
r.print(out);
return out;
}
//-------------------------------------------------------------------
class range_factory {
public:
virtual ~range_factory() {}
block_range const &convert_to_range(block_manager::read_ref rr, int64_t ref_count) {
if (!memcmp(rr.data(), zeros_.data(), MD_BLOCK_SIZE)) {
br_.reset(ZERO, rr, ref_count);
return br_;
}
uint32_t const *cksum = reinterpret_cast<uint32_t const*>(rr.data());
base::crc32c sum(*cksum);
sum.append(cksum + 1, MD_BLOCK_SIZE - sizeof(uint32_t));
switch (sum.get_sum()) {
case SUPERBLOCK_CSUM_SEED:
mbr_.reset(SUPERBLOCK, rr, ref_count);
return mbr_;
case INDEX_CSUM_XOR:
mbr_.reset(INDEX_BLOCK, rr, ref_count);
return mbr_;
case BITMAP_CSUM_XOR:
mbr_.reset(BITMAP_BLOCK, rr, ref_count);
return mbr_;
case BTREE_CSUM_XOR:
bbr_.reset(BTREE_NODE, rr, ref_count);
return bbr_;
default:
br_.reset(UNKNOWN, rr, ref_count);
return br_;
}
}
private:
static const std::vector<char> zeros_;
// for internal caching only
block_range br_;
meta_block_range mbr_;
btree_block_range bbr_;
};
const std::vector<char> range_factory::zeros_(MD_BLOCK_SIZE, 0);
class metadata_scanner {
public:
metadata_scanner(block_manager::ptr bm, uint64_t scan_begin, uint64_t scan_end,
bool check_for_strings)
: bm_(bm),
scan_begin_(scan_begin),
scan_end_(scan_end),
index_(scan_begin),
check_for_strings_(check_for_strings) {
if (scan_end_ <= scan_begin_)
throw std::runtime_error("badly formed region (end <= begin)");
// try to open metadata space-map (it's okay to fail)
try {
superblock_detail::superblock sb = read_superblock(bm);
tm_ = open_tm(bm, superblock_detail::SUPERBLOCK_LOCATION);
metadata_sm_ = open_metadata_sm(*tm_, &sb.metadata_space_map_root_);
tm_->set_sm(metadata_sm_);
} catch (std::exception &e) {
cerr << e.what() << endl;
}
// prefetch the first block
block_range const &r = read_block(index_++);
run_range_ = r.clone();
}
std::unique_ptr<block_range> get_range() {
std::unique_ptr<block_range> ret;
while (index_ < scan_end_) {
block_range const &r = read_block(index_++);
if (!run_range_->concat(r)) {
ret = std::move(run_range_);
run_range_ = r.clone();
break;
}
}
if (!ret) { // for the last run (index_ == scan_end_)
ret = std::move(run_range_);
run_range_.reset();
}
return ret;
}
map<block_address, vector<string>> const &get_strings() const {
return strings_;
}
private:
bool interesting_char(char c)
{
return isalnum(c) || ispunct(c);
}
unsigned printable_len(const char *b, const char *e)
{
const char *p = b;
while (p != e && interesting_char(*p))
p++;
return p - b;
}
// asci text within our metadata is a sure sign of corruption.
optional<vector<string> >
scan_strings(block_manager::read_ref rr)
{
vector<string> r;
const char *data = reinterpret_cast<const char *>(rr.data()), *end = data + MD_BLOCK_SIZE;
while (data < end) {
auto len = printable_len(data, end);
if (len >= 4)
r.push_back(string(data, data + len));
data += len + 1;
}
return r.size() ? optional<vector<string>>(r) : optional<vector<string>>();
}
block_range const &read_block(block_address b) {
block_manager::read_ref rr = bm_->read_lock(b);
int64_t ref_count;
try {
ref_count = metadata_sm_ ? static_cast<int64_t>(metadata_sm_->get_count(b)) : -1;
} catch (std::exception &e) {
ref_count = -1;
}
if (check_for_strings_) {
auto ss = scan_strings(rr);
if (ss) {
strings_.insert(make_pair(b, *ss));
}
}
return factory_.convert_to_range(rr, ref_count);
}
// note: space_map does not take the ownership of transaction_manager,
// so the transaction_manager must live in the same scope of space_map.
block_manager::ptr bm_;
transaction_manager::ptr tm_;
checked_space_map::ptr metadata_sm_;
uint64_t scan_begin_;
uint64_t scan_end_;
uint64_t index_;
std::unique_ptr<block_range> run_range_;
range_factory factory_;
bool check_for_strings_;
map<block_address, vector<string>> strings_;
};
//-------------------------------------------------------------------
struct flags {
flags()
: exclusive_(true),
examine_corruption_(false)
{
}
boost::optional<block_address> scan_begin_;
boost::optional<block_address> scan_end_;
bool exclusive_;
bool examine_corruption_;
};
int scan_metadata_(string const &input,
std::ostream &out,
flags const &f) {
block_manager::ptr bm;
bm = open_bm(input, block_manager::READ_ONLY, f.exclusive_);
block_address scan_begin = f.scan_begin_ ? *f.scan_begin_ : 0;
block_address scan_end = f.scan_end_ ? *f.scan_end_ : bm->get_nr_blocks();
metadata_scanner scanner(bm, scan_begin, scan_end, f.examine_corruption_);
std::unique_ptr<block_range> r;
while ((r = scanner.get_range())) {
out << *r << std::endl;
}
if (f.examine_corruption_) {
auto ss = scanner.get_strings();
for (auto const &ps : ss) {
out << ps.first << ": ";
unsigned total = 0;
for (auto const &s : ps.second)
total += s.length();
out << total << " bytes of text\n";
}
}
return 0;
}
int scan_metadata(string const &input,
boost::optional<string> output,
flags const &f) {
try {
if (output) {
std::ofstream out(output->c_str());
scan_metadata_(input, out, f);
} else
scan_metadata_(input, cout, f);
} catch (std::exception &e) {
cerr << e.what() << endl;
return 1;
}
return 0;
}
}
//---------------------------------------------------------------------------
thin_scan_cmd::thin_scan_cmd()
: command("thin_scan")
{
}
void
thin_scan_cmd::usage(std::ostream &out) const {
out << "Usage: " << get_name() << " [options] {device|file}\n"
<< "Options:\n"
<< " {-h|--help}\n"
<< " {-o|--output} <xml file>\n"
<< " {--begin} <block#>\n"
<< " {--end} <block#>\n"
<< " {--examine-corruption}\n"
<< " {-V|--version}" << endl;
}
int
thin_scan_cmd::run(int argc, char **argv)
{
const char shortopts[] = "ho:V";
const struct option longopts[] = {
{ "help", no_argument, NULL, 'h'},
{ "output", required_argument, NULL, 'o'},
{ "version", no_argument, NULL, 'V'},
{ "begin", required_argument, NULL, 1},
{ "end", required_argument, NULL, 2},
{ "examine-corruption", no_argument, NULL, 3 },
{ NULL, no_argument, NULL, 0 }
};
boost::optional<string> output;
flags f;
int c;
while ((c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) {
switch(c) {
case 'h':
usage(cout);
return 0;
case 'o':
output = optarg;
break;
case 'V':
cout << THIN_PROVISIONING_TOOLS_VERSION << endl;
return 0;
case 1:
try {
f.scan_begin_ = boost::lexical_cast<uint64_t>(optarg);
} catch (std::exception &e) {
cerr << e.what() << endl;
return 1;
}
break;
case 2:
try {
f.scan_end_ = boost::lexical_cast<uint64_t>(optarg);
} catch (std::exception &e) {
cerr << e.what() << endl;
return 1;
}
break;
case 3:
f.examine_corruption_ = true;
break;
default:
usage(cerr);
return 1;
}
}
if (argc == optind) {
cerr << "No input file provided." << endl;
usage(cerr);
return 1;
}
if (f.scan_begin_ && f.scan_end_ && (*f.scan_end_ <= *f.scan_begin_)) {
cerr << "badly formed region (end <= begin)" << endl;
return 1;
}
return scan_metadata(argv[optind], output, f);
}
//---------------------------------------------------------------------------
| jthornber/thin-provisioning-tools | thin-provisioning/thin_scan.cc | C++ | gpl-3.0 | 18,391 |
// ----------------------------------------------------------------------------
// Copyright (C) 2012 Louise A. Dennis, and Michael Fisher
//
// This file is part of the Agent Infrastructure Layer (AIL)
//
// The AIL is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// The AIL is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with the AIL; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// To contact the authors:
// http://www.csc.liv.ac.uk/~lad
//
//----------------------------------------------------------------------------
package ail.syntax.ast;
import java.util.ArrayList;
import gov.nasa.jpf.vm.VM;
import gov.nasa.jpf.vm.MJIEnv;
import gov.nasa.jpf.vm.Verify;
import ail.syntax.ListTermImpl;
import ail.syntax.ListTerm;
import ail.syntax.Term;
/**
* Generic Description of Abstract Classes in AIL and AJPF
* -------------------------------------------------------
*
* We use "Abstract" versions of syntax items for all bits of state that we sometimes wish to store in the native
* java VM as well in the JavaPathfinder VM. In particular files are parsed into the native VM and then the relevant
* initial state of the multi-agent system is reconstructed in the model-checking VM. This is done to improve
* efficiency of parsing (the native VM is faster). We also represent properties for model checking in the native VM
* and, indeed the property automata is stored only in the native VM. We used Abstract classes partly because less
* computational content is needed for these objects in the native VM and so a smaller representation can be used
* but also because specific support is needed for transferring information between the two virtual machines both
* in terms of methods and in terms of the data types chosen for the various fields. It was felt preferable to
* separate these things out from the classes used for the objects that determine the run time behaviour of a MAS.
*
* Abstract classes all have a method (toMCAPL) for creating a class for the equivalent concrete object used
* when executing the MAS. They also have a method (newJPFObject) that will create an equivalent object in the
* model-checking virtual machine from one that is held in the native VM. At the start of execution the agent
* program is parsed into abstract classes in the native VM. An equivalent structure is then created in the JVM
* using calls to newJPFObject and this structure is then converted into the structures used for executing the MAS
* by calls to toMCAPL.
*
*/
/**
* Abstract Syntax version of an implementation of list terms.
* @author lad
*
*/
public class Abstract_ListTermImpl implements Abstract_ListTerm {
/**
* Head of the list.
*/
private Abstract_Term term;
/**
* Tail of the list.
*/
private Abstract_ListTerm next;
/*
* (non-Javadoc)
* @see ail.syntax.ast.Abstract_ListTerm#append(ail.syntax.ast.Abstract_Term)
*/
public Abstract_ListTerm append(Abstract_Term t) {
if (isEmpty()) {
term = t;
next = new Abstract_ListTermImpl();
return this;
} else if (isTail()) {
// What to do?
return null;
} else {
return getNext().append(t);
}
}
/**
* Add a list of terms to the head of this list.
* @param tl
*/
@Override
public void addAll(ArrayList<Abstract_Term> tl) {
for (int i = tl.size() -1 ; i > -1; i--) {
addHead(tl.get(i));
}
}
/**
* Is this the empty list.
* @return
*/
public boolean isEmpty() {
return term == null;
}
/** make a hard copy of the terms */
public Abstract_ListTermImpl clone() {
Abstract_ListTermImpl t = new Abstract_ListTermImpl();
if (term != null) {
t.term = this.term.clone();
}
if (next != null) {
t.next = (Abstract_ListTerm)this.next.clone();
}
return t;
}
/**
* Does this list have no tail? Should be mal-formed in this case, to be honest.
* @return
*/
public boolean isTail() {
return next == null;
}
/**
* Return the tail of the list.
* @return
*/
public Abstract_ListTerm getNext() {
return next;
}
@Override
public Abstract_Term getTerm(int i) {
if (i == 0) {
return term;
}
if (i == 1) {
return next;
}
return null;
}
/*
* (non-Javadoc)
* @see ail.syntax.ast.Abstract_ListTerm#addHead(ail.syntax.ast.Abstract_Term)
*/
public void addHead(Abstract_Term h) {
if (isEmpty()) {
term = h;
next = new Abstract_ListTermImpl();
} else if (isTail()) {
// What to do?
} else {
next = this.clone();
term = h;
}
}
/*
* (non-Javadoc)
* @see ail.syntax.ast.Abstract_ListTerm#addTail(ail.syntax.ast.Abstract_ListTerm)
*/
public void addTail(Abstract_ListTerm t) {
Abstract_ListTermImpl tl = (Abstract_ListTermImpl) getNext();
if (tl.isEmpty()) {
next = t;
} else {
tl.addTail(t);
}
}
@Override
public int createInJPF(VM vm) {
Verify.log("ail.syntax.ast.Abstract_ListTermImpl", Verify.WARNING, "Abstract_ListTermImpl should not be being created from Listener");
return 0;
}
@Override
public ListTermImpl toMCAPL() {
ListTermImpl list = new ListTermImpl();
if (term != null) {
list.setHead((Term) term.toMCAPL());
}
if (next != null) {
list.setTail((ListTerm) next.toMCAPL());
}
return list;
}
@Override
public int newJPFObject(MJIEnv env) {
int objref = env.newObject("ail.syntax.ast.Abstract_ListTermImpl");
if (term != null) {
env.setReferenceField(objref, "term", term.newJPFObject(env));
}
if (next != null) {
env.setReferenceField(objref, "next", next.newJPFObject(env));
}
return objref;
}
}
| VerifiableAutonomy/mcapl | src/classes/ail/syntax/ast/Abstract_ListTermImpl.java | Java | gpl-3.0 | 6,090 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtCore/QStringListModel>
#include <QtCore/QSortFilterProxyModel>
#include <QtGui/QStandardItemModel>
#include <QtQuick/qquickview.h>
#include <QtQml/qqmlengine.h>
#include <QtQml/qqmlcontext.h>
#include <QtQml/qqmlexpression.h>
#include <QtQml/qqmlincubator.h>
#include <QtQuick/private/qquickitemview_p_p.h>
#include <QtQuick/private/qquicklistview_p.h>
#include <QtQuick/private/qquicktext_p.h>
#include <QtQml/private/qqmlobjectmodel_p.h>
#include <QtQml/private/qqmllistmodel_p.h>
#include <QtQml/private/qqmldelegatemodel_p.h>
#include "../../shared/util.h"
#include "../shared/viewtestutil.h"
#include "../shared/visualtestutil.h"
#include "incrementalmodel.h"
#include "proxytestinnermodel.h"
#include "randomsortmodel.h"
#include <math.h>
Q_DECLARE_METATYPE(Qt::LayoutDirection)
Q_DECLARE_METATYPE(QQuickItemView::VerticalLayoutDirection)
Q_DECLARE_METATYPE(QQuickItemView::PositionMode)
Q_DECLARE_METATYPE(QQuickListView::Orientation)
Q_DECLARE_METATYPE(QQuickFlickable::FlickableDirection)
Q_DECLARE_METATYPE(Qt::Key)
using namespace QQuickViewTestUtil;
using namespace QQuickVisualTestUtil;
#define SHARE_VIEWS
class tst_QQuickListView : public QQmlDataTest
{
Q_OBJECT
public:
tst_QQuickListView();
private slots:
void init();
void cleanupTestCase();
// Test QAbstractItemModel model types
void qAbstractItemModel_package_items();
void qAbstractItemModel_items();
void qAbstractItemModel_package_changed();
void qAbstractItemModel_changed();
void qAbstractItemModel_package_inserted();
void qAbstractItemModel_inserted();
void qAbstractItemModel_inserted_more();
void qAbstractItemModel_inserted_more_data();
void qAbstractItemModel_inserted_more_bottomToTop();
void qAbstractItemModel_inserted_more_bottomToTop_data();
void qAbstractItemModel_package_removed();
void qAbstractItemModel_removed();
void qAbstractItemModel_removed_more();
void qAbstractItemModel_removed_more_data();
void qAbstractItemModel_removed_more_bottomToTop();
void qAbstractItemModel_removed_more_bottomToTop_data();
void qAbstractItemModel_package_moved();
void qAbstractItemModel_package_moved_data();
void qAbstractItemModel_moved();
void qAbstractItemModel_moved_data();
void qAbstractItemModel_moved_bottomToTop();
void qAbstractItemModel_moved_bottomToTop_data();
void multipleChanges_condensed() { multipleChanges(true); }
void multipleChanges_condensed_data() { multipleChanges_data(); }
void multipleChanges_uncondensed() { multipleChanges(false); }
void multipleChanges_uncondensed_data() { multipleChanges_data(); }
void qAbstractItemModel_package_clear();
void qAbstractItemModel_clear();
void qAbstractItemModel_clear_bottomToTop();
void insertBeforeVisible();
void insertBeforeVisible_data();
void swapWithFirstItem();
void itemList();
void itemListFlicker();
void currentIndex_delayedItemCreation();
void currentIndex_delayedItemCreation_data();
void currentIndex();
void noCurrentIndex();
void keyNavigation();
void keyNavigation_data();
void enforceRange();
void enforceRange_withoutHighlight();
void spacing();
void qAbstractItemModel_package_sections();
void qAbstractItemModel_sections();
void sectionsPositioning();
void sectionsDelegate();
void sectionsDragOutsideBounds_data();
void sectionsDragOutsideBounds();
void sectionsDelegate_headerVisibility();
void sectionPropertyChange();
void sectionDelegateChange();
void sectionsItemInsertion();
void cacheBuffer();
void positionViewAtBeginningEnd();
void positionViewAtIndex();
void positionViewAtIndex_data();
void resetModel();
void propertyChanges();
void componentChanges();
void modelChanges();
void manualHighlight();
void initialZValues();
void initialZValues_data();
void header();
void header_data();
void header_delayItemCreation();
void headerChangesViewport();
void footer();
void footer_data();
void extents();
void extents_data();
void resetModel_headerFooter();
void resizeView();
void resizeViewAndRepaint();
void sizeLessThan1();
void QTBUG_14821();
void resizeDelegate();
void resizeFirstDelegate();
void repositionResizedDelegate();
void repositionResizedDelegate_data();
void QTBUG_16037();
void indexAt_itemAt_data();
void indexAt_itemAt();
void incrementalModel();
void onAdd();
void onAdd_data();
void onRemove();
void onRemove_data();
void attachedProperties_QTBUG_32836();
void rightToLeft();
void test_mirroring();
void margins();
void marginsResize();
void marginsResize_data();
void creationContext();
void snapToItem_data();
void snapToItem();
void snapOneItemResize_QTBUG_43555();
void snapOneItem_data();
void snapOneItem();
void snapOneItemCurrentIndexRemoveAnimation();
void QTBUG_9791();
void QTBUG_11105();
void QTBUG_21742();
void asynchronous();
void unrequestedVisibility();
void populateTransitions();
void populateTransitions_data();
void sizeTransitions();
void sizeTransitions_data();
void addTransitions();
void addTransitions_data();
void moveTransitions();
void moveTransitions_data();
void removeTransitions();
void removeTransitions_data();
void displacedTransitions();
void displacedTransitions_data();
void multipleTransitions();
void multipleTransitions_data();
void multipleDisplaced();
void flickBeyondBounds();
void flickBothDirections();
void flickBothDirections_data();
void destroyItemOnCreation();
void parentBinding();
void defaultHighlightMoveDuration();
void accessEmptyCurrentItem_QTBUG_30227();
void delayedChanges_QTBUG_30555();
void outsideViewportChangeNotAffectingView();
void testProxyModelChangedAfterMove();
void typedModel();
void displayMargin();
void negativeDisplayMargin();
void highlightItemGeometryChanges();
void QTBUG_36481();
void QTBUG_35920();
void stickyPositioning();
void stickyPositioning_data();
void roundingErrors();
void roundingErrors_data();
void QTBUG_38209();
void programmaticFlickAtBounds();
void programmaticFlickAtBounds2();
void layoutChange();
void QTBUG_39492_data();
void QTBUG_39492();
void jsArrayChange();
void objectModel();
void contentHeightWithDelayRemove();
void contentHeightWithDelayRemove_data();
void QTBUG_48044_currentItemNotVisibleAfterTransition();
void QTBUG_48870_fastModelUpdates();
void QTBUG_50105();
void keyNavigationEnabled();
void QTBUG_50097_stickyHeader_positionViewAtIndex();
void itemFiltered();
private:
template <class T> void items(const QUrl &source);
template <class T> void changed(const QUrl &source);
template <class T> void inserted(const QUrl &source);
template <class T> void inserted_more(QQuickItemView::VerticalLayoutDirection verticalLayoutDirection = QQuickItemView::TopToBottom);
template <class T> void removed(const QUrl &source, bool animated);
template <class T> void removed_more(const QUrl &source, QQuickItemView::VerticalLayoutDirection verticalLayoutDirection = QQuickItemView::TopToBottom);
template <class T> void moved(const QUrl &source, QQuickItemView::VerticalLayoutDirection verticalLayoutDirection = QQuickItemView::TopToBottom);
template <class T> void clear(const QUrl &source, QQuickItemView::VerticalLayoutDirection verticalLayoutDirection = QQuickItemView::TopToBottom);
template <class T> void sections(const QUrl &source);
void multipleChanges(bool condensed);
void multipleChanges_data();
QList<int> toIntList(const QVariantList &list);
void matchIndexLists(const QVariantList &indexLists, const QList<int> &expectedIndexes);
void matchItemsAndIndexes(const QVariantMap &items, const QaimModel &model, const QList<int> &expectedIndexes);
void matchItemLists(const QVariantList &itemLists, const QList<QQuickItem *> &expectedItems);
void inserted_more_data();
void removed_more_data();
void moved_data();
#ifdef SHARE_VIEWS
QQuickView *getView() {
if (m_view) {
if (QString(QTest::currentTestFunction()) != testForView) {
delete m_view;
m_view = 0;
} else {
m_view->setSource(QUrl());
return m_view;
}
}
testForView = QTest::currentTestFunction();
m_view = createView();
return m_view;
}
void releaseView(QQuickView *view) {
Q_ASSERT(view == m_view);
m_view->setSource(QUrl());
}
#else
QQuickView *getView() {
return createView();
}
void releaseView(QQuickView *view) {
delete view;
}
#endif
QQuickView *m_view;
QString testForView;
};
class TestObject : public QObject
{
Q_OBJECT
Q_PROPERTY(bool error READ error WRITE setError NOTIFY changedError)
Q_PROPERTY(bool animate READ animate NOTIFY changedAnim)
Q_PROPERTY(bool invalidHighlight READ invalidHighlight NOTIFY changedHl)
Q_PROPERTY(int cacheBuffer READ cacheBuffer NOTIFY changedCacheBuffer)
public:
TestObject(QObject *parent = 0)
: QObject(parent), mError(true), mAnimate(false), mInvalidHighlight(false)
, mCacheBuffer(0) {}
bool error() const { return mError; }
void setError(bool err) { mError = err; emit changedError(); }
bool animate() const { return mAnimate; }
void setAnimate(bool anim) { mAnimate = anim; emit changedAnim(); }
bool invalidHighlight() const { return mInvalidHighlight; }
void setInvalidHighlight(bool invalid) { mInvalidHighlight = invalid; emit changedHl(); }
int cacheBuffer() const { return mCacheBuffer; }
void setCacheBuffer(int buffer) { mCacheBuffer = buffer; emit changedCacheBuffer(); }
signals:
void changedError();
void changedAnim();
void changedHl();
void changedCacheBuffer();
public:
bool mError;
bool mAnimate;
bool mInvalidHighlight;
int mCacheBuffer;
};
tst_QQuickListView::tst_QQuickListView() : m_view(0)
{
}
void tst_QQuickListView::init()
{
#ifdef SHARE_VIEWS
if (m_view && QString(QTest::currentTestFunction()) != testForView) {
testForView = QString();
delete m_view;
m_view = 0;
}
#endif
qmlRegisterType<QAbstractItemModel>();
qmlRegisterType<ProxyTestInnerModel>("Proxy", 1, 0, "ProxyTestInnerModel");
qmlRegisterType<QSortFilterProxyModel>("Proxy", 1, 0, "QSortFilterProxyModel");
}
void tst_QQuickListView::cleanupTestCase()
{
#ifdef SHARE_VIEWS
testForView = QString();
delete m_view;
m_view = 0;
#endif
}
template <class T>
void tst_QQuickListView::items(const QUrl &source)
{
QScopedPointer<QQuickView> window(createView());
T model;
model.addItem("Fred", "12345");
model.addItem("John", "2345");
model.addItem("Bob", "54321");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(source);
qApp->processEvents();
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
listview->forceLayout();
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QMetaObject::invokeMethod(window->rootObject(), "checkProperties");
QTRY_VERIFY(!testObject->error());
QTRY_VERIFY(listview->highlightItem() != 0);
QTRY_COMPARE(listview->count(), model.count());
QTRY_COMPARE(window->rootObject()->property("count").toInt(), model.count());
listview->forceLayout();
QTRY_COMPARE(contentItem->childItems().count(), model.count()+1); // assumes all are visible, +1 for the (default) highlight item
// current item should be first item
QTRY_COMPARE(listview->currentItem(), findItem<QQuickItem>(contentItem, "wrapper", 0));
for (int i = 0; i < model.count(); ++i) {
QQuickText *name = findItem<QQuickText>(contentItem, "textName", i);
QTRY_VERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(i));
QQuickText *number = findItem<QQuickText>(contentItem, "textNumber", i);
QTRY_VERIFY(number != 0);
QTRY_COMPARE(number->text(), model.number(i));
}
// switch to other delegate
testObject->setAnimate(true);
QMetaObject::invokeMethod(window->rootObject(), "checkProperties");
QTRY_VERIFY(!testObject->error());
QTRY_VERIFY(listview->currentItem());
// set invalid highlight
testObject->setInvalidHighlight(true);
QMetaObject::invokeMethod(window->rootObject(), "checkProperties");
QTRY_VERIFY(!testObject->error());
QTRY_VERIFY(listview->currentItem());
QTRY_VERIFY(!listview->highlightItem());
// back to normal highlight
testObject->setInvalidHighlight(false);
QMetaObject::invokeMethod(window->rootObject(), "checkProperties");
QTRY_VERIFY(!testObject->error());
QTRY_VERIFY(listview->currentItem());
QTRY_VERIFY(listview->highlightItem() != 0);
// set an empty model and confirm that items are destroyed
T model2;
ctxt->setContextProperty("testModel", &model2);
// Force a layout, necessary if ListView is completed before VisualDataModel.
listview->forceLayout();
int itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
QTRY_COMPARE(itemCount, 0);
QTRY_COMPARE(listview->highlightResizeVelocity(), 1000.0);
QTRY_COMPARE(listview->highlightMoveVelocity(), 100000.0);
delete testObject;
}
template <class T>
void tst_QQuickListView::changed(const QUrl &source)
{
QScopedPointer<QQuickView> window(createView());
T model;
model.addItem("Fred", "12345");
model.addItem("John", "2345");
model.addItem("Bob", "54321");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(source);
qApp->processEvents();
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
listview->forceLayout();
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
// Force a layout, necessary if ListView is completed before VisualDataModel.
listview->forceLayout();
model.modifyItem(1, "Will", "9876");
QQuickText *name = findItem<QQuickText>(contentItem, "textName", 1);
QTRY_VERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(1));
QQuickText *number = findItem<QQuickText>(contentItem, "textNumber", 1);
QTRY_VERIFY(number != 0);
QTRY_COMPARE(number->text(), model.number(1));
delete testObject;
}
template <class T>
void tst_QQuickListView::inserted(const QUrl &source)
{
QScopedPointer<QQuickView> window(createView());
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
T model;
model.addItem("Fred", "12345");
model.addItem("John", "2345");
model.addItem("Bob", "54321");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(source);
qApp->processEvents();
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
model.insertItem(1, "Will", "9876");
QTRY_COMPARE(window->rootObject()->property("count").toInt(), model.count());
QTRY_COMPARE(contentItem->childItems().count(), model.count()+1); // assumes all are visible, +1 for the (default) highlight item
QQuickText *name = findItem<QQuickText>(contentItem, "textName", 1);
QTRY_VERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(1));
QQuickText *number = findItem<QQuickText>(contentItem, "textNumber", 1);
QTRY_VERIFY(number != 0);
QTRY_COMPARE(number->text(), model.number(1));
// Confirm items positioned correctly
for (int i = 0; i < model.count(); ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QTRY_COMPARE(item->y(), i*20.0);
}
model.insertItem(0, "Foo", "1111"); // zero index, and current item
QTRY_COMPARE(window->rootObject()->property("count").toInt(), model.count());
QTRY_COMPARE(contentItem->childItems().count(), model.count()+1); // assumes all are visible, +1 for the (default) highlight item
name = findItem<QQuickText>(contentItem, "textName", 0);
QTRY_VERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(0));
number = findItem<QQuickText>(contentItem, "textNumber", 0);
QTRY_VERIFY(number != 0);
QTRY_COMPARE(number->text(), model.number(0));
QTRY_COMPARE(listview->currentIndex(), 1);
// Confirm items positioned correctly
for (int i = 0; i < model.count(); ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QTRY_COMPARE(item->y(), i*20.0);
}
for (int i = model.count(); i < 30; ++i)
model.insertItem(i, "Hello", QString::number(i));
listview->setContentY(80);
// Insert item outside visible area
model.insertItem(1, "Hello", "1324");
QTRY_COMPARE(listview->contentY(), qreal(80));
// Confirm items positioned correctly
for (int i = 5; i < 5+15; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), i*20.0 - 20.0);
}
// QTRY_COMPARE(listview->contentItemHeight(), model.count() * 20.0);
// QTBUG-19675
model.clear();
model.insertItem(0, "Hello", "1234");
QTRY_COMPARE(window->rootObject()->property("count").toInt(), model.count());
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", 0);
QVERIFY(item);
QTRY_COMPARE(item->y() - listview->contentY(), 0.);
delete testObject;
}
template <class T>
void tst_QQuickListView::inserted_more(QQuickItemView::VerticalLayoutDirection verticalLayoutDirection)
{
QFETCH(qreal, contentY);
QFETCH(int, insertIndex);
QFETCH(int, insertCount);
QFETCH(qreal, itemsOffsetAfterMove);
T model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), "");
QQuickView *window = getView();
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(testFileUrl("listviewtest.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
if (verticalLayoutDirection == QQuickItemView::BottomToTop) {
listview->setVerticalLayoutDirection(verticalLayoutDirection);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
contentY = -listview->height() - contentY;
}
listview->setContentY(contentY);
QQuickItemViewPrivate::get(listview)->layout();
QList<QPair<QString, QString> > newData;
for (int i=0; i<insertCount; i++)
newData << qMakePair(QString("value %1").arg(i), QString::number(i));
model.insertItems(insertIndex, newData);
//Wait for polish (updates list to the model changes)
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QTRY_COMPARE(listview->property("count").toInt(), model.count());
// FIXME This is NOT checking anything about visibleItems.first()
#if 0
// check visibleItems.first() is in correct position
QQuickItem *item0 = findItem<QQuickItem>(contentItem, "wrapper", 0);
QVERIFY(item0);
if (verticalLayoutDirection == QQuickItemView::BottomToTop)
QCOMPARE(item0->y(), -item0->height() - itemsOffsetAfterMove);
else
QCOMPARE(item0->y(), itemsOffsetAfterMove);
#endif
QList<FxViewItem *> visibleItems = QQuickItemViewPrivate::get(listview)->visibleItems;
for (QList<FxViewItem *>::const_iterator itemIt = visibleItems.begin(); itemIt != visibleItems.end(); ++itemIt) {
FxViewItem *item = *itemIt;
if (item->item->position().y() >= 0 && item->item->position().y() < listview->height()) {
QVERIFY(!QQuickItemPrivate::get(item->item)->culled);
}
}
QList<QQuickItem*> items = findItems<QQuickItem>(contentItem, "wrapper");
int firstVisibleIndex = -1;
for (int i=0; i<items.count(); i++) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (item && !QQuickItemPrivate::get(item)->culled) {
firstVisibleIndex = i;
break;
}
}
QVERIFY2(firstVisibleIndex >= 0, QTest::toString(firstVisibleIndex));
// Confirm items positioned correctly and indexes correct
QQuickText *name;
QQuickText *number;
const qreal visibleFromPos = listview->contentY() - listview->displayMarginBeginning() - listview->cacheBuffer();
const qreal visibleToPos = listview->contentY() + listview->height() + listview->displayMarginEnd() + listview->cacheBuffer();
for (int i = firstVisibleIndex; i < model.count() && i < items.count(); ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY2(item, QTest::toString(QString("Item %1 not found").arg(i)));
qreal pos = i*20.0 + itemsOffsetAfterMove;
if (verticalLayoutDirection == QQuickItemView::BottomToTop)
pos = -item->height() - pos;
// Items outside the visible area (including cache buffer) should be skipped
if (pos > visibleToPos || pos < visibleFromPos) {
QTRY_VERIFY2(QQuickItemPrivate::get(item)->culled || item->y() < visibleFromPos || item->y() > visibleToPos,
QTest::toString(QString("index %5, y %1, from %2, to %3, expected pos %4, culled %6").
arg(item->y()).arg(visibleFromPos).arg(visibleToPos).arg(pos).arg(i).arg(bool(QQuickItemPrivate::get(item)->culled))));
continue;
}
QTRY_COMPARE(item->y(), pos);
name = findItem<QQuickText>(contentItem, "textName", i);
QVERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(i));
number = findItem<QQuickText>(contentItem, "textNumber", i);
QVERIFY(number != 0);
QTRY_COMPARE(number->text(), model.number(i));
}
releaseView(window);
delete testObject;
}
void tst_QQuickListView::inserted_more_data()
{
QTest::addColumn<qreal>("contentY");
QTest::addColumn<int>("insertIndex");
QTest::addColumn<int>("insertCount");
QTest::addColumn<qreal>("itemsOffsetAfterMove");
QTest::newRow("add 1, before visible items")
<< 80.0 // show 4-19
<< 3 << 1
<< -20.0; // insert above first visible i.e. 0 is at -20, first visible should not move
QTest::newRow("add multiple, before visible")
<< 80.0 // show 4-19
<< 3 << 3
<< -20.0 * 3; // again first visible should not move
QTest::newRow("add 1, at start of visible, content at start")
<< 0.0
<< 0 << 1
<< 0.0;
QTest::newRow("add multiple, start of visible, content at start")
<< 0.0
<< 0 << 3
<< 0.0;
QTest::newRow("add 1, at start of visible, content not at start")
<< 80.0 // show 4-19
<< 4 << 1
<< 0.0;
QTest::newRow("add multiple, at start of visible, content not at start")
<< 80.0 // show 4-19
<< 4 << 3
<< 0.0;
QTest::newRow("add 1, at end of visible, content at start")
<< 0.0
<< 15 << 1
<< 0.0;
QTest::newRow("add multiple, at end of visible, content at start")
<< 0.0
<< 15 << 3
<< 0.0;
QTest::newRow("add 1, at end of visible, content not at start")
<< 80.0 // show 4-19
<< 19 << 1
<< 0.0;
QTest::newRow("add multiple, at end of visible, content not at start")
<< 80.0 // show 4-19
<< 19 << 3
<< 0.0;
QTest::newRow("add 1, after visible, content at start")
<< 0.0
<< 16 << 1
<< 0.0;
QTest::newRow("add multiple, after visible, content at start")
<< 0.0
<< 16 << 3
<< 0.0;
QTest::newRow("add 1, after visible, content not at start")
<< 80.0 // show 4-19
<< 20 << 1
<< 0.0;
QTest::newRow("add multiple, after visible, content not at start")
<< 80.0 // show 4-19
<< 20 << 3
<< 0.0;
QTest::newRow("add multiple, within visible, content at start")
<< 0.0
<< 2 << 50
<< 0.0;
}
void tst_QQuickListView::insertBeforeVisible()
{
QFETCH(int, insertIndex);
QFETCH(int, insertCount);
QFETCH(int, removeIndex);
QFETCH(int, removeCount);
QFETCH(int, cacheBuffer);
QQuickText *name;
QQuickView *window = getView();
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(testFileUrl("listviewtest.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
listview->setCacheBuffer(cacheBuffer);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// trigger a refill (not just setting contentY) so that the visibleItems grid is updated
int firstVisibleIndex = 20; // move to an index where the top item is not visible
listview->setContentY(firstVisibleIndex * 20.0);
listview->setCurrentIndex(firstVisibleIndex);
qApp->processEvents();
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QTRY_COMPARE(listview->currentIndex(), firstVisibleIndex);
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", firstVisibleIndex);
QVERIFY(item);
QCOMPARE(item->y(), listview->contentY());
if (removeCount > 0)
model.removeItems(removeIndex, removeCount);
if (insertCount > 0) {
QList<QPair<QString, QString> > newData;
for (int i=0; i<insertCount; i++)
newData << qMakePair(QString("value %1").arg(i), QString::number(i));
model.insertItems(insertIndex, newData);
QTRY_COMPARE(listview->property("count").toInt(), model.count());
}
// now, moving to the top of the view should position the inserted items correctly
int itemsOffsetAfterMove = (removeCount - insertCount) * 20;
listview->setCurrentIndex(0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QTRY_COMPARE(listview->currentIndex(), 0);
QTRY_COMPARE(listview->contentY(), 0.0 + itemsOffsetAfterMove);
// Confirm items positioned correctly and indexes correct
int itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i = 0; i < model.count() && i < itemCount; ++i) {
item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY2(item, QTest::toString(QString("Item %1 not found").arg(i)));
QTRY_COMPARE(item->y(), i*20.0 + itemsOffsetAfterMove);
name = findItem<QQuickText>(contentItem, "textName", i);
QVERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(i));
}
releaseView(window);
delete testObject;
}
void tst_QQuickListView::insertBeforeVisible_data()
{
QTest::addColumn<int>("insertIndex");
QTest::addColumn<int>("insertCount");
QTest::addColumn<int>("removeIndex");
QTest::addColumn<int>("removeCount");
QTest::addColumn<int>("cacheBuffer");
QTest::newRow("insert 1 at 0, 0 buffer") << 0 << 1 << 0 << 0 << 0;
QTest::newRow("insert 1 at 0, 100 buffer") << 0 << 1 << 0 << 0 << 100;
QTest::newRow("insert 1 at 0, 500 buffer") << 0 << 1 << 0 << 0 << 500;
QTest::newRow("insert 1 at 1, 0 buffer") << 1 << 1 << 0 << 0 << 0;
QTest::newRow("insert 1 at 1, 100 buffer") << 1 << 1 << 0 << 0 << 100;
QTest::newRow("insert 1 at 1, 500 buffer") << 1 << 1 << 0 << 0 << 500;
QTest::newRow("insert multiple at 0, 0 buffer") << 0 << 3 << 0 << 0 << 0;
QTest::newRow("insert multiple at 0, 100 buffer") << 0 << 3 << 0 << 0 << 100;
QTest::newRow("insert multiple at 0, 500 buffer") << 0 << 3 << 0 << 0 << 500;
QTest::newRow("insert multiple at 1, 0 buffer") << 1 << 3 << 0 << 0 << 0;
QTest::newRow("insert multiple at 1, 100 buffer") << 1 << 3 << 0 << 0 << 100;
QTest::newRow("insert multiple at 1, 500 buffer") << 1 << 3 << 0 << 0 << 500;
QTest::newRow("remove 1 at 0, 0 buffer") << 0 << 0 << 0 << 1 << 0;
QTest::newRow("remove 1 at 0, 100 buffer") << 0 << 0 << 0 << 1 << 100;
QTest::newRow("remove 1 at 0, 500 buffer") << 0 << 0 << 0 << 1 << 500;
QTest::newRow("remove 1 at 1, 0 buffer") << 0 << 0 << 1 << 1 << 0;
QTest::newRow("remove 1 at 1, 100 buffer") << 0 << 0 << 1 << 1 << 100;
QTest::newRow("remove 1 at 1, 500 buffer") << 0 << 0 << 1 << 1 << 500;
QTest::newRow("remove multiple at 0, 0 buffer") << 0 << 0 << 0 << 3 << 0;
QTest::newRow("remove multiple at 0, 100 buffer") << 0 << 0 << 0 << 3 << 100;
QTest::newRow("remove multiple at 0, 500 buffer") << 0 << 0 << 0 << 3 << 500;
QTest::newRow("remove multiple at 1, 0 buffer") << 0 << 0 << 1 << 3 << 0;
QTest::newRow("remove multiple at 1, 100 buffer") << 0 << 0 << 1 << 3 << 100;
QTest::newRow("remove multiple at 1, 500 buffer") << 0 << 0 << 1 << 3 << 500;
}
template <class T>
void tst_QQuickListView::removed(const QUrl &source, bool /* animated */)
{
QScopedPointer<QQuickView> window(createView());
T model;
for (int i = 0; i < 50; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(source);
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
model.removeItem(1);
QTRY_COMPARE(window->rootObject()->property("count").toInt(), model.count());
QQuickText *name = findItem<QQuickText>(contentItem, "textName", 1);
QTRY_VERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(1));
QQuickText *number = findItem<QQuickText>(contentItem, "textNumber", 1);
QTRY_VERIFY(number != 0);
QTRY_COMPARE(number->text(), model.number(1));
// Confirm items positioned correctly
int itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i = 0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), qreal(i*20));
}
// Remove first item (which is the current item);
model.removeItem(0);
QTRY_COMPARE(window->rootObject()->property("count").toInt(), model.count());
name = findItem<QQuickText>(contentItem, "textName", 0);
QTRY_VERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(0));
number = findItem<QQuickText>(contentItem, "textNumber", 0);
QTRY_VERIFY(number != 0);
QTRY_COMPARE(number->text(), model.number(0));
// Confirm items positioned correctly
itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i = 0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(),i*20.0);
}
// Remove items not visible
model.removeItem(18);
QTRY_COMPARE(window->rootObject()->property("count").toInt(), model.count());
// Confirm items positioned correctly
itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i = 0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(),i*20.0);
}
// Remove items before visible
listview->setContentY(80);
listview->setCurrentIndex(10);
model.removeItem(1); // post: top item will be at 20
QTRY_COMPARE(window->rootObject()->property("count").toInt(), model.count());
// Confirm items positioned correctly
for (int i = 2; i < 18; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(),20+i*20.0);
}
// Remove current index
QTRY_COMPARE(listview->currentIndex(), 9);
QQuickItem *oldCurrent = listview->currentItem();
model.removeItem(9);
QTRY_COMPARE(listview->currentIndex(), 9);
QTRY_VERIFY(listview->currentItem() != oldCurrent);
listview->setContentY(20); // That's the top now
// let transitions settle.
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// Confirm items positioned correctly
itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i = 0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(),20+i*20.0);
}
// remove current item beyond visible items.
listview->setCurrentIndex(20);
listview->setContentY(40);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
model.removeItem(20);
QTRY_COMPARE(listview->currentIndex(), 20);
QTRY_VERIFY(listview->currentItem() != 0);
// remove item before current, but visible
listview->setCurrentIndex(8);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
oldCurrent = listview->currentItem();
model.removeItem(6);
QTRY_COMPARE(listview->currentIndex(), 7);
QTRY_COMPARE(listview->currentItem(), oldCurrent);
listview->setContentY(80);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// remove all visible items
model.removeItems(1, 18);
QTRY_COMPARE(listview->count() , model.count());
// Confirm items positioned correctly
itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i = 0; i < model.count() && i < itemCount-1; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i+1);
if (!item) qWarning() << "Item" << i+1 << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(),80+i*20.0);
}
model.removeItems(1, 17);
QTRY_COMPARE(listview->count() , model.count());
model.removeItems(2, 1);
QTRY_COMPARE(listview->count() , model.count());
model.addItem("New", "1");
QTRY_COMPARE(listview->count() , model.count());
QTRY_VERIFY(name = findItem<QQuickText>(contentItem, "textName", model.count()-1));
QCOMPARE(name->text(), QString("New"));
// Add some more items so that we don't run out
model.clear();
for (int i = 0; i < 50; i++)
model.addItem("Item" + QString::number(i), "");
// QTBUG-QTBUG-20575
listview->setCurrentIndex(0);
listview->setContentY(30);
model.removeItem(0);
QTRY_VERIFY(name = findItem<QQuickText>(contentItem, "textName", 0));
// QTBUG-19198 move to end and remove all visible items one at a time.
listview->positionViewAtEnd();
for (int i = 0; i < 18; ++i)
model.removeItems(model.count() - 1, 1);
QTRY_VERIFY(findItems<QQuickItem>(contentItem, "wrapper").count() > 16);
delete testObject;
}
template <class T>
void tst_QQuickListView::removed_more(const QUrl &source, QQuickItemView::VerticalLayoutDirection verticalLayoutDirection)
{
QFETCH(qreal, contentY);
QFETCH(int, removeIndex);
QFETCH(int, removeCount);
QFETCH(qreal, itemsOffsetAfterMove);
QQuickView *window = getView();
T model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(source);
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
if (verticalLayoutDirection == QQuickItemView::BottomToTop) {
listview->setVerticalLayoutDirection(verticalLayoutDirection);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
contentY = -listview->height() - contentY;
}
listview->setContentY(contentY);
model.removeItems(removeIndex, removeCount);
//Wait for polish (updates list to the model changes)
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QTRY_COMPARE(listview->property("count").toInt(), model.count());
// check visibleItems.first() is in correct position
QQuickItem *item0 = findItem<QQuickItem>(contentItem, "wrapper", 0);
QVERIFY(item0);
QVERIFY(item0);
if (verticalLayoutDirection == QQuickItemView::BottomToTop)
QCOMPARE(item0->y(), -item0->height() - itemsOffsetAfterMove);
else
QCOMPARE(item0->y(), itemsOffsetAfterMove);
QList<QQuickItem*> items = findItems<QQuickItem>(contentItem, "wrapper");
int firstVisibleIndex = -1;
for (int i=0; i<items.count(); i++) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (item && delegateVisible(item)) {
firstVisibleIndex = i;
break;
}
}
QVERIFY2(firstVisibleIndex >= 0, QTest::toString(firstVisibleIndex));
// Confirm items positioned correctly and indexes correct
QQuickText *name;
QQuickText *number;
for (int i = firstVisibleIndex; i < model.count() && i < items.count(); ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY2(item, QTest::toString(QString("Item %1 not found").arg(i)));
qreal pos = i*20.0 + itemsOffsetAfterMove;
if (verticalLayoutDirection == QQuickItemView::BottomToTop)
pos = -item0->height() - pos;
QTRY_COMPARE(item->y(), pos);
name = findItem<QQuickText>(contentItem, "textName", i);
QVERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(i));
number = findItem<QQuickText>(contentItem, "textNumber", i);
QVERIFY(number != 0);
QTRY_COMPARE(number->text(), model.number(i));
}
releaseView(window);
delete testObject;
}
void tst_QQuickListView::removed_more_data()
{
QTest::addColumn<qreal>("contentY");
QTest::addColumn<int>("removeIndex");
QTest::addColumn<int>("removeCount");
QTest::addColumn<qreal>("itemsOffsetAfterMove");
QTest::newRow("remove 1, before visible items")
<< 80.0 // show 4-19
<< 3 << 1
<< 20.0; // visible items slide down by 1 item so that first visible does not move
QTest::newRow("remove multiple, all before visible items")
<< 80.0
<< 1 << 3
<< 20.0 * 3;
QTest::newRow("remove multiple, all before visible items, remove item 0")
<< 80.0
<< 0 << 4
<< 20.0 * 4;
// remove 1,2,3 before the visible pos, 0 moves down to just before the visible pos,
// items 4,5 are removed from view, item 6 slides up to original pos of item 4 (80px)
QTest::newRow("remove multiple, mix of items from before and within visible items")
<< 80.0
<< 1 << 5
<< 20.0 * 3; // adjust for the 3 items removed before the visible
QTest::newRow("remove multiple, mix of items from before and within visible items, remove item 0")
<< 80.0
<< 0 << 6
<< 20.0 * 4; // adjust for the 3 items removed before the visible
QTest::newRow("remove 1, from start of visible, content at start")
<< 0.0
<< 0 << 1
<< 0.0;
QTest::newRow("remove multiple, from start of visible, content at start")
<< 0.0
<< 0 << 3
<< 0.0;
QTest::newRow("remove 1, from start of visible, content not at start")
<< 80.0 // show 4-19
<< 4 << 1
<< 0.0;
QTest::newRow("remove multiple, from start of visible, content not at start")
<< 80.0 // show 4-19
<< 4 << 3
<< 0.0;
QTest::newRow("remove 1, from middle of visible, content at start")
<< 0.0
<< 10 << 1
<< 0.0;
QTest::newRow("remove multiple, from middle of visible, content at start")
<< 0.0
<< 10 << 5
<< 0.0;
QTest::newRow("remove 1, from middle of visible, content not at start")
<< 80.0 // show 4-19
<< 10 << 1
<< 0.0;
QTest::newRow("remove multiple, from middle of visible, content not at start")
<< 80.0 // show 4-19
<< 10 << 5
<< 0.0;
QTest::newRow("remove 1, after visible, content at start")
<< 0.0
<< 16 << 1
<< 0.0;
QTest::newRow("remove multiple, after visible, content at start")
<< 0.0
<< 16 << 5
<< 0.0;
QTest::newRow("remove 1, after visible, content not at middle")
<< 80.0 // show 4-19
<< 16+4 << 1
<< 0.0;
QTest::newRow("remove multiple, after visible, content not at start")
<< 80.0 // show 4-19
<< 16+4 << 5
<< 0.0;
QTest::newRow("remove multiple, mix of items from within and after visible items")
<< 80.0
<< 18 << 5
<< 0.0;
}
template <class T>
void tst_QQuickListView::clear(const QUrl &source, QQuickItemView::VerticalLayoutDirection verticalLayoutDirection)
{
QScopedPointer<QQuickView> window(createView());
T model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(source);
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
listview->setVerticalLayoutDirection(verticalLayoutDirection);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
model.clear();
QTRY_COMPARE(findItems<QQuickListView>(contentItem, "wrapper").count(), 0);
QTRY_COMPARE(listview->count(), 0);
QTRY_VERIFY(!listview->currentItem());
if (verticalLayoutDirection == QQuickItemView::TopToBottom)
QTRY_COMPARE(listview->contentY(), 0.0);
else
QTRY_COMPARE(listview->contentY(), -listview->height());
QCOMPARE(listview->currentIndex(), -1);
QCOMPARE(listview->contentHeight(), 0.0);
// confirm sanity when adding an item to cleared list
model.addItem("New", "1");
listview->forceLayout();
QTRY_COMPARE(listview->count(), 1);
QVERIFY(listview->currentItem() != 0);
QCOMPARE(listview->currentIndex(), 0);
delete testObject;
}
template <class T>
void tst_QQuickListView::moved(const QUrl &source, QQuickItemView::VerticalLayoutDirection verticalLayoutDirection)
{
QFETCH(qreal, contentY);
QFETCH(int, from);
QFETCH(int, to);
QFETCH(int, count);
QFETCH(qreal, itemsOffsetAfterMove);
QQuickText *name;
QQuickText *number;
QQuickView *window = getView();
T model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(source);
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
// always need to wait for view to be painted before the first move()
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
bool waitForPolish = (contentY != 0);
if (verticalLayoutDirection == QQuickItemView::BottomToTop) {
listview->setVerticalLayoutDirection(verticalLayoutDirection);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
contentY = -listview->height() - contentY;
}
listview->setContentY(contentY);
if (waitForPolish)
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
model.moveItems(from, to, count);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QList<QQuickItem*> items = findItems<QQuickItem>(contentItem, "wrapper");
int firstVisibleIndex = -1;
for (int i=0; i<items.count(); i++) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (item && delegateVisible(item)) {
firstVisibleIndex = i;
break;
}
}
QVERIFY2(firstVisibleIndex >= 0, QTest::toString(firstVisibleIndex));
// Confirm items positioned correctly and indexes correct
for (int i = firstVisibleIndex; i < model.count() && i < items.count(); ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY2(item, QTest::toString(QString("Item %1 not found").arg(i)));
qreal pos = i*20.0 + itemsOffsetAfterMove;
if (verticalLayoutDirection == QQuickItemView::BottomToTop)
pos = -item->height() - pos;
QTRY_COMPARE(item->y(), pos);
name = findItem<QQuickText>(contentItem, "textName", i);
QVERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(i));
number = findItem<QQuickText>(contentItem, "textNumber", i);
QVERIFY(number != 0);
QTRY_COMPARE(number->text(), model.number(i));
// current index should have been updated
if (item == listview->currentItem())
QTRY_COMPARE(listview->currentIndex(), i);
}
releaseView(window);
delete testObject;
}
void tst_QQuickListView::moved_data()
{
QTest::addColumn<qreal>("contentY");
QTest::addColumn<int>("from");
QTest::addColumn<int>("to");
QTest::addColumn<int>("count");
QTest::addColumn<qreal>("itemsOffsetAfterMove");
// model starts with 30 items, each 20px high, in area 320px high
// 16 items should be visible at a time
// itemsOffsetAfterMove should be > 0 whenever items above the visible pos have moved
QTest::newRow("move 1 forwards, within visible items")
<< 0.0
<< 1 << 4 << 1
<< 0.0;
QTest::newRow("move 1 forwards, from non-visible -> visible")
<< 80.0 // show 4-19
<< 1 << 18 << 1
<< 20.0; // removed 1 item above the first visible, so item 0 should drop down by 1 to minimize movement
QTest::newRow("move 1 forwards, from non-visible -> visible (move first item)")
<< 80.0 // show 4-19
<< 0 << 4 << 1
<< 20.0; // first item has moved to below item4, everything drops down by size of 1 item
QTest::newRow("move 1 forwards, from visible -> non-visible")
<< 0.0
<< 1 << 16 << 1
<< 0.0;
QTest::newRow("move 1 forwards, from visible -> non-visible (move first item)")
<< 0.0
<< 0 << 16 << 1
<< 0.0;
QTest::newRow("move 1 backwards, within visible items")
<< 0.0
<< 4 << 1 << 1
<< 0.0;
QTest::newRow("move 1 backwards, within visible items (to first index)")
<< 0.0
<< 4 << 0 << 1
<< 0.0;
QTest::newRow("move 1 backwards, from non-visible -> visible")
<< 0.0
<< 20 << 4 << 1
<< 0.0;
QTest::newRow("move 1 backwards, from non-visible -> visible (move last item)")
<< 0.0
<< 29 << 15 << 1
<< 0.0;
QTest::newRow("move 1 backwards, from visible -> non-visible")
<< 80.0 // show 4-19
<< 16 << 1 << 1
<< -20.0; // to minimize movement, item 0 moves to -20, and other items do not move
QTest::newRow("move 1 backwards, from visible -> non-visible (move first item)")
<< 80.0 // show 4-19
<< 16 << 0 << 1
<< -20.0; // to minimize movement, item 16 (now at 0) moves to -20, and other items do not move
QTest::newRow("move multiple forwards, within visible items")
<< 0.0
<< 0 << 5 << 3
<< 0.0;
QTest::newRow("move multiple forwards, before visible items")
<< 140.0 // show 7-22
<< 4 << 5 << 3 // 4,5,6 move to below 7
<< 20.0 * 3; // 4,5,6 moved down
QTest::newRow("move multiple forwards, from non-visible -> visible")
<< 80.0 // show 4-19
<< 1 << 5 << 3
<< 20.0 * 3; // moving 3 from above the content y should adjust y positions accordingly
QTest::newRow("move multiple forwards, from non-visible -> visible (move first item)")
<< 80.0 // show 4-19
<< 0 << 5 << 3
<< 20.0 * 3; // moving 3 from above the content y should adjust y positions accordingly
QTest::newRow("move multiple forwards, mix of non-visible/visible")
<< 40.0
<< 1 << 16 << 2
<< 20.0; // item 1,2 are removed, item 3 is now first visible
QTest::newRow("move multiple forwards, to bottom of view")
<< 0.0
<< 5 << 13 << 3
<< 0.0;
QTest::newRow("move multiple forwards, to bottom of view, first->last")
<< 0.0
<< 0 << 13 << 3
<< 0.0;
QTest::newRow("move multiple forwards, to bottom of view, content y not 0")
<< 80.0
<< 5+4 << 13+4 << 3
<< 0.0;
QTest::newRow("move multiple forwards, from visible -> non-visible")
<< 0.0
<< 1 << 16 << 3
<< 0.0;
QTest::newRow("move multiple forwards, from visible -> non-visible (move first item)")
<< 0.0
<< 0 << 16 << 3
<< 0.0;
QTest::newRow("move multiple backwards, within visible items")
<< 0.0
<< 4 << 1 << 3
<< 0.0;
QTest::newRow("move multiple backwards, within visible items (move first item)")
<< 0.0
<< 10 << 0 << 3
<< 0.0;
QTest::newRow("move multiple backwards, from non-visible -> visible")
<< 0.0
<< 20 << 4 << 3
<< 0.0;
QTest::newRow("move multiple backwards, from non-visible -> visible (move last item)")
<< 0.0
<< 27 << 10 << 3
<< 0.0;
QTest::newRow("move multiple backwards, from visible -> non-visible")
<< 80.0 // show 4-19
<< 16 << 1 << 3
<< -20.0 * 3; // to minimize movement, 0 moves by -60, and other items do not move
QTest::newRow("move multiple backwards, from visible -> non-visible (move first item)")
<< 80.0 // show 4-19
<< 16 << 0 << 3
<< -20.0 * 3; // to minimize movement, 16,17,18 move to above item 0, and other items do not move
}
void tst_QQuickListView::multipleChanges(bool condensed)
{
QFETCH(int, startCount);
QFETCH(QList<ListChange>, changes);
QFETCH(int, newCount);
QFETCH(int, newCurrentIndex);
QQuickView *window = getView();
QaimModel model;
for (int i = 0; i < startCount; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(testFileUrl("listviewtest.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
for (int i=0; i<changes.count(); i++) {
switch (changes[i].type) {
case ListChange::Inserted:
{
QList<QPair<QString, QString> > items;
for (int j=changes[i].index; j<changes[i].index + changes[i].count; ++j)
items << qMakePair(QString("new item %1").arg(j), QString::number(j));
model.insertItems(changes[i].index, items);
break;
}
case ListChange::Removed:
model.removeItems(changes[i].index, changes[i].count);
break;
case ListChange::Moved:
model.moveItems(changes[i].index, changes[i].to, changes[i].count);
break;
case ListChange::SetCurrent:
listview->setCurrentIndex(changes[i].index);
break;
case ListChange::SetContentY:
listview->setContentY(changes[i].pos);
break;
default:
continue;
}
if (!condensed) {
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
}
}
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QCOMPARE(listview->count(), newCount);
QCOMPARE(listview->count(), model.count());
QCOMPARE(listview->currentIndex(), newCurrentIndex);
QQuickText *name;
QQuickText *number;
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
int itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i=0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY2(item, QTest::toString(QString("Item %1 not found").arg(i)));
name = findItem<QQuickText>(contentItem, "textName", i);
QVERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(i));
number = findItem<QQuickText>(contentItem, "textNumber", i);
QVERIFY(number != 0);
QTRY_COMPARE(number->text(), model.number(i));
}
delete testObject;
releaseView(window);
}
void tst_QQuickListView::multipleChanges_data()
{
QTest::addColumn<int>("startCount");
QTest::addColumn<QList<ListChange> >("changes");
QTest::addColumn<int>("newCount");
QTest::addColumn<int>("newCurrentIndex");
QList<ListChange> changes;
for (int i=1; i<30; i++)
changes << ListChange::remove(0);
QTest::newRow("remove all but 1, first->last") << 30 << changes << 1 << 0;
changes << ListChange::remove(0);
QTest::newRow("remove all") << 30 << changes << 0 << -1;
changes.clear();
changes << ListChange::setCurrent(29);
for (int i=29; i>0; i--)
changes << ListChange::remove(i);
QTest::newRow("remove last (current) -> first") << 30 << changes << 1 << 0;
QTest::newRow("remove then insert at 0") << 10 << (QList<ListChange>()
<< ListChange::remove(0, 1)
<< ListChange::insert(0, 1)
) << 10 << 1;
QTest::newRow("remove then insert at non-zero index") << 10 << (QList<ListChange>()
<< ListChange::setCurrent(2)
<< ListChange::remove(2, 1)
<< ListChange::insert(2, 1)
) << 10 << 3;
QTest::newRow("remove current then insert below it") << 10 << (QList<ListChange>()
<< ListChange::setCurrent(1)
<< ListChange::remove(1, 3)
<< ListChange::insert(2, 2)
) << 9 << 1;
QTest::newRow("remove current index then move it down") << 10 << (QList<ListChange>()
<< ListChange::setCurrent(2)
<< ListChange::remove(1, 3)
<< ListChange::move(1, 5, 1)
) << 7 << 5;
QTest::newRow("remove current index then move it up") << 10 << (QList<ListChange>()
<< ListChange::setCurrent(5)
<< ListChange::remove(4, 3)
<< ListChange::move(4, 1, 1)
) << 7 << 1;
QTest::newRow("insert multiple times") << 0 << (QList<ListChange>()
<< ListChange::insert(0, 2)
<< ListChange::insert(0, 4)
<< ListChange::insert(0, 6)
) << 12 << 10;
QTest::newRow("insert multiple times with current index changes") << 0 << (QList<ListChange>()
<< ListChange::insert(0, 2)
<< ListChange::insert(0, 4)
<< ListChange::insert(0, 6)
<< ListChange::setCurrent(3)
<< ListChange::insert(3, 2)
) << 14 << 5;
QTest::newRow("insert and remove all") << 0 << (QList<ListChange>()
<< ListChange::insert(0, 30)
<< ListChange::remove(0, 30)
) << 0 << -1;
QTest::newRow("insert and remove current") << 30 << (QList<ListChange>()
<< ListChange::insert(1)
<< ListChange::setCurrent(1)
<< ListChange::remove(1)
) << 30 << 1;
QTest::newRow("insert before 0, then remove cross section of new and old items") << 10 << (QList<ListChange>()
<< ListChange::insert(0, 10)
<< ListChange::remove(5, 10)
) << 10 << 5;
QTest::newRow("insert multiple, then move new items to end") << 10 << (QList<ListChange>()
<< ListChange::insert(0, 3)
<< ListChange::move(0, 10, 3)
) << 13 << 0;
QTest::newRow("insert multiple, then move new and some old items to end") << 10 << (QList<ListChange>()
<< ListChange::insert(0, 3)
<< ListChange::move(0, 8, 5)
) << 13 << 11;
QTest::newRow("insert multiple at end, then move new and some old items to start") << 10 << (QList<ListChange>()
<< ListChange::setCurrent(9)
<< ListChange::insert(10, 3)
<< ListChange::move(8, 0, 5)
) << 13 << 1;
QTest::newRow("move back and forth to same index") << 10 << (QList<ListChange>()
<< ListChange::setCurrent(1)
<< ListChange::move(1, 2, 2)
<< ListChange::move(2, 1, 2)
) << 10 << 1;
QTest::newRow("move forwards then back") << 10 << (QList<ListChange>()
<< ListChange::setCurrent(2)
<< ListChange::move(1, 2, 3)
<< ListChange::move(3, 0, 5)
) << 10 << 0;
QTest::newRow("move current, then remove it") << 10 << (QList<ListChange>()
<< ListChange::setCurrent(5)
<< ListChange::move(5, 0, 1)
<< ListChange::remove(0)
) << 9 << 0;
QTest::newRow("move current, then insert before it") << 10 << (QList<ListChange>()
<< ListChange::setCurrent(5)
<< ListChange::move(5, 0, 1)
<< ListChange::insert(0)
) << 11 << 1;
QTest::newRow("move multiple, then remove them") << 10 << (QList<ListChange>()
<< ListChange::setCurrent(1)
<< ListChange::move(5, 1, 3)
<< ListChange::remove(1, 3)
) << 7 << 1;
QTest::newRow("move multiple, then insert before them") << 10 << (QList<ListChange>()
<< ListChange::setCurrent(5)
<< ListChange::move(5, 1, 3)
<< ListChange::insert(1, 5)
) << 15 << 6;
QTest::newRow("move multiple, then insert after them") << 10 << (QList<ListChange>()
<< ListChange::setCurrent(3)
<< ListChange::move(0, 1, 2)
<< ListChange::insert(3, 5)
) << 15 << 8;
QTest::newRow("clear current") << 0 << (QList<ListChange>()
<< ListChange::insert(0, 5)
<< ListChange::setCurrent(-1)
<< ListChange::remove(0, 5)
<< ListChange::insert(0, 5)
) << 5 << -1;
QTest::newRow("remove, scroll") << 30 << (QList<ListChange>()
<< ListChange::remove(20, 5)
<< ListChange::setContentY(20)
) << 25 << 0;
QTest::newRow("insert, scroll") << 10 << (QList<ListChange>()
<< ListChange::insert(9, 5)
<< ListChange::setContentY(20)
) << 15 << 0;
QTest::newRow("move, scroll") << 20 << (QList<ListChange>()
<< ListChange::move(15, 8, 3)
<< ListChange::setContentY(0)
) << 20 << 0;
QTest::newRow("clear, insert, scroll") << 30 << (QList<ListChange>()
<< ListChange::setContentY(20)
<< ListChange::remove(0, 30)
<< ListChange::insert(0, 2)
<< ListChange::setContentY(0)
) << 2 << 0;
}
void tst_QQuickListView::swapWithFirstItem()
{
QScopedPointer<QQuickView> window(createView());
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(testFileUrl("listviewtest.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// ensure content position is stable
listview->setContentY(0);
model.moveItem(1, 0);
QTRY_COMPARE(listview->contentY(), qreal(0));
delete testObject;
}
void tst_QQuickListView::enforceRange()
{
QScopedPointer<QQuickView> window(createView());
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
window->setSource(testFileUrl("listview-enforcerange.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QTRY_COMPARE(listview->preferredHighlightBegin(), 100.0);
QTRY_COMPARE(listview->preferredHighlightEnd(), 100.0);
QTRY_COMPARE(listview->highlightRangeMode(), QQuickListView::StrictlyEnforceRange);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
// view should be positioned at the top of the range.
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", 0);
QTRY_VERIFY(item);
QTRY_COMPARE(listview->contentY(), -100.0);
QQuickText *name = findItem<QQuickText>(contentItem, "textName", 0);
QTRY_VERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(0));
QQuickText *number = findItem<QQuickText>(contentItem, "textNumber", 0);
QTRY_VERIFY(number != 0);
QTRY_COMPARE(number->text(), model.number(0));
// Check currentIndex is updated when contentItem moves
listview->setContentY(20);
QTRY_COMPARE(listview->currentIndex(), 6);
// change model
QaimModel model2;
for (int i = 0; i < 5; i++)
model2.addItem("Item" + QString::number(i), "");
ctxt->setContextProperty("testModel", &model2);
QCOMPARE(listview->count(), 5);
}
void tst_QQuickListView::enforceRange_withoutHighlight()
{
// QTBUG-20287
// If no highlight is set but StrictlyEnforceRange is used, the content should still move
// to the correct position (i.e. to the next/previous item, not next/previous section)
// when moving up/down via incrementCurrentIndex() and decrementCurrentIndex()
QScopedPointer<QQuickView> window(createView());
QaimModel model;
model.addItem("Item 0", "a");
model.addItem("Item 1", "b");
model.addItem("Item 2", "b");
model.addItem("Item 3", "c");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
window->setSource(testFileUrl("listview-enforcerange-nohighlight.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
qreal expectedPos = -100.0;
expectedPos += 10.0; // scroll past 1st section's delegate (10px height)
QTRY_COMPARE(listview->contentY(), expectedPos);
expectedPos += 20 + 10; // scroll past 1st section and section delegate of 2nd section
QTest::keyClick(window.data(), Qt::Key_Down);
QTRY_COMPARE(listview->contentY(), expectedPos);
expectedPos += 20; // scroll past 1st item of 2nd section
QTest::keyClick(window.data(), Qt::Key_Down);
QTRY_COMPARE(listview->contentY(), expectedPos);
expectedPos += 20 + 10; // scroll past 2nd item of 2nd section and section delegate of 3rd section
QTest::keyClick(window.data(), Qt::Key_Down);
QTRY_COMPARE(listview->contentY(), expectedPos);
}
void tst_QQuickListView::spacing()
{
QScopedPointer<QQuickView> window(createView());
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(testFileUrl("listviewtest.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// Confirm items positioned correctly
int itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i = 0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), qreal(i*20));
}
listview->setSpacing(10);
QTRY_COMPARE(listview->spacing(), qreal(10));
// Confirm items positioned correctly
QTRY_VERIFY(findItems<QQuickItem>(contentItem, "wrapper").count() == 11);
for (int i = 0; i < 11; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), qreal(i*30));
}
listview->setSpacing(0);
// Confirm items positioned correctly
QTRY_VERIFY(findItems<QQuickItem>(contentItem, "wrapper").count() >= 16);
for (int i = 0; i < 16; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), i*20.0);
}
delete testObject;
}
template <typename T>
void tst_QQuickListView::sections(const QUrl &source)
{
QScopedPointer<QQuickView> window(createView());
T model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), QString::number(i/5));
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
window->setSource(source);
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// Confirm items positioned correctly
int itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i = 0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY(item);
QTRY_COMPARE(item->y(), qreal(i*20 + ((i+4)/5) * 20));
QQuickText *next = findItem<QQuickText>(item, "nextSection");
QCOMPARE(next->text().toInt(), (i+1)/5);
}
QVERIFY(!listview->property("sectionsInvalidOnCompletion").toBool());
QSignalSpy currentSectionChangedSpy(listview, SIGNAL(currentSectionChanged()));
// Remove section boundary
model.removeItem(5);
listview->forceLayout();
QTRY_COMPARE(listview->count(), model.count());
// New section header created
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", 5);
QTRY_VERIFY(item);
QTRY_COMPARE(item->height(), 40.0);
model.insertItem(3, "New Item", "0");
listview->forceLayout();
QTRY_COMPARE(listview->count(), model.count());
// Section header moved
item = findItem<QQuickItem>(contentItem, "wrapper", 5);
QTRY_VERIFY(item);
QTRY_COMPARE(item->height(), 20.0);
item = findItem<QQuickItem>(contentItem, "wrapper", 6);
QTRY_VERIFY(item);
QTRY_COMPARE(item->height(), 40.0);
// insert item which will become a section header
model.insertItem(6, "Replace header", "1");
listview->forceLayout();
QTRY_COMPARE(listview->count(), model.count());
item = findItem<QQuickItem>(contentItem, "wrapper", 6);
QTRY_VERIFY(item);
QTRY_COMPARE(item->height(), 40.0);
item = findItem<QQuickItem>(contentItem, "wrapper", 7);
QTRY_VERIFY(item);
QTRY_COMPARE(item->height(), 20.0);
QTRY_COMPARE(listview->currentSection(), QString("0"));
listview->setContentY(140);
QTRY_COMPARE(listview->currentSection(), QString("1"));
QTRY_COMPARE(currentSectionChangedSpy.count(), 1);
listview->setContentY(20);
QTRY_COMPARE(listview->currentSection(), QString("0"));
QTRY_COMPARE(currentSectionChangedSpy.count(), 2);
item = findItem<QQuickItem>(contentItem, "wrapper", 1);
QTRY_VERIFY(item);
QTRY_COMPARE(item->height(), 20.0);
// check that headers change when item changes
listview->setContentY(0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
model.modifyItem(0, "changed", "2");
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
item = findItem<QQuickItem>(contentItem, "wrapper", 1);
QTRY_VERIFY(item);
QTRY_COMPARE(item->height(), 40.0);
}
void tst_QQuickListView::sectionsDelegate()
{
QScopedPointer<QQuickView> window(createView());
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), QString::number(i/5));
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
window->setSource(testFileUrl("listview-sections_delegate.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// Confirm items positioned correctly
int itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i = 0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), qreal(i*20 + ((i+5)/5) * 20));
QQuickText *next = findItem<QQuickText>(item, "nextSection");
QCOMPARE(next->text().toInt(), (i+1)/5);
}
for (int i = 0; i < 3; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "sect_" + QString::number(i));
QVERIFY(item);
QTRY_COMPARE(item->y(), qreal(i*20*6));
}
// change section
model.modifyItem(0, "One", "aaa");
model.modifyItem(1, "Two", "aaa");
model.modifyItem(2, "Three", "aaa");
model.modifyItem(3, "Four", "aaa");
model.modifyItem(4, "Five", "aaa");
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
for (int i = 0; i < 3; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem,
"sect_" + (i == 0 ? QString("aaa") : QString::number(i)));
QVERIFY(item);
QTRY_COMPARE(item->y(), qreal(i*20*6));
}
// remove section boundary
model.removeItem(5);
listview->forceLayout();
QTRY_COMPARE(listview->count(), model.count());
for (int i = 0; i < 3; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem,
"sect_" + (i == 0 ? QString("aaa") : QString::number(i)));
QVERIFY(item);
}
// QTBUG-17606
QList<QQuickItem*> items = findItems<QQuickItem>(contentItem, "sect_1");
QCOMPARE(items.count(), 1);
// QTBUG-17759
model.modifyItem(0, "One", "aaa");
model.modifyItem(1, "One", "aaa");
model.modifyItem(2, "One", "aaa");
model.modifyItem(3, "Four", "aaa");
model.modifyItem(4, "Four", "aaa");
model.modifyItem(5, "Four", "aaa");
model.modifyItem(6, "Five", "aaa");
model.modifyItem(7, "Five", "aaa");
model.modifyItem(8, "Five", "aaa");
model.modifyItem(9, "Two", "aaa");
model.modifyItem(10, "Two", "aaa");
model.modifyItem(11, "Two", "aaa");
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QTRY_COMPARE(findItems<QQuickItem>(contentItem, "sect_aaa").count(), 1);
window->rootObject()->setProperty("sectionProperty", "name");
// ensure view has settled.
QTRY_COMPARE(findItems<QQuickItem>(contentItem, "sect_Four").count(), 1);
for (int i = 0; i < 4; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem,
"sect_" + model.name(i*3));
QVERIFY(item);
QTRY_COMPARE(item->y(), qreal(i*20*4));
}
}
void tst_QQuickListView::sectionsDragOutsideBounds_data()
{
QTest::addColumn<int>("distance");
QTest::addColumn<int>("cacheBuffer");
QTest::newRow("500, no cache buffer") << 500 << 0;
QTest::newRow("1000, no cache buffer") << 1000 << 0;
QTest::newRow("500, cache buffer") << 500 << 320;
QTest::newRow("1000, cache buffer") << 1000 << 320;
}
void tst_QQuickListView::sectionsDragOutsideBounds()
{
QFETCH(int, distance);
QFETCH(int, cacheBuffer);
QQuickView *window = getView();
QQuickViewTestUtil::moveMouseAway(window);
QaimModel model;
for (int i = 0; i < 10; i++)
model.addItem("Item" + QString::number(i), QString::number(i/5));
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
window->setSource(testFileUrl("listview-sections_delegate.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
listview->setCacheBuffer(cacheBuffer);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// QTBUG-17769
// Drag view up beyond bounds
QTest::mousePress(window, Qt::LeftButton, 0, QPoint(20,20));
QTest::mouseMove(window, QPoint(20,0));
QTest::mouseMove(window, QPoint(20,-50));
QTest::mouseMove(window, QPoint(20,-distance));
QTest::mouseRelease(window, Qt::LeftButton, 0, QPoint(20,-distance));
// view should settle back at 0
QTRY_COMPARE(listview->contentY(), 0.0);
QTest::mousePress(window, Qt::LeftButton, 0, QPoint(20,0));
QTest::mouseMove(window, QPoint(20,20));
QTest::mouseMove(window, QPoint(20,70));
QTest::mouseMove(window, QPoint(20,distance));
QTest::mouseRelease(window, Qt::LeftButton, 0, QPoint(20,distance));
// view should settle back at 0
QTRY_COMPARE(listview->contentY(), 0.0);
releaseView(window);
}
void tst_QQuickListView::sectionsDelegate_headerVisibility()
{
QSKIP("QTBUG-24395");
QScopedPointer<QQuickView> window(createView());
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), QString::number(i/5));
window->rootContext()->setContextProperty("testModel", &model);
window->setSource(testFileUrl("listview-sections_delegate.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
window->requestActivate();
QTest::qWaitForWindowActive(window.data());
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// ensure section header is maintained in view
listview->setCurrentIndex(20);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QTRY_VERIFY(qFuzzyCompare(listview->contentY(), 200.0));
QTRY_VERIFY(!listview->isMoving());
listview->setCurrentIndex(0);
QTRY_VERIFY(qFuzzyIsNull(listview->contentY()));
}
void tst_QQuickListView::sectionsPositioning()
{
QScopedPointer<QQuickView> window(createView());
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), QString::number(i/5));
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
window->setSource(testFileUrl("listview-sections_delegate.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
window->rootObject()->setProperty("sectionPositioning", QVariant(int(QQuickViewSection::InlineLabels | QQuickViewSection::CurrentLabelAtStart | QQuickViewSection::NextLabelAtEnd)));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
for (int i = 0; i < 3; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "sect_" + QString::number(i));
QVERIFY(item);
QTRY_COMPARE(item->y(), qreal(i*20*6));
}
QQuickItem *topItem = findVisibleChild(contentItem, "sect_0"); // section header
QVERIFY(topItem);
QCOMPARE(topItem->y(), 0.);
QQuickItem *bottomItem = findVisibleChild(contentItem, "sect_3"); // section footer
QVERIFY(bottomItem);
QCOMPARE(bottomItem->y(), 300.);
// move down a little and check that section header is at top
listview->setContentY(10);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QCOMPARE(topItem->y(), 0.);
// push the top header up
listview->setContentY(110);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
topItem = findVisibleChild(contentItem, "sect_0"); // section header
QVERIFY(topItem);
QCOMPARE(topItem->y(), 100.);
QQuickItem *item = findVisibleChild(contentItem, "sect_1");
QVERIFY(item);
QCOMPARE(item->y(), 120.);
bottomItem = findVisibleChild(contentItem, "sect_4"); // section footer
QVERIFY(bottomItem);
QCOMPARE(bottomItem->y(), 410.);
// Move past section 0
listview->setContentY(120);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
topItem = findVisibleChild(contentItem, "sect_0"); // section header
QVERIFY(!topItem);
// Push section footer down
listview->setContentY(70);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
bottomItem = findVisibleChild(contentItem, "sect_4"); // section footer
QVERIFY(bottomItem);
QCOMPARE(bottomItem->y(), 380.);
// Change current section, and verify case insensitive comparison
listview->setContentY(10);
model.modifyItem(0, "One", "aaa");
model.modifyItem(1, "Two", "AAA");
model.modifyItem(2, "Three", "aAa");
model.modifyItem(3, "Four", "aaA");
model.modifyItem(4, "Five", "Aaa");
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QTRY_COMPARE(listview->currentSection(), QString("aaa"));
for (int i = 0; i < 3; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem,
"sect_" + (i == 0 ? QString("aaa") : QString::number(i)));
QVERIFY(item);
QTRY_COMPARE(item->y(), qreal(i*20*6));
}
QTRY_VERIFY((topItem = findVisibleChild(contentItem, "sect_aaa"))); // section header
QCOMPARE(topItem->y(), 10.);
// remove section boundary
listview->setContentY(120);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
model.removeItem(5);
listview->forceLayout();
QTRY_COMPARE(listview->count(), model.count());
for (int i = 1; i < 3; ++i) {
QQuickItem *item = findVisibleChild(contentItem,
"sect_" + QString::number(i));
QVERIFY(item);
QTRY_COMPARE(item->y(), qreal(i*20*6));
}
topItem = findVisibleChild(contentItem, "sect_1");
QVERIFY(topItem);
QTRY_COMPARE(topItem->y(), 120.);
// Change the next section
listview->setContentY(0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
bottomItem = findVisibleChild(contentItem, "sect_3"); // section footer
QVERIFY(bottomItem);
QTRY_COMPARE(bottomItem->y(), 300.);
model.modifyItem(14, "New", "new");
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QTRY_VERIFY(bottomItem = findVisibleChild(contentItem, "sect_new")); // section footer
QTRY_COMPARE(bottomItem->y(), 300.);
// delegate size increase should push section footer down
listview->setContentY(70);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QTRY_VERIFY(bottomItem = findVisibleChild(contentItem, "sect_3")); // section footer
QTRY_COMPARE(bottomItem->y(), 370.);
QQuickItem *inlineSection = findVisibleChild(contentItem, "sect_new");
item = findItem<QQuickItem>(contentItem, "wrapper", 13);
QVERIFY(item);
item->setHeight(40.);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QTRY_COMPARE(bottomItem->y(), 380.);
QCOMPARE(inlineSection->y(), 360.);
item->setHeight(20.);
// Turn sticky footer off
listview->setContentY(20);
window->rootObject()->setProperty("sectionPositioning", QVariant(int(QQuickViewSection::InlineLabels | QQuickViewSection::CurrentLabelAtStart)));
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QTRY_VERIFY(item = findVisibleChild(contentItem, "sect_new")); // inline label restored
QCOMPARE(item->y(), 340.);
// Turn sticky header off
listview->setContentY(30);
window->rootObject()->setProperty("sectionPositioning", QVariant(int(QQuickViewSection::InlineLabels)));
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QTRY_VERIFY(item = findVisibleChild(contentItem, "sect_aaa")); // inline label restored
QCOMPARE(item->y(), 0.);
// if an empty model is set the header/footer should be cleaned up
window->rootObject()->setProperty("sectionPositioning", QVariant(int(QQuickViewSection::InlineLabels | QQuickViewSection::CurrentLabelAtStart | QQuickViewSection::NextLabelAtEnd)));
QTRY_VERIFY(findVisibleChild(contentItem, "sect_aaa")); // section header
QTRY_VERIFY(findVisibleChild(contentItem, "sect_new")); // section footer
QaimModel model1;
ctxt->setContextProperty("testModel", &model1);
QTRY_VERIFY(!findVisibleChild(contentItem, "sect_aaa")); // section header
QTRY_VERIFY(!findVisibleChild(contentItem, "sect_new")); // section footer
// clear model - header/footer should be cleaned up
ctxt->setContextProperty("testModel", &model);
QTRY_VERIFY(findVisibleChild(contentItem, "sect_aaa")); // section header
QTRY_VERIFY(findVisibleChild(contentItem, "sect_new")); // section footer
model.clear();
QTRY_VERIFY(!findVisibleChild(contentItem, "sect_aaa")); // section header
QTRY_VERIFY(!findVisibleChild(contentItem, "sect_new")); // section footer
}
void tst_QQuickListView::sectionPropertyChange()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("sectionpropertychange.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// Confirm items positioned correctly
for (int i = 0; i < 2; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), qreal(25. + i*75.));
}
QMetaObject::invokeMethod(window->rootObject(), "switchGroups");
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// Confirm items positioned correctly
for (int i = 0; i < 2; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), qreal(25. + i*75.));
}
QMetaObject::invokeMethod(window->rootObject(), "switchGroups");
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// Confirm items positioned correctly
for (int i = 0; i < 2; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), qreal(25. + i*75.));
}
QMetaObject::invokeMethod(window->rootObject(), "switchGrouped");
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// Confirm items positioned correctly
for (int i = 0; i < 2; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), qreal(25. + i*50.));
}
QMetaObject::invokeMethod(window->rootObject(), "switchGrouped");
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// Confirm items positioned correctly
for (int i = 0; i < 2; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), qreal(25. + i*75.));
}
}
void tst_QQuickListView::sectionDelegateChange()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("sectiondelegatechange.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = qobject_cast<QQuickListView *>(window->rootObject());
QVERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QVERIFY(contentItem != 0);
QQUICK_VERIFY_POLISH(listview);
QVERIFY(findItems<QQuickItem>(contentItem, "section1").count() > 0);
QCOMPARE(findItems<QQuickItem>(contentItem, "section2").count(), 0);
for (int i = 0; i < 3; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "item", i);
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), qreal(25. + i*50.));
}
QMetaObject::invokeMethod(window->rootObject(), "switchDelegates");
QQUICK_VERIFY_POLISH(listview);
QCOMPARE(findItems<QQuickItem>(contentItem, "section1").count(), 0);
QVERIFY(findItems<QQuickItem>(contentItem, "section2").count() > 0);
for (int i = 0; i < 3; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "item", i);
QVERIFY(item);
QTRY_COMPARE(item->y(), qreal(50. + i*75.));
}
}
// QTBUG-43873
void tst_QQuickListView::sectionsItemInsertion()
{
QScopedPointer<QQuickView> window(createView());
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), QString::number(i/5));
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
window->setSource(testFileUrl("listview-sections_delegate.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
for (int i = 0; i < 3; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "sect_" + QString::number(i));
QVERIFY(item);
QTRY_COMPARE(item->y(), qreal(i*20*6));
}
QQuickItem *topItem = findVisibleChild(contentItem, "sect_0"); // section header
QVERIFY(topItem);
QCOMPARE(topItem->y(), 0.);
// Insert a full screen of items at the beginning.
for (int i = 0; i < 10; i++)
model.insertItem(i, "Item" + QString::number(i), QLatin1String("A"));
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
int itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
QVERIFY(itemCount > 10);
// Verify that the new items are postioned correctly, and have the correct attached section properties
for (int i = 0; i < 10 && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY(item);
QTRY_COMPARE(item->y(), 20+i*20.0);
QCOMPARE(item->property("section").toString(), QLatin1String("A"));
QCOMPARE(item->property("nextSection").toString(), i < 9 ? QLatin1String("A") : QLatin1String("0"));
QCOMPARE(item->property("prevSection").toString(), i > 0 ? QLatin1String("A") : QLatin1String(""));
}
// Verify that the exiting items are postioned correctly, and have the correct attached section properties
for (int i = 10; i < 15 && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY(item);
QTRY_COMPARE(item->y(), 40+i*20.0);
QCOMPARE(item->property("section").toString(), QLatin1String("0"));
QCOMPARE(item->property("nextSection").toString(), i < 14 ? QLatin1String("0") : QLatin1String("1"));
QCOMPARE(item->property("prevSection").toString(), i > 10 ? QLatin1String("0") : QLatin1String("A"));
}
}
void tst_QQuickListView::currentIndex_delayedItemCreation()
{
QFETCH(bool, setCurrentToZero);
QQuickView *window = getView();
// test currentIndexChanged() is emitted even if currentIndex = 0 on start up
// (since the currentItem will have changed and that shares the same index)
window->rootContext()->setContextProperty("setCurrentToZero", setCurrentToZero);
window->setSource(testFileUrl("fillModelOnComponentCompleted.qml"));
qApp->processEvents();
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QSignalSpy spy(listview, SIGNAL(currentItemChanged()));
//QCOMPARE(listview->currentIndex(), 0);
listview->forceLayout();
QTRY_COMPARE(spy.count(), 1);
releaseView(window);
}
void tst_QQuickListView::currentIndex_delayedItemCreation_data()
{
QTest::addColumn<bool>("setCurrentToZero");
QTest::newRow("set to 0") << true;
QTest::newRow("don't set to 0") << false;
}
void tst_QQuickListView::currentIndex()
{
QaimModel initModel;
for (int i = 0; i < 30; i++)
initModel.addItem("Item" + QString::number(i), QString::number(i));
QQuickView *window = new QQuickView(0);
window->setGeometry(0,0,240,320);
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &initModel);
ctxt->setContextProperty("testWrap", QVariant(false));
QString filename(testFile("listview-initCurrent.qml"));
window->setSource(QUrl::fromLocalFile(filename));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// currentIndex is initialized to 20
// currentItem should be in view
QCOMPARE(listview->currentIndex(), 20);
QCOMPARE(listview->contentY(), 100.0);
QCOMPARE(listview->currentItem(), findItem<QQuickItem>(contentItem, "wrapper", 20));
QCOMPARE(listview->highlightItem()->y(), listview->currentItem()->y());
// changing model should reset currentIndex to 0
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), QString::number(i));
ctxt->setContextProperty("testModel", &model);
listview->forceLayout();
QCOMPARE(listview->currentIndex(), 0);
QCOMPARE(listview->currentItem(), findItem<QQuickItem>(contentItem, "wrapper", 0));
// confirm that the velocity is updated
listview->setCurrentIndex(20);
QTRY_VERIFY(listview->verticalVelocity() != 0.0);
listview->setCurrentIndex(0);
QTRY_COMPARE(listview->verticalVelocity(), 0.0);
// footer should become visible if it is out of view, and then current index is set to count-1
window->rootObject()->setProperty("showFooter", true);
QTRY_VERIFY(listview->footerItem());
listview->setCurrentIndex(model.count()-2);
QTRY_VERIFY(listview->footerItem()->y() > listview->contentY() + listview->height());
listview->setCurrentIndex(model.count()-1);
QTRY_COMPARE(listview->contentY() + listview->height(), (20.0 * model.count()) + listview->footerItem()->height());
window->rootObject()->setProperty("showFooter", false);
// header should become visible if it is out of view, and then current index is set to 0
window->rootObject()->setProperty("showHeader", true);
QTRY_VERIFY(listview->headerItem());
listview->setCurrentIndex(1);
QTRY_VERIFY(listview->headerItem()->y() + listview->headerItem()->height() < listview->contentY());
listview->setCurrentIndex(0);
QTRY_COMPARE(listview->contentY(), -listview->headerItem()->height());
window->rootObject()->setProperty("showHeader", false);
// turn off auto highlight
listview->setHighlightFollowsCurrentItem(false);
QVERIFY(!listview->highlightFollowsCurrentItem());
QVERIFY(listview->highlightItem());
qreal hlPos = listview->highlightItem()->y();
listview->setCurrentIndex(4);
QTRY_COMPARE(listview->highlightItem()->y(), hlPos);
// insert item before currentIndex
window->rootObject()->setProperty("currentItemChangedCount", QVariant(0));
listview->setCurrentIndex(28);
QTRY_COMPARE(window->rootObject()->property("currentItemChangedCount").toInt(), 1);
model.insertItem(0, "Foo", "1111");
QTRY_COMPARE(window->rootObject()->property("current").toInt(), 29);
QCOMPARE(window->rootObject()->property("currentItemChangedCount").toInt(), 1);
// check removing highlight by setting currentIndex to -1;
listview->setCurrentIndex(-1);
QCOMPARE(listview->currentIndex(), -1);
QVERIFY(!listview->highlightItem());
QVERIFY(!listview->currentItem());
// moving currentItem out of view should make it invisible
listview->setCurrentIndex(0);
QTRY_VERIFY(delegateVisible(listview->currentItem()));
listview->setContentY(200);
QTRY_VERIFY(!delegateVisible(listview->currentItem()));
// empty model should reset currentIndex to -1
QaimModel emptyModel;
ctxt->setContextProperty("testModel", &emptyModel);
QCOMPARE(listview->currentIndex(), -1);
delete window;
}
void tst_QQuickListView::noCurrentIndex()
{
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), QString::number(i));
QQuickView *window = new QQuickView(0);
window->setGeometry(0,0,240,320);
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
QString filename(testFile("listview-noCurrent.qml"));
window->setSource(QUrl::fromLocalFile(filename));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// current index should be -1 at startup
// and we should not have a currentItem or highlightItem
QCOMPARE(listview->currentIndex(), -1);
QCOMPARE(listview->contentY(), 0.0);
QVERIFY(!listview->highlightItem());
QVERIFY(!listview->currentItem());
listview->setCurrentIndex(2);
QCOMPARE(listview->currentIndex(), 2);
QVERIFY(listview->highlightItem());
QVERIFY(listview->currentItem());
delete window;
}
void tst_QQuickListView::keyNavigation()
{
QFETCH(QQuickListView::Orientation, orientation);
QFETCH(Qt::LayoutDirection, layoutDirection);
QFETCH(QQuickItemView::VerticalLayoutDirection, verticalLayoutDirection);
QFETCH(Qt::Key, forwardsKey);
QFETCH(Qt::Key, backwardsKey);
QFETCH(QPointF, contentPosAtFirstItem);
QFETCH(QPointF, contentPosAtLastItem);
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), "");
QQuickView *window = getView();
TestObject *testObject = new TestObject;
window->rootContext()->setContextProperty("testModel", &model);
window->rootContext()->setContextProperty("testObject", testObject);
window->setSource(testFileUrl("listviewtest.qml"));
window->show();
QTest::qWaitForWindowActive(window);
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
listview->setOrientation(orientation);
listview->setLayoutDirection(layoutDirection);
listview->setVerticalLayoutDirection(verticalLayoutDirection);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
window->requestActivate();
QTest::qWaitForWindowActive(window);
QTRY_COMPARE(qGuiApp->focusWindow(), window);
QTest::keyClick(window, forwardsKey);
QCOMPARE(listview->currentIndex(), 1);
QTest::keyClick(window, backwardsKey);
QCOMPARE(listview->currentIndex(), 0);
// hold down a key to go forwards
for (int i=0; i<model.count()-1; i++) {
QTest::simulateEvent(window, true, forwardsKey, Qt::NoModifier, "", true);
QCOMPARE(listview->currentIndex(), i+1);
}
QTest::keyRelease(window, forwardsKey);
listview->forceLayout();
QTRY_COMPARE(listview->currentIndex(), model.count()-1);
QTRY_COMPARE(listview->contentX(), contentPosAtLastItem.x());
QTRY_COMPARE(listview->contentY(), contentPosAtLastItem.y());
// hold down a key to go backwards
for (int i=model.count()-1; i > 0; i--) {
QTest::simulateEvent(window, true, backwardsKey, Qt::NoModifier, "", true);
QTRY_COMPARE(listview->currentIndex(), i-1);
}
QTest::keyRelease(window, backwardsKey);
listview->forceLayout();
QTRY_COMPARE(listview->currentIndex(), 0);
QTRY_COMPARE(listview->contentX(), contentPosAtFirstItem.x());
QTRY_COMPARE(listview->contentY(), contentPosAtFirstItem.y());
// no wrap
QVERIFY(!listview->isWrapEnabled());
listview->incrementCurrentIndex();
QCOMPARE(listview->currentIndex(), 1);
listview->decrementCurrentIndex();
QCOMPARE(listview->currentIndex(), 0);
listview->decrementCurrentIndex();
QCOMPARE(listview->currentIndex(), 0);
// with wrap
listview->setWrapEnabled(true);
QVERIFY(listview->isWrapEnabled());
listview->decrementCurrentIndex();
QCOMPARE(listview->currentIndex(), model.count()-1);
QTRY_COMPARE(listview->contentX(), contentPosAtLastItem.x());
QTRY_COMPARE(listview->contentY(), contentPosAtLastItem.y());
listview->incrementCurrentIndex();
QCOMPARE(listview->currentIndex(), 0);
QTRY_COMPARE(listview->contentX(), contentPosAtFirstItem.x());
QTRY_COMPARE(listview->contentY(), contentPosAtFirstItem.y());
releaseView(window);
delete testObject;
}
void tst_QQuickListView::keyNavigation_data()
{
QTest::addColumn<QQuickListView::Orientation>("orientation");
QTest::addColumn<Qt::LayoutDirection>("layoutDirection");
QTest::addColumn<QQuickItemView::VerticalLayoutDirection>("verticalLayoutDirection");
QTest::addColumn<Qt::Key>("forwardsKey");
QTest::addColumn<Qt::Key>("backwardsKey");
QTest::addColumn<QPointF>("contentPosAtFirstItem");
QTest::addColumn<QPointF>("contentPosAtLastItem");
QTest::newRow("Vertical, TopToBottom")
<< QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::TopToBottom
<< Qt::Key_Down << Qt::Key_Up
<< QPointF(0, 0)
<< QPointF(0, 30*20 - 320);
QTest::newRow("Vertical, BottomToTop")
<< QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::BottomToTop
<< Qt::Key_Up << Qt::Key_Down
<< QPointF(0, -320)
<< QPointF(0, -(30 * 20));
QTest::newRow("Horizontal, LeftToRight")
<< QQuickListView::Horizontal << Qt::LeftToRight << QQuickItemView::TopToBottom
<< Qt::Key_Right << Qt::Key_Left
<< QPointF(0, 0)
<< QPointF(30*240 - 240, 0);
QTest::newRow("Horizontal, RightToLeft")
<< QQuickListView::Horizontal << Qt::RightToLeft << QQuickItemView::TopToBottom
<< Qt::Key_Left << Qt::Key_Right
<< QPointF(-240, 0)
<< QPointF(-(30 * 240), 0);
}
void tst_QQuickListView::itemList()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("itemlist.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "view");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QQmlObjectModel *model = window->rootObject()->findChild<QQmlObjectModel*>("itemModel");
QTRY_VERIFY(model != 0);
QTRY_COMPARE(model->count(), 3);
QTRY_COMPARE(listview->currentIndex(), 0);
QQuickItem *item = findItem<QQuickItem>(contentItem, "item1");
QTRY_VERIFY(item);
QTRY_COMPARE(item->x(), 0.0);
QCOMPARE(item->height(), listview->height());
QQuickText *text = findItem<QQuickText>(contentItem, "text1");
QTRY_VERIFY(text);
QTRY_COMPARE(text->text(), QLatin1String("index: 0"));
listview->setCurrentIndex(2);
item = findItem<QQuickItem>(contentItem, "item3");
QTRY_VERIFY(item);
QTRY_COMPARE(item->x(), 480.0);
text = findItem<QQuickText>(contentItem, "text3");
QTRY_VERIFY(text);
QTRY_COMPARE(text->text(), QLatin1String("index: 2"));
}
void tst_QQuickListView::itemListFlicker()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("itemlist-flicker.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "view");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QQmlObjectModel *model = window->rootObject()->findChild<QQmlObjectModel*>("itemModel");
QTRY_VERIFY(model != 0);
QTRY_COMPARE(model->count(), 3);
QTRY_COMPARE(listview->currentIndex(), 0);
QQuickItem *item = findItem<QQuickItem>(contentItem, "item1");
QVERIFY(item);
QVERIFY(delegateVisible(item));
item = findItem<QQuickItem>(contentItem, "item2");
QVERIFY(item);
QVERIFY(delegateVisible(item));
item = findItem<QQuickItem>(contentItem, "item3");
QVERIFY(item);
QVERIFY(delegateVisible(item));
listview->setCurrentIndex(1);
item = findItem<QQuickItem>(contentItem, "item1");
QVERIFY(item);
QVERIFY(delegateVisible(item));
item = findItem<QQuickItem>(contentItem, "item2");
QVERIFY(item);
QVERIFY(delegateVisible(item));
item = findItem<QQuickItem>(contentItem, "item3");
QVERIFY(item);
QVERIFY(delegateVisible(item));
listview->setCurrentIndex(2);
item = findItem<QQuickItem>(contentItem, "item1");
QVERIFY(item);
QVERIFY(delegateVisible(item));
item = findItem<QQuickItem>(contentItem, "item2");
QVERIFY(item);
QVERIFY(delegateVisible(item));
item = findItem<QQuickItem>(contentItem, "item3");
QVERIFY(item);
QVERIFY(delegateVisible(item));
}
void tst_QQuickListView::cacheBuffer()
{
QScopedPointer<QQuickView> window(createView());
QaimModel model;
for (int i = 0; i < 90; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(testFileUrl("listviewtest.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_VERIFY(listview->delegate() != 0);
QTRY_VERIFY(listview->model() != 0);
QTRY_VERIFY(listview->highlight() != 0);
// Confirm items positioned correctly
int itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i = 0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), qreal(i*20));
}
QQmlIncubationController controller;
window->engine()->setIncubationController(&controller);
testObject->setCacheBuffer(200);
QTRY_COMPARE(listview->cacheBuffer(), 200);
// items will be created one at a time
for (int i = itemCount; i < qMin(itemCount+10,model.count()); ++i) {
QVERIFY(findItem<QQuickItem>(listview, "wrapper", i) == 0);
QQuickItem *item = 0;
while (!item) {
bool b = false;
controller.incubateWhile(&b);
item = findItem<QQuickItem>(listview, "wrapper", i);
}
}
{
bool b = true;
controller.incubateWhile(&b);
}
int newItemCount = 0;
newItemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
// Confirm items positioned correctly
for (int i = 0; i < model.count() && i < newItemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), qreal(i*20));
}
// move view and confirm items in view are visible immediately and outside are created async
listview->setContentY(300);
for (int i = 15; i < 32; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QVERIFY(item);
QCOMPARE(item->y(), qreal(i*20));
}
QVERIFY(findItem<QQuickItem>(listview, "wrapper", 32) == 0);
// ensure buffered items are created
for (int i = 32; i < qMin(41,model.count()); ++i) {
QQuickItem *item = 0;
while (!item) {
qGuiApp->processEvents(); // allow refill to happen
bool b = false;
controller.incubateWhile(&b);
item = findItem<QQuickItem>(listview, "wrapper", i);
}
}
{
bool b = true;
controller.incubateWhile(&b);
}
// negative cache buffer is ignored
listview->setCacheBuffer(-1);
QCOMPARE(listview->cacheBuffer(), 200);
delete testObject;
}
void tst_QQuickListView::positionViewAtBeginningEnd()
{
QScopedPointer<QQuickView> window(createView());
QaimModel model;
for (int i = 0; i < 40; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->show();
window->setSource(testFileUrl("listviewtest.qml"));
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
listview->setContentY(100);
// positionAtBeginnging
listview->positionViewAtBeginning();
QTRY_COMPARE(listview->contentY(), 0.);
listview->setContentY(80);
window->rootObject()->setProperty("showHeader", true);
listview->positionViewAtBeginning();
QTRY_COMPARE(listview->contentY(), -30.);
// positionAtEnd
listview->positionViewAtEnd();
QTRY_COMPARE(listview->contentY(), 480.); // 40*20 - 320
listview->setContentY(80);
window->rootObject()->setProperty("showFooter", true);
listview->positionViewAtEnd();
QTRY_COMPARE(listview->contentY(), 510.);
// set current item to outside visible view, position at beginning
// and ensure highlight moves to current item
listview->setCurrentIndex(1);
listview->positionViewAtBeginning();
QTRY_COMPARE(listview->contentY(), -30.);
QVERIFY(listview->highlightItem());
QCOMPARE(listview->highlightItem()->y(), 20.);
delete testObject;
}
void tst_QQuickListView::positionViewAtIndex()
{
QFETCH(bool, enforceRange);
QFETCH(qreal, initContentY);
QFETCH(int, index);
QFETCH(QQuickListView::PositionMode, mode);
QFETCH(qreal, contentY);
QQuickView *window = getView();
QaimModel model;
for (int i = 0; i < 40; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->show();
window->setSource(testFileUrl("listviewtest.qml"));
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
window->rootObject()->setProperty("enforceRange", enforceRange);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
listview->setContentY(initContentY);
listview->positionViewAtIndex(index, mode);
QTRY_COMPARE(listview->contentY(), contentY);
// Confirm items positioned correctly
int itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i = index; i < model.count() && i < itemCount-index-1; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), i*20.);
}
releaseView(window);
}
void tst_QQuickListView::positionViewAtIndex_data()
{
QTest::addColumn<bool>("enforceRange");
QTest::addColumn<qreal>("initContentY");
QTest::addColumn<int>("index");
QTest::addColumn<QQuickListView::PositionMode>("mode");
QTest::addColumn<qreal>("contentY");
QTest::newRow("no range, 3 at Beginning") << false << 0. << 3 << QQuickListView::Beginning << 60.;
QTest::newRow("no range, 3 at End") << false << 0. << 3 << QQuickListView::End << 0.;
QTest::newRow("no range, 22 at Beginning") << false << 0. << 22 << QQuickListView::Beginning << 440.;
// Position on an item that would leave empty space if positioned at the top
QTest::newRow("no range, 28 at Beginning") << false << 0. << 28 << QQuickListView::Beginning << 480.;
// Position at End using last index
QTest::newRow("no range, last at End") << false << 0. << 39 << QQuickListView::End << 480.;
// Position at End
QTest::newRow("no range, 20 at End") << false << 0. << 20 << QQuickListView::End << 100.;
// Position in Center
QTest::newRow("no range, 15 at Center") << false << 0. << 15 << QQuickListView::Center << 150.;
// Ensure at least partially visible
QTest::newRow("no range, 15 visible => Visible") << false << 150. << 15 << QQuickListView::Visible << 150.;
QTest::newRow("no range, 15 partially visible => Visible") << false << 302. << 15 << QQuickListView::Visible << 302.;
QTest::newRow("no range, 15 before visible => Visible") << false << 320. << 15 << QQuickListView::Visible << 300.;
QTest::newRow("no range, 20 visible => Visible") << false << 85. << 20 << QQuickListView::Visible << 85.;
QTest::newRow("no range, 20 before visible => Visible") << false << 75. << 20 << QQuickListView::Visible << 100.;
QTest::newRow("no range, 20 after visible => Visible") << false << 480. << 20 << QQuickListView::Visible << 400.;
// Ensure completely visible
QTest::newRow("no range, 20 visible => Contain") << false << 120. << 20 << QQuickListView::Contain << 120.;
QTest::newRow("no range, 15 partially visible => Contain") << false << 302. << 15 << QQuickListView::Contain << 300.;
QTest::newRow("no range, 20 partially visible => Contain") << false << 85. << 20 << QQuickListView::Contain << 100.;
QTest::newRow("strict range, 3 at End") << true << 0. << 3 << QQuickListView::End << -120.;
QTest::newRow("strict range, 38 at Beginning") << true << 0. << 38 << QQuickListView::Beginning << 660.;
QTest::newRow("strict range, 15 at Center") << true << 0. << 15 << QQuickListView::Center << 140.;
QTest::newRow("strict range, 3 at SnapPosition") << true << 0. << 3 << QQuickListView::SnapPosition << -60.;
QTest::newRow("strict range, 10 at SnapPosition") << true << 0. << 10 << QQuickListView::SnapPosition << 80.;
QTest::newRow("strict range, 38 at SnapPosition") << true << 0. << 38 << QQuickListView::SnapPosition << 640.;
}
void tst_QQuickListView::resetModel()
{
QScopedPointer<QQuickView> window(createView());
QStringList strings;
strings << "one" << "two" << "three";
QStringListModel model(strings);
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
window->setSource(testFileUrl("displaylist.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QTRY_COMPARE(listview->count(), model.rowCount());
for (int i = 0; i < model.rowCount(); ++i) {
QQuickText *display = findItem<QQuickText>(contentItem, "displayText", i);
QTRY_VERIFY(display != 0);
QTRY_COMPARE(display->text(), strings.at(i));
}
strings.clear();
strings << "four" << "five" << "six" << "seven";
model.setStringList(strings);
listview->forceLayout();
QTRY_COMPARE(listview->count(), model.rowCount());
for (int i = 0; i < model.rowCount(); ++i) {
QQuickText *display = findItem<QQuickText>(contentItem, "displayText", i);
QTRY_VERIFY(display != 0);
QTRY_COMPARE(display->text(), strings.at(i));
}
}
void tst_QQuickListView::propertyChanges()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("propertychangestest.qml"));
QQuickListView *listView = window->rootObject()->findChild<QQuickListView*>("listView");
QTRY_VERIFY(listView);
QSignalSpy highlightFollowsCurrentItemSpy(listView, SIGNAL(highlightFollowsCurrentItemChanged()));
QSignalSpy preferredHighlightBeginSpy(listView, SIGNAL(preferredHighlightBeginChanged()));
QSignalSpy preferredHighlightEndSpy(listView, SIGNAL(preferredHighlightEndChanged()));
QSignalSpy highlightRangeModeSpy(listView, SIGNAL(highlightRangeModeChanged()));
QSignalSpy keyNavigationWrapsSpy(listView, SIGNAL(keyNavigationWrapsChanged()));
QSignalSpy cacheBufferSpy(listView, SIGNAL(cacheBufferChanged()));
QSignalSpy snapModeSpy(listView, SIGNAL(snapModeChanged()));
QTRY_COMPARE(listView->highlightFollowsCurrentItem(), true);
QTRY_COMPARE(listView->preferredHighlightBegin(), 0.0);
QTRY_COMPARE(listView->preferredHighlightEnd(), 0.0);
QTRY_COMPARE(listView->highlightRangeMode(), QQuickListView::ApplyRange);
QTRY_COMPARE(listView->isWrapEnabled(), true);
QTRY_COMPARE(listView->cacheBuffer(), 10);
QTRY_COMPARE(listView->snapMode(), QQuickListView::SnapToItem);
listView->setHighlightFollowsCurrentItem(false);
listView->setPreferredHighlightBegin(1.0);
listView->setPreferredHighlightEnd(1.0);
listView->setHighlightRangeMode(QQuickListView::StrictlyEnforceRange);
listView->setWrapEnabled(false);
listView->setCacheBuffer(3);
listView->setSnapMode(QQuickListView::SnapOneItem);
QTRY_COMPARE(listView->highlightFollowsCurrentItem(), false);
QTRY_COMPARE(listView->preferredHighlightBegin(), 1.0);
QTRY_COMPARE(listView->preferredHighlightEnd(), 1.0);
QTRY_COMPARE(listView->highlightRangeMode(), QQuickListView::StrictlyEnforceRange);
QTRY_COMPARE(listView->isWrapEnabled(), false);
QTRY_COMPARE(listView->cacheBuffer(), 3);
QTRY_COMPARE(listView->snapMode(), QQuickListView::SnapOneItem);
QTRY_COMPARE(highlightFollowsCurrentItemSpy.count(),1);
QTRY_COMPARE(preferredHighlightBeginSpy.count(),1);
QTRY_COMPARE(preferredHighlightEndSpy.count(),1);
QTRY_COMPARE(highlightRangeModeSpy.count(),1);
QTRY_COMPARE(keyNavigationWrapsSpy.count(),1);
QTRY_COMPARE(cacheBufferSpy.count(),1);
QTRY_COMPARE(snapModeSpy.count(),1);
listView->setHighlightFollowsCurrentItem(false);
listView->setPreferredHighlightBegin(1.0);
listView->setPreferredHighlightEnd(1.0);
listView->setHighlightRangeMode(QQuickListView::StrictlyEnforceRange);
listView->setWrapEnabled(false);
listView->setCacheBuffer(3);
listView->setSnapMode(QQuickListView::SnapOneItem);
QTRY_COMPARE(highlightFollowsCurrentItemSpy.count(),1);
QTRY_COMPARE(preferredHighlightBeginSpy.count(),1);
QTRY_COMPARE(preferredHighlightEndSpy.count(),1);
QTRY_COMPARE(highlightRangeModeSpy.count(),1);
QTRY_COMPARE(keyNavigationWrapsSpy.count(),1);
QTRY_COMPARE(cacheBufferSpy.count(),1);
QTRY_COMPARE(snapModeSpy.count(),1);
}
void tst_QQuickListView::componentChanges()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("propertychangestest.qml"));
QQuickListView *listView = window->rootObject()->findChild<QQuickListView*>("listView");
QTRY_VERIFY(listView);
QQmlComponent component(window->engine());
component.setData("import QtQuick 2.0; Rectangle { color: \"blue\"; }", QUrl::fromLocalFile(""));
QQmlComponent delegateComponent(window->engine());
delegateComponent.setData("import QtQuick 2.0; Text { text: '<b>Name:</b> ' + name }", QUrl::fromLocalFile(""));
QSignalSpy highlightSpy(listView, SIGNAL(highlightChanged()));
QSignalSpy delegateSpy(listView, SIGNAL(delegateChanged()));
QSignalSpy headerSpy(listView, SIGNAL(headerChanged()));
QSignalSpy footerSpy(listView, SIGNAL(footerChanged()));
listView->setHighlight(&component);
listView->setHeader(&component);
listView->setFooter(&component);
listView->setDelegate(&delegateComponent);
QTRY_COMPARE(listView->highlight(), &component);
QTRY_COMPARE(listView->header(), &component);
QTRY_COMPARE(listView->footer(), &component);
QTRY_COMPARE(listView->delegate(), &delegateComponent);
QTRY_COMPARE(highlightSpy.count(),1);
QTRY_COMPARE(delegateSpy.count(),1);
QTRY_COMPARE(headerSpy.count(),1);
QTRY_COMPARE(footerSpy.count(),1);
listView->setHighlight(&component);
listView->setHeader(&component);
listView->setFooter(&component);
listView->setDelegate(&delegateComponent);
QTRY_COMPARE(highlightSpy.count(),1);
QTRY_COMPARE(delegateSpy.count(),1);
QTRY_COMPARE(headerSpy.count(),1);
QTRY_COMPARE(footerSpy.count(),1);
}
void tst_QQuickListView::modelChanges()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("propertychangestest.qml"));
QQuickListView *listView = window->rootObject()->findChild<QQuickListView*>("listView");
QTRY_VERIFY(listView);
QQmlListModel *alternateModel = window->rootObject()->findChild<QQmlListModel*>("alternateModel");
QTRY_VERIFY(alternateModel);
QVariant modelVariant = QVariant::fromValue<QObject *>(alternateModel);
QSignalSpy modelSpy(listView, SIGNAL(modelChanged()));
listView->setModel(modelVariant);
QTRY_COMPARE(listView->model(), modelVariant);
QTRY_COMPARE(modelSpy.count(),1);
listView->setModel(modelVariant);
QTRY_COMPARE(modelSpy.count(),1);
listView->setModel(QVariant());
QTRY_COMPARE(modelSpy.count(),2);
}
void tst_QQuickListView::QTBUG_9791()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("strictlyenforcerange.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = qobject_cast<QQuickListView*>(window->rootObject());
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_VERIFY(listview->delegate() != 0);
QTRY_VERIFY(listview->model() != 0);
QMetaObject::invokeMethod(listview, "fillModel");
qApp->processEvents();
// Confirm items positioned correctly
int itemCount = findItems<QQuickItem>(contentItem, "wrapper", false).count();
QCOMPARE(itemCount, 3);
for (int i = 0; i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->x(), i*300.0);
}
// check that view is positioned correctly
QTRY_COMPARE(listview->contentX(), 590.0);
}
void tst_QQuickListView::manualHighlight()
{
QQuickView *window = new QQuickView(0);
window->setGeometry(0,0,240,320);
QString filename(testFile("manual-highlight.qml"));
window->setSource(QUrl::fromLocalFile(filename));
qApp->processEvents();
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(listview->currentIndex(), 0);
QTRY_COMPARE(listview->currentItem(), findItem<QQuickItem>(contentItem, "wrapper", 0));
QTRY_COMPARE(listview->highlightItem()->y() - 5, listview->currentItem()->y());
listview->setCurrentIndex(2);
QTRY_COMPARE(listview->currentIndex(), 2);
QTRY_COMPARE(listview->currentItem(), findItem<QQuickItem>(contentItem, "wrapper", 2));
QTRY_COMPARE(listview->highlightItem()->y() - 5, listview->currentItem()->y());
// QTBUG-15972
listview->positionViewAtIndex(3, QQuickListView::Contain);
QTRY_COMPARE(listview->currentIndex(), 2);
QTRY_COMPARE(listview->currentItem(), findItem<QQuickItem>(contentItem, "wrapper", 2));
QTRY_COMPARE(listview->highlightItem()->y() - 5, listview->currentItem()->y());
delete window;
}
void tst_QQuickListView::QTBUG_11105()
{
QScopedPointer<QQuickView> window(createView());
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(testFileUrl("listviewtest.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// Confirm items positioned correctly
int itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i = 0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), qreal(i*20));
}
listview->positionViewAtIndex(20, QQuickListView::Beginning);
QCOMPARE(listview->contentY(), 280.);
QaimModel model2;
for (int i = 0; i < 5; i++)
model2.addItem("Item" + QString::number(i), "");
ctxt->setContextProperty("testModel", &model2);
itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
QCOMPARE(itemCount, 5);
delete testObject;
}
void tst_QQuickListView::initialZValues()
{
QFETCH(QString, fileName);
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl(fileName));
qApp->processEvents();
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QVERIFY(listview->currentItem());
QTRY_COMPARE(listview->currentItem()->z(), listview->property("itemZ").toReal());
QVERIFY(listview->headerItem());
QTRY_COMPARE(listview->headerItem()->z(), listview->property("headerZ").toReal());
QVERIFY(listview->footerItem());
QTRY_COMPARE(listview->footerItem()->z(), listview->property("footerZ").toReal());
QVERIFY(listview->highlightItem());
QTRY_COMPARE(listview->highlightItem()->z(), listview->property("highlightZ").toReal());
QQuickText *sectionItem = 0;
QTRY_VERIFY(sectionItem = findItem<QQuickText>(contentItem, "section"));
QTRY_COMPARE(sectionItem->z(), listview->property("sectionZ").toReal());
}
void tst_QQuickListView::initialZValues_data()
{
QTest::addColumn<QString>("fileName");
QTest::newRow("defaults") << "defaultZValues.qml";
QTest::newRow("constants") << "constantZValues.qml";
QTest::newRow("bindings") << "boundZValues.qml";
}
void tst_QQuickListView::header()
{
QFETCH(QQuickListView::Orientation, orientation);
QFETCH(Qt::LayoutDirection, layoutDirection);
QFETCH(QQuickItemView::VerticalLayoutDirection, verticalLayoutDirection);
QFETCH(QPointF, initialHeaderPos);
QFETCH(QPointF, changedHeaderPos);
QFETCH(QPointF, initialContentPos);
QFETCH(QPointF, changedContentPos);
QFETCH(QPointF, firstDelegatePos);
QFETCH(QPointF, resizeContentPos);
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), "");
QQuickView *window = getView();
window->rootContext()->setContextProperty("testModel", &model);
window->rootContext()->setContextProperty("initialViewWidth", 240);
window->rootContext()->setContextProperty("initialViewHeight", 320);
window->setSource(testFileUrl("header.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
listview->setOrientation(orientation);
listview->setLayoutDirection(layoutDirection);
listview->setVerticalLayoutDirection(verticalLayoutDirection);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QQuickText *header = 0;
QTRY_VERIFY(header = findItem<QQuickText>(contentItem, "header"));
QCOMPARE(header, listview->headerItem());
QCOMPARE(header->width(), 100.);
QCOMPARE(header->height(), 30.);
QCOMPARE(header->position(), initialHeaderPos);
QCOMPARE(QPointF(listview->contentX(), listview->contentY()), initialContentPos);
if (orientation == QQuickListView::Vertical)
QCOMPARE(listview->contentHeight(), model.count() * 30. + header->height());
else
QCOMPARE(listview->contentWidth(), model.count() * 240. + header->width());
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", 0);
QVERIFY(item);
QCOMPARE(item->position(), firstDelegatePos);
model.clear();
listview->forceLayout();
QTRY_COMPARE(listview->count(), model.count());
QCOMPARE(header->position(), initialHeaderPos); // header should stay where it is
if (orientation == QQuickListView::Vertical)
QCOMPARE(listview->contentHeight(), header->height());
else
QCOMPARE(listview->contentWidth(), header->width());
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), "");
QSignalSpy headerItemSpy(listview, SIGNAL(headerItemChanged()));
QMetaObject::invokeMethod(window->rootObject(), "changeHeader");
QCOMPARE(headerItemSpy.count(), 1);
header = findItem<QQuickText>(contentItem, "header");
QVERIFY(!header);
header = findItem<QQuickText>(contentItem, "header2");
QVERIFY(header);
QCOMPARE(header, listview->headerItem());
QCOMPARE(header->position(), changedHeaderPos);
QCOMPARE(header->width(), 50.);
QCOMPARE(header->height(), 20.);
QTRY_COMPARE(QPointF(listview->contentX(), listview->contentY()), changedContentPos);
item = findItem<QQuickItem>(contentItem, "wrapper", 0);
QVERIFY(item);
QCOMPARE(item->position(), firstDelegatePos);
listview->positionViewAtBeginning();
header->setHeight(10);
header->setWidth(40);
QTRY_COMPARE(QPointF(listview->contentX(), listview->contentY()), resizeContentPos);
releaseView(window);
// QTBUG-21207 header should become visible if view resizes from initial empty size
window = getView();
window->rootContext()->setContextProperty("testModel", &model);
window->rootContext()->setContextProperty("initialViewWidth", 0.0);
window->rootContext()->setContextProperty("initialViewHeight", 0.0);
window->setSource(testFileUrl("header.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
listview->setOrientation(orientation);
listview->setLayoutDirection(layoutDirection);
listview->setVerticalLayoutDirection(verticalLayoutDirection);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
listview->setWidth(240);
listview->setHeight(320);
QTRY_COMPARE(listview->headerItem()->position(), initialHeaderPos);
QCOMPARE(QPointF(listview->contentX(), listview->contentY()), initialContentPos);
releaseView(window);
}
void tst_QQuickListView::header_data()
{
QTest::addColumn<QQuickListView::Orientation>("orientation");
QTest::addColumn<Qt::LayoutDirection>("layoutDirection");
QTest::addColumn<QQuickItemView::VerticalLayoutDirection>("verticalLayoutDirection");
QTest::addColumn<QPointF>("initialHeaderPos");
QTest::addColumn<QPointF>("changedHeaderPos");
QTest::addColumn<QPointF>("initialContentPos");
QTest::addColumn<QPointF>("changedContentPos");
QTest::addColumn<QPointF>("firstDelegatePos");
QTest::addColumn<QPointF>("resizeContentPos");
// header1 = 100 x 30
// header2 = 50 x 20
// delegates = 240 x 30
// view width = 240
// header above items, top left
QTest::newRow("vertical, left to right") << QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::TopToBottom
<< QPointF(0, -30)
<< QPointF(0, -20)
<< QPointF(0, -30)
<< QPointF(0, -20)
<< QPointF(0, 0)
<< QPointF(0, -10);
// header above items, top right
QTest::newRow("vertical, layout right to left") << QQuickListView::Vertical << Qt::RightToLeft << QQuickItemView::TopToBottom
<< QPointF(0, -30)
<< QPointF(0, -20)
<< QPointF(0, -30)
<< QPointF(0, -20)
<< QPointF(0, 0)
<< QPointF(0, -10);
// header to left of items
QTest::newRow("horizontal, layout left to right") << QQuickListView::Horizontal << Qt::LeftToRight << QQuickItemView::TopToBottom
<< QPointF(-100, 0)
<< QPointF(-50, 0)
<< QPointF(-100, 0)
<< QPointF(-50, 0)
<< QPointF(0, 0)
<< QPointF(-40, 0);
// header to right of items
QTest::newRow("horizontal, layout right to left") << QQuickListView::Horizontal << Qt::RightToLeft << QQuickItemView::TopToBottom
<< QPointF(0, 0)
<< QPointF(0, 0)
<< QPointF(-240 + 100, 0)
<< QPointF(-240 + 50, 0)
<< QPointF(-240, 0)
<< QPointF(-240 + 40, 0);
// header below items
QTest::newRow("vertical, bottom to top") << QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::BottomToTop
<< QPointF(0, 0)
<< QPointF(0, 0)
<< QPointF(0, -320 + 30)
<< QPointF(0, -320 + 20)
<< QPointF(0, -30)
<< QPointF(0, -320 + 10);
}
void tst_QQuickListView::header_delayItemCreation()
{
QScopedPointer<QQuickView> window(createView());
QaimModel model;
window->rootContext()->setContextProperty("setCurrentToZero", QVariant(false));
window->setSource(testFileUrl("fillModelOnComponentCompleted.qml"));
qApp->processEvents();
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QQuickText *header = findItem<QQuickText>(contentItem, "header");
QVERIFY(header);
QCOMPARE(header->y(), -header->height());
QCOMPARE(listview->contentY(), -header->height());
model.clear();
QTRY_COMPARE(header->y(), -header->height());
}
void tst_QQuickListView::headerChangesViewport()
{
QQuickView *window = getView();
window->rootContext()->setContextProperty("headerHeight", 20);
window->rootContext()->setContextProperty("headerWidth", 240);
window->setSource(testFileUrl("headerchangesviewport.qml"));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QQuickText *header = 0;
QTRY_VERIFY(header = findItem<QQuickText>(contentItem, "header"));
QCOMPARE(header, listview->headerItem());
QCOMPARE(header->height(), 20.);
QCOMPARE(listview->contentHeight(), 20.);
// change height
window->rootContext()->setContextProperty("headerHeight", 50);
// verify that list content height updates also
QCOMPARE(header->height(), 50.);
QCOMPARE(listview->contentHeight(), 50.);
}
void tst_QQuickListView::footer()
{
QFETCH(QQuickListView::Orientation, orientation);
QFETCH(Qt::LayoutDirection, layoutDirection);
QFETCH(QQuickItemView::VerticalLayoutDirection, verticalLayoutDirection);
QFETCH(QPointF, initialFooterPos);
QFETCH(QPointF, firstDelegatePos);
QFETCH(QPointF, initialContentPos);
QFETCH(QPointF, changedFooterPos);
QFETCH(QPointF, changedContentPos);
QFETCH(QPointF, resizeContentPos);
QQuickView *window = getView();
QaimModel model;
for (int i = 0; i < 3; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
window->setSource(testFileUrl("footer.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
listview->setOrientation(orientation);
listview->setLayoutDirection(layoutDirection);
listview->setVerticalLayoutDirection(verticalLayoutDirection);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QQuickText *footer = findItem<QQuickText>(contentItem, "footer");
QVERIFY(footer);
QCOMPARE(footer, listview->footerItem());
QCOMPARE(footer->position(), initialFooterPos);
QCOMPARE(footer->width(), 100.);
QCOMPARE(footer->height(), 30.);
QCOMPARE(QPointF(listview->contentX(), listview->contentY()), initialContentPos);
if (orientation == QQuickListView::Vertical)
QCOMPARE(listview->contentHeight(), model.count() * 20. + footer->height());
else
QCOMPARE(listview->contentWidth(), model.count() * 40. + footer->width());
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", 0);
QVERIFY(item);
QCOMPARE(item->position(), firstDelegatePos);
// remove one item
model.removeItem(1);
if (orientation == QQuickListView::Vertical) {
QTRY_COMPARE(footer->y(), verticalLayoutDirection == QQuickItemView::TopToBottom ?
initialFooterPos.y() - 20 : initialFooterPos.y() + 20); // delegate width = 40
} else {
QTRY_COMPARE(footer->x(), layoutDirection == Qt::LeftToRight ?
initialFooterPos.x() - 40 : initialFooterPos.x() + 40); // delegate width = 40
}
// remove all items
model.clear();
if (orientation == QQuickListView::Vertical)
QTRY_COMPARE(listview->contentHeight(), footer->height());
else
QTRY_COMPARE(listview->contentWidth(), footer->width());
QPointF posWhenNoItems(0, 0);
if (orientation == QQuickListView::Horizontal && layoutDirection == Qt::RightToLeft)
posWhenNoItems.setX(-100);
else if (orientation == QQuickListView::Vertical && verticalLayoutDirection == QQuickItemView::BottomToTop)
posWhenNoItems.setY(-30);
QTRY_COMPARE(footer->position(), posWhenNoItems);
// if header is present, it's at a negative pos, so the footer should not move
window->rootObject()->setProperty("showHeader", true);
QTRY_COMPARE(footer->position(), posWhenNoItems);
window->rootObject()->setProperty("showHeader", false);
// add 30 items
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), "");
QSignalSpy footerItemSpy(listview, SIGNAL(footerItemChanged()));
QMetaObject::invokeMethod(window->rootObject(), "changeFooter");
QCOMPARE(footerItemSpy.count(), 1);
footer = findItem<QQuickText>(contentItem, "footer");
QVERIFY(!footer);
footer = findItem<QQuickText>(contentItem, "footer2");
QVERIFY(footer);
QCOMPARE(footer, listview->footerItem());
QCOMPARE(footer->position(), changedFooterPos);
QCOMPARE(footer->width(), 50.);
QCOMPARE(footer->height(), 20.);
QTRY_COMPARE(QPointF(listview->contentX(), listview->contentY()), changedContentPos);
item = findItem<QQuickItem>(contentItem, "wrapper", 0);
QVERIFY(item);
QCOMPARE(item->position(), firstDelegatePos);
listview->positionViewAtEnd();
footer->setHeight(10);
footer->setWidth(40);
QTRY_COMPARE(QPointF(listview->contentX(), listview->contentY()), resizeContentPos);
releaseView(window);
}
void tst_QQuickListView::footer_data()
{
QTest::addColumn<QQuickListView::Orientation>("orientation");
QTest::addColumn<Qt::LayoutDirection>("layoutDirection");
QTest::addColumn<QQuickItemView::VerticalLayoutDirection>("verticalLayoutDirection");
QTest::addColumn<QPointF>("initialFooterPos");
QTest::addColumn<QPointF>("changedFooterPos");
QTest::addColumn<QPointF>("initialContentPos");
QTest::addColumn<QPointF>("changedContentPos");
QTest::addColumn<QPointF>("firstDelegatePos");
QTest::addColumn<QPointF>("resizeContentPos");
// footer1 = 100 x 30
// footer2 = 50 x 20
// delegates = 40 x 20
// view width = 240
// view height = 320
// footer below items, bottom left
QTest::newRow("vertical, layout left to right") << QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::TopToBottom
<< QPointF(0, 3 * 20)
<< QPointF(0, 30 * 20) // added 30 items
<< QPointF(0, 0)
<< QPointF(0, 0)
<< QPointF(0, 0)
<< QPointF(0, 30 * 20 - 320 + 10);
// footer below items, bottom right
QTest::newRow("vertical, layout right to left") << QQuickListView::Vertical << Qt::RightToLeft << QQuickItemView::TopToBottom
<< QPointF(0, 3 * 20)
<< QPointF(0, 30 * 20)
<< QPointF(0, 0)
<< QPointF(0, 0)
<< QPointF(0, 0)
<< QPointF(0, 30 * 20 - 320 + 10);
// footer to right of items
QTest::newRow("horizontal, layout left to right") << QQuickListView::Horizontal << Qt::LeftToRight << QQuickItemView::TopToBottom
<< QPointF(40 * 3, 0)
<< QPointF(40 * 30, 0)
<< QPointF(0, 0)
<< QPointF(0, 0)
<< QPointF(0, 0)
<< QPointF(40 * 30 - 240 + 40, 0);
// footer to left of items
QTest::newRow("horizontal, layout right to left") << QQuickListView::Horizontal << Qt::RightToLeft << QQuickItemView::TopToBottom
<< QPointF(-(40 * 3) - 100, 0)
<< QPointF(-(40 * 30) - 50, 0) // 50 = new footer width
<< QPointF(-240, 0)
<< QPointF(-240, 0)
<< QPointF(-40, 0)
<< QPointF(-(40 * 30) - 40, 0);
// footer above items
QTest::newRow("vertical, layout left to right") << QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::BottomToTop
<< QPointF(0, -(3 * 20) - 30)
<< QPointF(0, -(30 * 20) - 20)
<< QPointF(0, -320)
<< QPointF(0, -320)
<< QPointF(0, -20)
<< QPointF(0, -(30 * 20) - 10);
}
class LVAccessor : public QQuickListView
{
public:
qreal minY() const { return minYExtent(); }
qreal maxY() const { return maxYExtent(); }
qreal minX() const { return minXExtent(); }
qreal maxX() const { return maxXExtent(); }
};
void tst_QQuickListView::extents()
{
QFETCH(QQuickListView::Orientation, orientation);
QFETCH(Qt::LayoutDirection, layoutDirection);
QFETCH(QQuickItemView::VerticalLayoutDirection, verticalLayoutDirection);
QFETCH(QPointF, headerPos);
QFETCH(QPointF, footerPos);
QFETCH(QPointF, minPos);
QFETCH(QPointF, maxPos);
QFETCH(QPointF, origin_empty);
QFETCH(QPointF, origin_short);
QFETCH(QPointF, origin_long);
QQuickView *window = getView();
QaimModel model;
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
window->setSource(testFileUrl("headerfooter.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = qobject_cast<QQuickListView*>(window->rootObject());
QTRY_VERIFY(listview != 0);
listview->setOrientation(orientation);
listview->setLayoutDirection(layoutDirection);
listview->setVerticalLayoutDirection(verticalLayoutDirection);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QQuickItem *header = findItem<QQuickItem>(contentItem, "header");
QVERIFY(header);
QCOMPARE(header->position(), headerPos);
QQuickItem *footer = findItem<QQuickItem>(contentItem, "footer");
QVERIFY(footer);
QCOMPARE(footer->position(), footerPos);
QCOMPARE(static_cast<LVAccessor*>(listview)->minX(), minPos.x());
QCOMPARE(static_cast<LVAccessor*>(listview)->minY(), minPos.y());
QCOMPARE(static_cast<LVAccessor*>(listview)->maxX(), maxPos.x());
QCOMPARE(static_cast<LVAccessor*>(listview)->maxY(), maxPos.y());
QCOMPARE(listview->originX(), origin_empty.x());
QCOMPARE(listview->originY(), origin_empty.y());
for (int i=0; i<3; i++)
model.addItem("Item" + QString::number(i), "");
listview->forceLayout();
QTRY_COMPARE(listview->count(), model.count());
QCOMPARE(listview->originX(), origin_short.x());
QCOMPARE(listview->originY(), origin_short.y());
for (int i=3; i<30; i++)
model.addItem("Item" + QString::number(i), "");
listview->forceLayout();
QTRY_COMPARE(listview->count(), model.count());
QCOMPARE(listview->originX(), origin_long.x());
QCOMPARE(listview->originY(), origin_long.y());
releaseView(window);
}
void tst_QQuickListView::extents_data()
{
QTest::addColumn<QQuickListView::Orientation>("orientation");
QTest::addColumn<Qt::LayoutDirection>("layoutDirection");
QTest::addColumn<QQuickItemView::VerticalLayoutDirection>("verticalLayoutDirection");
QTest::addColumn<QPointF>("headerPos");
QTest::addColumn<QPointF>("footerPos");
QTest::addColumn<QPointF>("minPos");
QTest::addColumn<QPointF>("maxPos");
QTest::addColumn<QPointF>("origin_empty");
QTest::addColumn<QPointF>("origin_short");
QTest::addColumn<QPointF>("origin_long");
// header is 240x20 (or 20x320 in Horizontal orientation)
// footer is 240x30 (or 30x320 in Horizontal orientation)
QTest::newRow("Vertical, TopToBottom")
<< QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::TopToBottom
<< QPointF(0, -20) << QPointF(0, 0)
<< QPointF(0, 20) << QPointF(240, 20)
<< QPointF(0, -20) << QPointF(0, -20) << QPointF(0, -20);
QTest::newRow("Vertical, BottomToTop")
<< QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::BottomToTop
<< QPointF(0, 0) << QPointF(0, -30)
<< QPointF(0, 320 - 20) << QPointF(240, 320 - 20) // content flow is reversed
<< QPointF(0, -30) << QPointF(0, (-30.0 * 3) - 30) << QPointF(0, (-30.0 * 30) - 30);
QTest::newRow("Horizontal, LeftToRight")
<< QQuickListView::Horizontal << Qt::LeftToRight << QQuickItemView::TopToBottom
<< QPointF(-20, 0) << QPointF(0, 0)
<< QPointF(20, 0) << QPointF(20, 320)
<< QPointF(-20, 0) << QPointF(-20, 0) << QPointF(-20, 0);
QTest::newRow("Horizontal, RightToLeft")
<< QQuickListView::Horizontal << Qt::RightToLeft << QQuickItemView::TopToBottom
<< QPointF(0, 0) << QPointF(-30, 0)
<< QPointF(240 - 20, 0) << QPointF(240 - 20, 320) // content flow is reversed
<< QPointF(-30, 0) << QPointF((-240.0 * 3) - 30, 0) << QPointF((-240.0 * 30) - 30, 0);
}
void tst_QQuickListView::resetModel_headerFooter()
{
// Resetting a model shouldn't crash in views with header/footer
QScopedPointer<QQuickView> window(createView());
QaimModel model;
for (int i = 0; i < 4; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
window->setSource(testFileUrl("headerfooter.qml"));
qApp->processEvents();
QQuickListView *listview = qobject_cast<QQuickListView*>(window->rootObject());
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QQuickItem *header = findItem<QQuickItem>(contentItem, "header");
QVERIFY(header);
QCOMPARE(header->y(), -header->height());
QQuickItem *footer = findItem<QQuickItem>(contentItem, "footer");
QVERIFY(footer);
QCOMPARE(footer->y(), 30.*4);
model.reset();
// A reset should not force a new header or footer to be created.
QQuickItem *newHeader = findItem<QQuickItem>(contentItem, "header");
QCOMPARE(newHeader, header);
QCOMPARE(header->y(), -header->height());
QQuickItem *newFooter = findItem<QQuickItem>(contentItem, "footer");
QCOMPARE(newFooter, footer);
QCOMPARE(footer->y(), 30.*4);
}
void tst_QQuickListView::resizeView()
{
QScopedPointer<QQuickView> window(createView());
QaimModel model;
for (int i = 0; i < 40; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(testFileUrl("listviewtest.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// Confirm items positioned correctly
int itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i = 0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), i*20.);
}
QVariant heightRatio;
QMetaObject::invokeMethod(window->rootObject(), "heightRatio", Q_RETURN_ARG(QVariant, heightRatio));
QCOMPARE(heightRatio.toReal(), 0.4);
listview->setHeight(200);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QMetaObject::invokeMethod(window->rootObject(), "heightRatio", Q_RETURN_ARG(QVariant, heightRatio));
QCOMPARE(heightRatio.toReal(), 0.25);
// Ensure we handle -ve sizes
listview->setHeight(-100);
QTRY_COMPARE(findItems<QQuickItem>(contentItem, "wrapper", false).count(), 1);
listview->setCacheBuffer(200);
QTRY_COMPARE(findItems<QQuickItem>(contentItem, "wrapper", false).count(), 11);
// ensure items in cache become visible
listview->setHeight(200);
QTRY_COMPARE(findItems<QQuickItem>(contentItem, "wrapper", false).count(), 21);
itemCount = findItems<QQuickItem>(contentItem, "wrapper", false).count();
for (int i = 0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), i*20.);
QCOMPARE(delegateVisible(item), i < 11); // inside view visible, outside not visible
}
// ensure items outside view become invisible
listview->setHeight(100);
QTRY_COMPARE(findItems<QQuickItem>(contentItem, "wrapper", false).count(), 16);
itemCount = findItems<QQuickItem>(contentItem, "wrapper", false).count();
for (int i = 0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), i*20.);
QCOMPARE(delegateVisible(item), i < 6); // inside view visible, outside not visible
}
delete testObject;
}
void tst_QQuickListView::resizeViewAndRepaint()
{
QScopedPointer<QQuickView> window(createView());
QaimModel model;
for (int i = 0; i < 40; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
ctxt->setContextProperty("initialHeight", 100);
window->setSource(testFileUrl("resizeview.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// item at index 10 should not be currently visible
QVERIFY(!findItem<QQuickItem>(contentItem, "wrapper", 10));
listview->setHeight(320);
QTRY_VERIFY(findItem<QQuickItem>(contentItem, "wrapper", 10));
listview->setHeight(100);
QTRY_VERIFY(!findItem<QQuickItem>(contentItem, "wrapper", 10));
}
void tst_QQuickListView::sizeLessThan1()
{
QScopedPointer<QQuickView> window(createView());
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(testFileUrl("sizelessthan1.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// Confirm items positioned correctly
int itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i = 0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), i*0.5);
}
delete testObject;
}
void tst_QQuickListView::QTBUG_14821()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("qtbug14821.qml"));
qApp->processEvents();
QQuickListView *listview = qobject_cast<QQuickListView*>(window->rootObject());
QVERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QVERIFY(contentItem != 0);
listview->decrementCurrentIndex();
QCOMPARE(listview->currentIndex(), 99);
listview->incrementCurrentIndex();
QCOMPARE(listview->currentIndex(), 0);
}
void tst_QQuickListView::resizeDelegate()
{
QScopedPointer<QQuickView> window(createView());
QStringList strings;
for (int i = 0; i < 30; ++i)
strings << QString::number(i);
QStringListModel model(strings);
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
window->setSource(testFileUrl("displaylist.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QVERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QVERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QCOMPARE(listview->count(), model.rowCount());
listview->setCurrentIndex(25);
listview->setContentY(0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
for (int i = 0; i < 16; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY(item != 0);
QCOMPARE(item->y(), i*20.0);
}
QCOMPARE(listview->currentItem()->y(), 500.0);
QTRY_COMPARE(listview->highlightItem()->y(), 500.0);
window->rootObject()->setProperty("delegateHeight", 30);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
for (int i = 0; i < 11; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY(item != 0);
QTRY_COMPARE(item->y(), i*30.0);
}
QTRY_COMPARE(listview->currentItem()->y(), 750.0);
QTRY_COMPARE(listview->highlightItem()->y(), 750.0);
listview->setCurrentIndex(1);
listview->positionViewAtIndex(25, QQuickListView::Beginning);
listview->positionViewAtIndex(5, QQuickListView::Beginning);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
for (int i = 5; i < 16; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY(item != 0);
QCOMPARE(item->y(), i*30.0);
}
QTRY_COMPARE(listview->currentItem()->y(), 30.0);
QTRY_COMPARE(listview->highlightItem()->y(), 30.0);
window->rootObject()->setProperty("delegateHeight", 20);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
for (int i = 5; i < 11; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY(item != 0);
QTRY_COMPARE(item->y(), 150 + (i-5)*20.0);
}
QTRY_COMPARE(listview->currentItem()->y(), 70.0);
QTRY_COMPARE(listview->highlightItem()->y(), 70.0);
}
void tst_QQuickListView::resizeFirstDelegate()
{
// QTBUG-20712: Content Y jumps constantly if first delegate height == 0
// and other delegates have height > 0
QScopedPointer<QQuickView> window(createView());
// bug only occurs when all items in the model are visible
QaimModel model;
for (int i = 0; i < 10; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(testFileUrl("listviewtest.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QVERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QVERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QQuickItem *item = 0;
for (int i = 0; i < model.count(); ++i) {
item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY(item != 0);
QCOMPARE(item->y(), i*20.0);
}
item = findItem<QQuickItem>(contentItem, "wrapper", 0);
item->setHeight(0);
// check the content y has not jumped up and down
QCOMPARE(listview->contentY(), 0.0);
QSignalSpy spy(listview, SIGNAL(contentYChanged()));
QTest::qWait(100);
QCOMPARE(spy.count(), 0);
for (int i = 1; i < model.count(); ++i) {
item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY(item != 0);
QTRY_COMPARE(item->y(), (i-1)*20.0);
}
// QTBUG-22014: refill doesn't clear items scrolling off the top of the
// list if they follow a zero-sized delegate
for (int i = 0; i < 10; i++)
model.addItem("Item" + QString::number(i), "");
listview->forceLayout();
QTRY_COMPARE(listview->count(), model.count());
item = findItem<QQuickItem>(contentItem, "wrapper", 1);
QVERIFY(item);
item->setHeight(0);
listview->setCurrentIndex(19);
qApp->processEvents();
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// items 0-2 should have been deleted
for (int i=0; i<3; i++) {
QTRY_VERIFY(!findItem<QQuickItem>(contentItem, "wrapper", i));
}
delete testObject;
}
void tst_QQuickListView::repositionResizedDelegate()
{
QFETCH(QQuickListView::Orientation, orientation);
QFETCH(Qt::LayoutDirection, layoutDirection);
QFETCH(QQuickItemView::VerticalLayoutDirection, verticalLayoutDirection);
QFETCH(QPointF, contentPos_itemFirstHalfVisible);
QFETCH(QPointF, contentPos_itemSecondHalfVisible);
QFETCH(QRectF, origPositionerRect);
QFETCH(QRectF, resizedPositionerRect);
QQuickView *window = getView();
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testHorizontal", orientation == QQuickListView::Horizontal);
ctxt->setContextProperty("testRightToLeft", layoutDirection == Qt::RightToLeft);
ctxt->setContextProperty("testBottomToTop", verticalLayoutDirection == QQuickListView::BottomToTop);
window->setSource(testFileUrl("repositionResizedDelegate.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = qobject_cast<QQuickListView*>(window->rootObject());
QTRY_VERIFY(listview != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QQuickItem *positioner = findItem<QQuickItem>(window->rootObject(), "positioner");
QVERIFY(positioner);
QTRY_COMPARE(positioner->boundingRect().size(), origPositionerRect.size());
QTRY_COMPARE(positioner->position(), origPositionerRect.topLeft());
QSignalSpy spy(listview, orientation == QQuickListView::Vertical ? SIGNAL(contentYChanged()) : SIGNAL(contentXChanged()));
int prevSpyCount = 0;
// When an item is resized while it is partially visible, it should resize in the
// direction of the content flow. If a RightToLeft or BottomToTop layout is used,
// the item should also be re-positioned so its end position stays the same.
listview->setContentX(contentPos_itemFirstHalfVisible.x());
listview->setContentY(contentPos_itemFirstHalfVisible.y());
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
prevSpyCount = spy.count();
QVERIFY(QMetaObject::invokeMethod(window->rootObject(), "incrementRepeater"));
QTRY_COMPARE(positioner->boundingRect().size(), resizedPositionerRect.size());
QTRY_COMPARE(positioner->position(), resizedPositionerRect.topLeft());
QCOMPARE(listview->contentX(), contentPos_itemFirstHalfVisible.x());
QCOMPARE(listview->contentY(), contentPos_itemFirstHalfVisible.y());
QCOMPARE(spy.count(), prevSpyCount);
QVERIFY(QMetaObject::invokeMethod(window->rootObject(), "decrementRepeater"));
QTRY_COMPARE(positioner->boundingRect().size(), origPositionerRect.size());
QTRY_COMPARE(positioner->position(), origPositionerRect.topLeft());
QCOMPARE(listview->contentX(), contentPos_itemFirstHalfVisible.x());
QCOMPARE(listview->contentY(), contentPos_itemFirstHalfVisible.y());
listview->setContentX(contentPos_itemSecondHalfVisible.x());
listview->setContentY(contentPos_itemSecondHalfVisible.y());
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
prevSpyCount = spy.count();
QVERIFY(QMetaObject::invokeMethod(window->rootObject(), "incrementRepeater"));
positioner = findItem<QQuickItem>(window->rootObject(), "positioner");
QTRY_COMPARE(positioner->boundingRect().size(), resizedPositionerRect.size());
QTRY_COMPARE(positioner->position(), resizedPositionerRect.topLeft());
QCOMPARE(listview->contentX(), contentPos_itemSecondHalfVisible.x());
QCOMPARE(listview->contentY(), contentPos_itemSecondHalfVisible.y());
qApp->processEvents();
QCOMPARE(spy.count(), prevSpyCount);
releaseView(window);
}
void tst_QQuickListView::repositionResizedDelegate_data()
{
QTest::addColumn<QQuickListView::Orientation>("orientation");
QTest::addColumn<Qt::LayoutDirection>("layoutDirection");
QTest::addColumn<QQuickListView::VerticalLayoutDirection>("verticalLayoutDirection");
QTest::addColumn<QPointF>("contentPos_itemFirstHalfVisible");
QTest::addColumn<QPointF>("contentPos_itemSecondHalfVisible");
QTest::addColumn<QRectF>("origPositionerRect");
QTest::addColumn<QRectF>("resizedPositionerRect");
QTest::newRow("vertical")
<< QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::TopToBottom
<< QPointF(0, 60) << QPointF(0, 200 + 60)
<< QRectF(0, 200, 120, 120)
<< QRectF(0, 200, 120, 120 * 2);
QTest::newRow("vertical, BottomToTop")
<< QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::BottomToTop
<< QPointF(0, -200 - 60) << QPointF(0, -200 - 260)
<< QRectF(0, -200 - 120, 120, 120)
<< QRectF(0, -200 - 120*2, 120, 120 * 2);
QTest::newRow("horizontal")
<< QQuickListView::Horizontal<< Qt::LeftToRight << QQuickItemView::TopToBottom
<< QPointF(60, 0) << QPointF(260, 0)
<< QRectF(200, 0, 120, 120)
<< QRectF(200, 0, 120 * 2, 120);
QTest::newRow("horizontal, rtl")
<< QQuickListView::Horizontal << Qt::RightToLeft << QQuickItemView::TopToBottom
<< QPointF(-200 - 60, 0) << QPointF(-200 - 260, 0)
<< QRectF(-200 - 120, 0, 120, 120)
<< QRectF(-200 - 120 * 2, 0, 120 * 2, 120);
}
void tst_QQuickListView::QTBUG_16037()
{
QScopedPointer<QQuickView> window(createView());
window->show();
window->setSource(testFileUrl("qtbug16037.qml"));
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "listview");
QTRY_VERIFY(listview != 0);
QVERIFY(listview->contentHeight() <= 0.0);
QMetaObject::invokeMethod(window->rootObject(), "setModel");
QTRY_COMPARE(listview->contentHeight(), 80.0);
}
void tst_QQuickListView::indexAt_itemAt_data()
{
QTest::addColumn<qreal>("x");
QTest::addColumn<qreal>("y");
QTest::addColumn<int>("index");
QTest::newRow("Item 0 - 0, 0") << 0. << 0. << 0;
QTest::newRow("Item 0 - 0, 19") << 0. << 19. << 0;
QTest::newRow("Item 0 - 239, 19") << 239. << 19. << 0;
QTest::newRow("Item 1 - 0, 20") << 0. << 20. << 1;
QTest::newRow("No Item - 240, 20") << 240. << 20. << -1;
}
void tst_QQuickListView::indexAt_itemAt()
{
QFETCH(qreal, x);
QFETCH(qreal, y);
QFETCH(int, index);
QQuickView *window = getView();
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", testObject);
window->setSource(testFileUrl("listviewtest.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QQuickItem *item = 0;
if (index >= 0) {
item = findItem<QQuickItem>(contentItem, "wrapper", index);
QVERIFY(item);
}
QCOMPARE(listview->indexAt(x,y), index);
QCOMPARE(listview->itemAt(x,y), item);
releaseView(window);
delete testObject;
}
void tst_QQuickListView::incrementalModel()
{
QScopedPointer<QQuickView> window(createView());
QSKIP("QTBUG-30716");
IncrementalModel model;
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
window->setSource(testFileUrl("displaylist.qml"));
qApp->processEvents();
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
listview->forceLayout();
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
listview->forceLayout();
QTRY_COMPARE(listview->count(), 20);
listview->positionViewAtIndex(10, QQuickListView::Beginning);
listview->forceLayout();
QTRY_COMPARE(listview->count(), 25);
}
void tst_QQuickListView::onAdd()
{
QFETCH(int, initialItemCount);
QFETCH(int, itemsToAdd);
const int delegateHeight = 10;
QaimModel model;
// these initial items should not trigger ListView.onAdd
for (int i=0; i<initialItemCount; i++)
model.addItem("dummy value", "dummy value");
QScopedPointer<QQuickView> window(createView());
window->setGeometry(0,0,200, delegateHeight * (initialItemCount + itemsToAdd));
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
ctxt->setContextProperty("delegateHeight", delegateHeight);
window->setSource(testFileUrl("attachedSignals.qml"));
QQuickListView* listview = qobject_cast<QQuickListView*>(window->rootObject());
listview->setProperty("width", window->width());
listview->setProperty("height", window->height());
qApp->processEvents();
QList<QPair<QString, QString> > items;
for (int i=0; i<itemsToAdd; i++)
items << qMakePair(QString("value %1").arg(i), QString::number(i));
model.addItems(items);
listview->forceLayout();
QTRY_COMPARE(listview->property("count").toInt(), model.count());
QVariantList result = listview->property("addedDelegates").toList();
QCOMPARE(result.count(), items.count());
for (int i=0; i<items.count(); i++)
QCOMPARE(result[i].toString(), items[i].first);
}
void tst_QQuickListView::onAdd_data()
{
QTest::addColumn<int>("initialItemCount");
QTest::addColumn<int>("itemsToAdd");
QTest::newRow("0, add 1") << 0 << 1;
QTest::newRow("0, add 2") << 0 << 2;
QTest::newRow("0, add 10") << 0 << 10;
QTest::newRow("1, add 1") << 1 << 1;
QTest::newRow("1, add 2") << 1 << 2;
QTest::newRow("1, add 10") << 1 << 10;
QTest::newRow("5, add 1") << 5 << 1;
QTest::newRow("5, add 2") << 5 << 2;
QTest::newRow("5, add 10") << 5 << 10;
}
void tst_QQuickListView::onRemove()
{
QFETCH(int, initialItemCount);
QFETCH(int, indexToRemove);
QFETCH(int, removeCount);
const int delegateHeight = 10;
QaimModel model;
for (int i=0; i<initialItemCount; i++)
model.addItem(QString("value %1").arg(i), "dummy value");
QQuickView *window = getView();
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
ctxt->setContextProperty("delegateHeight", delegateHeight);
window->setSource(testFileUrl("attachedSignals.qml"));
QQuickListView *listview = qobject_cast<QQuickListView *>(window->rootObject());
model.removeItems(indexToRemove, removeCount);
listview->forceLayout();
QTRY_COMPARE(listview->property("count").toInt(), model.count());
QCOMPARE(listview->property("removedDelegateCount"), QVariant(removeCount));
releaseView(window);
}
void tst_QQuickListView::onRemove_data()
{
QTest::addColumn<int>("initialItemCount");
QTest::addColumn<int>("indexToRemove");
QTest::addColumn<int>("removeCount");
QTest::newRow("remove first") << 1 << 0 << 1;
QTest::newRow("two items, remove first") << 2 << 0 << 1;
QTest::newRow("two items, remove last") << 2 << 1 << 1;
QTest::newRow("two items, remove all") << 2 << 0 << 2;
QTest::newRow("four items, remove first") << 4 << 0 << 1;
QTest::newRow("four items, remove 0-2") << 4 << 0 << 2;
QTest::newRow("four items, remove 1-3") << 4 << 1 << 2;
QTest::newRow("four items, remove 2-4") << 4 << 2 << 2;
QTest::newRow("four items, remove last") << 4 << 3 << 1;
QTest::newRow("four items, remove all") << 4 << 0 << 4;
QTest::newRow("ten items, remove 1-8") << 10 << 0 << 8;
QTest::newRow("ten items, remove 2-7") << 10 << 2 << 5;
QTest::newRow("ten items, remove 4-10") << 10 << 4 << 6;
}
void tst_QQuickListView::rightToLeft()
{
QScopedPointer<QQuickView> window(createView());
window->setGeometry(0,0,640,320);
window->setSource(testFileUrl("rightToLeft.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QVERIFY(window->rootObject() != 0);
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "view");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QQmlObjectModel *model = window->rootObject()->findChild<QQmlObjectModel*>("itemModel");
QTRY_VERIFY(model != 0);
QTRY_COMPARE(model->count(), 3);
QTRY_COMPARE(listview->currentIndex(), 0);
// initial position at first item, right edge aligned
QCOMPARE(listview->contentX(), -640.);
QQuickItem *item = findItem<QQuickItem>(contentItem, "item1");
QTRY_VERIFY(item);
QTRY_COMPARE(item->x(), -100.0);
QCOMPARE(item->height(), listview->height());
QQuickText *text = findItem<QQuickText>(contentItem, "text1");
QTRY_VERIFY(text);
QTRY_COMPARE(text->text(), QLatin1String("index: 0"));
listview->setCurrentIndex(2);
item = findItem<QQuickItem>(contentItem, "item3");
QTRY_VERIFY(item);
QTRY_COMPARE(item->x(), -540.0);
text = findItem<QQuickText>(contentItem, "text3");
QTRY_VERIFY(text);
QTRY_COMPARE(text->text(), QLatin1String("index: 2"));
QCOMPARE(listview->contentX(), -640.);
// Ensure resizing maintains position relative to right edge
qobject_cast<QQuickItem*>(window->rootObject())->setWidth(600);
QTRY_COMPARE(listview->contentX(), -600.);
}
void tst_QQuickListView::test_mirroring()
{
QScopedPointer<QQuickView> windowA(createView());
windowA->setSource(testFileUrl("rightToLeft.qml"));
QQuickListView *listviewA = findItem<QQuickListView>(windowA->rootObject(), "view");
QTRY_VERIFY(listviewA != 0);
QScopedPointer<QQuickView> windowB(createView());
windowB->setSource(testFileUrl("rightToLeft.qml"));
QQuickListView *listviewB = findItem<QQuickListView>(windowB->rootObject(), "view");
QTRY_VERIFY(listviewA != 0);
qApp->processEvents();
QList<QString> objectNames;
objectNames << "item1" << "item2"; // << "item3"
listviewA->setProperty("layoutDirection", Qt::LeftToRight);
listviewB->setProperty("layoutDirection", Qt::RightToLeft);
QCOMPARE(listviewA->layoutDirection(), listviewA->effectiveLayoutDirection());
// LTR != RTL
foreach (const QString objectName, objectNames)
QVERIFY(findItem<QQuickItem>(listviewA, objectName)->x() != findItem<QQuickItem>(listviewB, objectName)->x());
listviewA->setProperty("layoutDirection", Qt::LeftToRight);
listviewB->setProperty("layoutDirection", Qt::LeftToRight);
// LTR == LTR
foreach (const QString objectName, objectNames)
QCOMPARE(findItem<QQuickItem>(listviewA, objectName)->x(), findItem<QQuickItem>(listviewB, objectName)->x());
QCOMPARE(listviewB->layoutDirection(), listviewB->effectiveLayoutDirection());
QQuickItemPrivate::get(listviewB)->setLayoutMirror(true);
QVERIFY(listviewB->layoutDirection() != listviewB->effectiveLayoutDirection());
// LTR != LTR+mirror
foreach (const QString objectName, objectNames)
QVERIFY(findItem<QQuickItem>(listviewA, objectName)->x() != findItem<QQuickItem>(listviewB, objectName)->x());
listviewA->setProperty("layoutDirection", Qt::RightToLeft);
// RTL == LTR+mirror
foreach (const QString objectName, objectNames)
QCOMPARE(findItem<QQuickItem>(listviewA, objectName)->x(), findItem<QQuickItem>(listviewB, objectName)->x());
listviewB->setProperty("layoutDirection", Qt::RightToLeft);
// RTL != RTL+mirror
foreach (const QString objectName, objectNames)
QVERIFY(findItem<QQuickItem>(listviewA, objectName)->x() != findItem<QQuickItem>(listviewB, objectName)->x());
listviewA->setProperty("layoutDirection", Qt::LeftToRight);
// LTR == RTL+mirror
foreach (const QString objectName, objectNames)
QCOMPARE(findItem<QQuickItem>(listviewA, objectName)->x(), findItem<QQuickItem>(listviewB, objectName)->x());
}
void tst_QQuickListView::margins()
{
QScopedPointer<QQuickView> window(createView());
QaimModel model;
for (int i = 0; i < 50; i++)
model.addItem("Item" + QString::number(i), "");
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
window->setSource(testFileUrl("margins.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QCOMPARE(listview->contentY(), -30.);
QCOMPARE(listview->originY(), 0.);
// check end bound
listview->positionViewAtEnd();
qreal pos = listview->contentY();
listview->setContentY(pos + 80);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
listview->returnToBounds();
QTRY_COMPARE(listview->contentY(), pos + 50);
// remove item before visible and check that top margin is maintained
// and originY is updated
listview->setContentY(100);
model.removeItem(1);
listview->forceLayout();
QTRY_COMPARE(listview->count(), model.count());
listview->setContentY(-50);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
listview->returnToBounds();
QCOMPARE(listview->originY(), 20.);
QTRY_COMPARE(listview->contentY(), -10.);
// reduce top margin
listview->setTopMargin(20);
QCOMPARE(listview->originY(), 20.);
QTRY_COMPARE(listview->contentY(), 0.);
// check end bound
listview->positionViewAtEnd();
pos = listview->contentY();
listview->setContentY(pos + 80);
listview->returnToBounds();
QTRY_COMPARE(listview->contentY(), pos + 50);
// reduce bottom margin
pos = listview->contentY();
listview->setBottomMargin(40);
QCOMPARE(listview->originY(), 20.);
QTRY_COMPARE(listview->contentY(), pos-10);
}
// QTBUG-24028
void tst_QQuickListView::marginsResize()
{
QFETCH(QQuickListView::Orientation, orientation);
QFETCH(Qt::LayoutDirection, layoutDirection);
QFETCH(QQuickItemView::VerticalLayoutDirection, verticalLayoutDirection);
QFETCH(qreal, start);
QFETCH(qreal, end);
QPoint flickStart(20, 20);
QPoint flickEnd(20, 20);
if (orientation == QQuickListView::Vertical)
flickStart.ry() += (verticalLayoutDirection == QQuickItemView::TopToBottom) ? 180 : -180;
else
flickStart.rx() += (layoutDirection == Qt::LeftToRight) ? 180 : -180;
QQuickView *window = getView();
window->setSource(testFileUrl("margins2.qml"));
QQuickViewTestUtil::moveMouseAway(window);
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "listview");
QTRY_VERIFY(listview != 0);
listview->setOrientation(orientation);
listview->setLayoutDirection(layoutDirection);
listview->setVerticalLayoutDirection(verticalLayoutDirection);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// view is resized after componentCompleted - top margin should still be visible
if (orientation == QQuickListView::Vertical)
QCOMPARE(listview->contentY(), start);
else
QCOMPARE(listview->contentX(), start);
// move to last index and ensure bottom margin is visible.
listview->setCurrentIndex(19);
if (orientation == QQuickListView::Vertical)
QTRY_COMPARE(listview->contentY(), end);
else
QTRY_COMPARE(listview->contentX(), end);
// flick past the end and check content pos still settles on correct extents
flick(window, flickStart, flickEnd, 180);
QTRY_VERIFY(!listview->isMoving());
if (orientation == QQuickListView::Vertical)
QTRY_COMPARE(listview->contentY(), end);
else
QTRY_COMPARE(listview->contentX(), end);
// back to top - top margin should be visible.
listview->setCurrentIndex(0);
if (orientation == QQuickListView::Vertical)
QTRY_COMPARE(listview->contentY(), start);
else
QTRY_COMPARE(listview->contentX(), start);
// flick past the beginning and check content pos still settles on correct extents
flick(window, flickEnd, flickStart, 180);
QTRY_VERIFY(!listview->isMoving());
if (orientation == QQuickListView::Vertical)
QTRY_COMPARE(listview->contentY(), start);
else
QTRY_COMPARE(listview->contentX(), start);
releaseView(window);
}
void tst_QQuickListView::marginsResize_data()
{
QTest::addColumn<QQuickListView::Orientation>("orientation");
QTest::addColumn<Qt::LayoutDirection>("layoutDirection");
QTest::addColumn<QQuickListView::VerticalLayoutDirection>("verticalLayoutDirection");
QTest::addColumn<qreal>("start");
QTest::addColumn<qreal>("end");
// in Right to Left mode, leftMargin still means leftMargin - it doesn't reverse to mean rightMargin
QTest::newRow("vertical")
<< QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::TopToBottom
<< -40.0 << 1020.0;
QTest::newRow("vertical, BottomToTop")
<< QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::BottomToTop
<< -180.0 << -1240.0;
QTest::newRow("horizontal")
<< QQuickListView::Horizontal<< Qt::LeftToRight << QQuickItemView::TopToBottom
<< -40.0 << 1020.0;
QTest::newRow("horizontal, rtl")
<< QQuickListView::Horizontal << Qt::RightToLeft << QQuickItemView::TopToBottom
<< -180.0 << -1240.0;
}
void tst_QQuickListView::snapToItem_data()
{
QTest::addColumn<QQuickListView::Orientation>("orientation");
QTest::addColumn<Qt::LayoutDirection>("layoutDirection");
QTest::addColumn<QQuickItemView::VerticalLayoutDirection>("verticalLayoutDirection");
QTest::addColumn<int>("highlightRangeMode");
QTest::addColumn<QPoint>("flickStart");
QTest::addColumn<QPoint>("flickEnd");
QTest::addColumn<qreal>("snapAlignment");
QTest::addColumn<qreal>("endExtent");
QTest::addColumn<qreal>("startExtent");
QTest::newRow("vertical, top to bottom")
<< QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::TopToBottom << int(QQuickItemView::NoHighlightRange)
<< QPoint(20, 200) << QPoint(20, 20) << 60.0 << 560.0 << 0.0;
QTest::newRow("vertical, bottom to top")
<< QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::BottomToTop << int(QQuickItemView::NoHighlightRange)
<< QPoint(20, 20) << QPoint(20, 200) << -60.0 << -560.0 - 240.0 << -240.0;
QTest::newRow("horizontal, left to right")
<< QQuickListView::Horizontal << Qt::LeftToRight << QQuickItemView::TopToBottom << int(QQuickItemView::NoHighlightRange)
<< QPoint(200, 20) << QPoint(20, 20) << 60.0 << 560.0 << 0.0;
QTest::newRow("horizontal, right to left")
<< QQuickListView::Horizontal << Qt::RightToLeft << QQuickItemView::TopToBottom << int(QQuickItemView::NoHighlightRange)
<< QPoint(20, 20) << QPoint(200, 20) << -60.0 << -560.0 - 240.0 << -240.0;
QTest::newRow("vertical, top to bottom, enforce range")
<< QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::TopToBottom << int(QQuickItemView::StrictlyEnforceRange)
<< QPoint(20, 200) << QPoint(20, 20) << 60.0 << 700.0 << -20.0;
QTest::newRow("vertical, bottom to top, enforce range")
<< QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::BottomToTop << int(QQuickItemView::StrictlyEnforceRange)
<< QPoint(20, 20) << QPoint(20, 200) << -60.0 << -560.0 - 240.0 - 140.0 << -220.0;
QTest::newRow("horizontal, left to right, enforce range")
<< QQuickListView::Horizontal << Qt::LeftToRight << QQuickItemView::TopToBottom << int(QQuickItemView::StrictlyEnforceRange)
<< QPoint(200, 20) << QPoint(20, 20) << 60.0 << 700.0 << -20.0;
QTest::newRow("horizontal, right to left, enforce range")
<< QQuickListView::Horizontal << Qt::RightToLeft << QQuickItemView::TopToBottom << int(QQuickItemView::StrictlyEnforceRange)
<< QPoint(20, 20) << QPoint(200, 20) << -60.0 << -560.0 - 240.0 - 140.0 << -220.0;
}
void tst_QQuickListView::snapToItem()
{
QFETCH(QQuickListView::Orientation, orientation);
QFETCH(Qt::LayoutDirection, layoutDirection);
QFETCH(QQuickItemView::VerticalLayoutDirection, verticalLayoutDirection);
QFETCH(int, highlightRangeMode);
QFETCH(QPoint, flickStart);
QFETCH(QPoint, flickEnd);
QFETCH(qreal, snapAlignment);
QFETCH(qreal, endExtent);
QFETCH(qreal, startExtent);
QQuickView *window = getView();
QQuickViewTestUtil::moveMouseAway(window);
window->setSource(testFileUrl("snapToItem.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
listview->setOrientation(orientation);
listview->setLayoutDirection(layoutDirection);
listview->setVerticalLayoutDirection(verticalLayoutDirection);
listview->setHighlightRangeMode(QQuickItemView::HighlightRangeMode(highlightRangeMode));
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
// confirm that a flick hits an item boundary
flick(window, flickStart, flickEnd, 180);
QTRY_VERIFY(listview->isMoving() == false); // wait until it stops
if (orientation == QQuickListView::Vertical)
QCOMPARE(qreal(fmod(listview->contentY(),80.0)), snapAlignment);
else
QCOMPARE(qreal(fmod(listview->contentX(),80.0)), snapAlignment);
// flick to end
do {
flick(window, flickStart, flickEnd, 180);
QTRY_VERIFY(listview->isMoving() == false); // wait until it stops
} while (orientation == QQuickListView::Vertical
? verticalLayoutDirection == QQuickItemView::TopToBottom ? !listview->isAtYEnd() : !listview->isAtYBeginning()
: layoutDirection == Qt::LeftToRight ? !listview->isAtXEnd() : !listview->isAtXBeginning());
if (orientation == QQuickListView::Vertical)
QCOMPARE(listview->contentY(), endExtent);
else
QCOMPARE(listview->contentX(), endExtent);
// flick to start
do {
flick(window, flickEnd, flickStart, 180);
QTRY_VERIFY(listview->isMoving() == false); // wait until it stops
} while (orientation == QQuickListView::Vertical
? verticalLayoutDirection == QQuickItemView::TopToBottom ? !listview->isAtYBeginning() : !listview->isAtYEnd()
: layoutDirection == Qt::LeftToRight ? !listview->isAtXBeginning() : !listview->isAtXEnd());
if (orientation == QQuickListView::Vertical)
QCOMPARE(listview->contentY(), startExtent);
else
QCOMPARE(listview->contentX(), startExtent);
releaseView(window);
}
void tst_QQuickListView::snapOneItemResize_QTBUG_43555()
{
QScopedPointer<QQuickView> window(createView());
window->resize(QSize(100, 320));
window->setResizeMode(QQuickView::SizeRootObjectToView);
QQuickViewTestUtil::moveMouseAway(window.data());
window->setSource(testFileUrl("snapOneItemResize.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = qobject_cast<QQuickListView*>(window->rootObject());
QTRY_VERIFY(listview != 0);
QSignalSpy currentIndexSpy(listview, SIGNAL(currentIndexChanged()));
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QTRY_COMPARE(listview->currentIndex(), 5);
currentIndexSpy.clear();
window->resize(QSize(400, 320));
QTRY_COMPARE(int(listview->width()), 400);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QTRY_COMPARE(listview->currentIndex(), 5);
QCOMPARE(currentIndexSpy.count(), 0);
}
void tst_QQuickListView::qAbstractItemModel_package_items()
{
items<QaimModel>(testFileUrl("listviewtest-package.qml"));
}
void tst_QQuickListView::qAbstractItemModel_items()
{
items<QaimModel>(testFileUrl("listviewtest.qml"));
}
void tst_QQuickListView::qAbstractItemModel_package_changed()
{
changed<QaimModel>(testFileUrl("listviewtest-package.qml"));
}
void tst_QQuickListView::qAbstractItemModel_changed()
{
changed<QaimModel>(testFileUrl("listviewtest.qml"));
}
void tst_QQuickListView::qAbstractItemModel_package_inserted()
{
inserted<QaimModel>(testFileUrl("listviewtest-package.qml"));
}
void tst_QQuickListView::qAbstractItemModel_inserted()
{
inserted<QaimModel>(testFileUrl("listviewtest.qml"));
}
void tst_QQuickListView::qAbstractItemModel_inserted_more()
{
inserted_more<QaimModel>();
}
void tst_QQuickListView::qAbstractItemModel_inserted_more_data()
{
inserted_more_data();
}
void tst_QQuickListView::qAbstractItemModel_inserted_more_bottomToTop()
{
inserted_more<QaimModel>(QQuickItemView::BottomToTop);
}
void tst_QQuickListView::qAbstractItemModel_inserted_more_bottomToTop_data()
{
inserted_more_data();
}
void tst_QQuickListView::qAbstractItemModel_package_removed()
{
removed<QaimModel>(testFileUrl("listviewtest-package.qml"), false);
removed<QaimModel>(testFileUrl("listviewtest-package.qml"), true);
}
void tst_QQuickListView::qAbstractItemModel_removed()
{
removed<QaimModel>(testFileUrl("listviewtest.qml"), false);
removed<QaimModel>(testFileUrl("listviewtest.qml"), true);
}
void tst_QQuickListView::qAbstractItemModel_removed_more()
{
removed_more<QaimModel>(testFileUrl("listviewtest.qml"));
}
void tst_QQuickListView::qAbstractItemModel_removed_more_data()
{
removed_more_data();
}
void tst_QQuickListView::qAbstractItemModel_removed_more_bottomToTop()
{
removed_more<QaimModel>(testFileUrl("listviewtest.qml"), QQuickItemView::BottomToTop);
}
void tst_QQuickListView::qAbstractItemModel_removed_more_bottomToTop_data()
{
removed_more_data();
}
void tst_QQuickListView::qAbstractItemModel_package_moved()
{
moved<QaimModel>(testFileUrl("listviewtest-package.qml"));
}
void tst_QQuickListView::qAbstractItemModel_package_moved_data()
{
moved_data();
}
void tst_QQuickListView::qAbstractItemModel_moved()
{
moved<QaimModel>(testFileUrl("listviewtest.qml"));
}
void tst_QQuickListView::qAbstractItemModel_moved_data()
{
moved_data();
}
void tst_QQuickListView::qAbstractItemModel_moved_bottomToTop()
{
moved<QaimModel>(testFileUrl("listviewtest-package.qml"), QQuickItemView::BottomToTop);
}
void tst_QQuickListView::qAbstractItemModel_moved_bottomToTop_data()
{
moved_data();
}
void tst_QQuickListView::qAbstractItemModel_package_clear()
{
clear<QaimModel>(testFileUrl("listviewtest-package.qml"));
}
void tst_QQuickListView::qAbstractItemModel_clear()
{
clear<QaimModel>(testFileUrl("listviewtest.qml"));
}
void tst_QQuickListView::qAbstractItemModel_clear_bottomToTop()
{
clear<QaimModel>(testFileUrl("listviewtest.qml"), QQuickItemView::BottomToTop);
}
void tst_QQuickListView::qAbstractItemModel_package_sections()
{
sections<QaimModel>(testFileUrl("listview-sections-package.qml"));
}
void tst_QQuickListView::qAbstractItemModel_sections()
{
sections<QaimModel>(testFileUrl("listview-sections.qml"));
}
void tst_QQuickListView::creationContext()
{
QQuickView window;
window.setGeometry(0,0,240,320);
window.setSource(testFileUrl("creationContext.qml"));
qApp->processEvents();
QQuickItem *rootItem = qobject_cast<QQuickItem *>(window.rootObject());
QVERIFY(rootItem);
QVERIFY(rootItem->property("count").toInt() > 0);
QQuickItem *item = findItem<QQuickItem>(rootItem, "listItem");
QVERIFY(item);
QCOMPARE(item->property("text").toString(), QString("Hello!"));
item = rootItem->findChild<QQuickItem *>("header");
QVERIFY(item);
QCOMPARE(item->property("text").toString(), QString("Hello!"));
item = rootItem->findChild<QQuickItem *>("footer");
QVERIFY(item);
QCOMPARE(item->property("text").toString(), QString("Hello!"));
item = rootItem->findChild<QQuickItem *>("section");
QVERIFY(item);
QCOMPARE(item->property("text").toString(), QString("Hello!"));
}
void tst_QQuickListView::QTBUG_21742()
{
QQuickView window;
window.setGeometry(0,0,200,200);
window.setSource(testFileUrl("qtbug-21742.qml"));
qApp->processEvents();
QQuickItem *rootItem = qobject_cast<QQuickItem *>(window.rootObject());
QVERIFY(rootItem);
QCOMPARE(rootItem->property("count").toInt(), 1);
}
void tst_QQuickListView::asynchronous()
{
QScopedPointer<QQuickView> window(createView());
window->show();
QQmlIncubationController controller;
window->engine()->setIncubationController(&controller);
window->setSource(testFileUrl("asyncloader.qml"));
QQuickItem *rootObject = qobject_cast<QQuickItem*>(window->rootObject());
QVERIFY(rootObject);
QQuickListView *listview = 0;
while (!listview) {
bool b = false;
controller.incubateWhile(&b);
listview = rootObject->findChild<QQuickListView*>("view");
}
// items will be created one at a time
for (int i = 0; i < 8; ++i) {
QVERIFY(findItem<QQuickItem>(listview, "wrapper", i) == 0);
QQuickItem *item = 0;
while (!item) {
bool b = false;
controller.incubateWhile(&b);
item = findItem<QQuickItem>(listview, "wrapper", i);
}
}
{
bool b = true;
controller.incubateWhile(&b);
}
// verify positioning
QQuickItem *contentItem = listview->contentItem();
for (int i = 0; i < 8; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QTRY_COMPARE(item->y(), i*50.0);
}
}
void tst_QQuickListView::snapOneItem_data()
{
QTest::addColumn<QQuickListView::Orientation>("orientation");
QTest::addColumn<Qt::LayoutDirection>("layoutDirection");
QTest::addColumn<QQuickItemView::VerticalLayoutDirection>("verticalLayoutDirection");
QTest::addColumn<int>("highlightRangeMode");
QTest::addColumn<QPoint>("flickStart");
QTest::addColumn<QPoint>("flickEnd");
QTest::addColumn<qreal>("snapAlignment");
QTest::addColumn<qreal>("endExtent");
QTest::addColumn<qreal>("startExtent");
QTest::newRow("vertical, top to bottom")
<< QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::TopToBottom << int(QQuickItemView::NoHighlightRange)
<< QPoint(20, 200) << QPoint(20, 20) << 180.0 << 560.0 << 0.0;
QTest::newRow("vertical, bottom to top")
<< QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::BottomToTop << int(QQuickItemView::NoHighlightRange)
<< QPoint(20, 20) << QPoint(20, 200) << -420.0 << -560.0 - 240.0 << -240.0;
QTest::newRow("horizontal, left to right")
<< QQuickListView::Horizontal << Qt::LeftToRight << QQuickItemView::TopToBottom << int(QQuickItemView::NoHighlightRange)
<< QPoint(200, 20) << QPoint(20, 20) << 180.0 << 560.0 << 0.0;
QTest::newRow("horizontal, right to left")
<< QQuickListView::Horizontal << Qt::RightToLeft << QQuickItemView::TopToBottom << int(QQuickItemView::NoHighlightRange)
<< QPoint(20, 20) << QPoint(200, 20) << -420.0 << -560.0 - 240.0 << -240.0;
QTest::newRow("vertical, top to bottom, enforce range")
<< QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::TopToBottom << int(QQuickItemView::StrictlyEnforceRange)
<< QPoint(20, 200) << QPoint(20, 20) << 180.0 << 580.0 << -20.0;
QTest::newRow("vertical, bottom to top, enforce range")
<< QQuickListView::Vertical << Qt::LeftToRight << QQuickItemView::BottomToTop << int(QQuickItemView::StrictlyEnforceRange)
<< QPoint(20, 20) << QPoint(20, 200) << -420.0 << -580.0 - 240.0 << -220.0;
QTest::newRow("horizontal, left to right, enforce range")
<< QQuickListView::Horizontal << Qt::LeftToRight << QQuickItemView::TopToBottom << int(QQuickItemView::StrictlyEnforceRange)
<< QPoint(200, 20) << QPoint(20, 20) << 180.0 << 580.0 << -20.0;
QTest::newRow("horizontal, right to left, enforce range")
<< QQuickListView::Horizontal << Qt::RightToLeft << QQuickItemView::TopToBottom << int(QQuickItemView::StrictlyEnforceRange)
<< QPoint(20, 20) << QPoint(200, 20) << -420.0 << -580.0 - 240.0 << -220.0;
}
void tst_QQuickListView::snapOneItem()
{
QFETCH(QQuickListView::Orientation, orientation);
QFETCH(Qt::LayoutDirection, layoutDirection);
QFETCH(QQuickItemView::VerticalLayoutDirection, verticalLayoutDirection);
QFETCH(int, highlightRangeMode);
QFETCH(QPoint, flickStart);
QFETCH(QPoint, flickEnd);
QFETCH(qreal, snapAlignment);
QFETCH(qreal, endExtent);
QFETCH(qreal, startExtent);
QQuickView *window = getView();
QQuickViewTestUtil::moveMouseAway(window);
window->setSource(testFileUrl("snapOneItem.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
listview->setOrientation(orientation);
listview->setLayoutDirection(layoutDirection);
listview->setVerticalLayoutDirection(verticalLayoutDirection);
listview->setHighlightRangeMode(QQuickItemView::HighlightRangeMode(highlightRangeMode));
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QSignalSpy currentIndexSpy(listview, SIGNAL(currentIndexChanged()));
// confirm that a flick hits the next item boundary
flick(window, flickStart, flickEnd, 180);
QTRY_VERIFY(listview->isMoving() == false); // wait until it stops
if (orientation == QQuickListView::Vertical)
QCOMPARE(listview->contentY(), snapAlignment);
else
QCOMPARE(listview->contentX(), snapAlignment);
if (QQuickItemView::HighlightRangeMode(highlightRangeMode) == QQuickItemView::StrictlyEnforceRange) {
QCOMPARE(listview->currentIndex(), 1);
QCOMPARE(currentIndexSpy.count(), 1);
}
// flick to end
do {
flick(window, flickStart, flickEnd, 180);
QTRY_VERIFY(listview->isMoving() == false); // wait until it stops
} while (orientation == QQuickListView::Vertical
? verticalLayoutDirection == QQuickItemView::TopToBottom ? !listview->isAtYEnd() : !listview->isAtYBeginning()
: layoutDirection == Qt::LeftToRight ? !listview->isAtXEnd() : !listview->isAtXBeginning());
if (orientation == QQuickListView::Vertical)
QCOMPARE(listview->contentY(), endExtent);
else
QCOMPARE(listview->contentX(), endExtent);
if (QQuickItemView::HighlightRangeMode(highlightRangeMode) == QQuickItemView::StrictlyEnforceRange) {
QCOMPARE(listview->currentIndex(), 3);
QCOMPARE(currentIndexSpy.count(), 3);
}
// flick to start
do {
flick(window, flickEnd, flickStart, 180);
QTRY_VERIFY(listview->isMoving() == false); // wait until it stops
} while (orientation == QQuickListView::Vertical
? verticalLayoutDirection == QQuickItemView::TopToBottom ? !listview->isAtYBeginning() : !listview->isAtYEnd()
: layoutDirection == Qt::LeftToRight ? !listview->isAtXBeginning() : !listview->isAtXEnd());
if (orientation == QQuickListView::Vertical)
QCOMPARE(listview->contentY(), startExtent);
else
QCOMPARE(listview->contentX(), startExtent);
if (QQuickItemView::HighlightRangeMode(highlightRangeMode) == QQuickItemView::StrictlyEnforceRange) {
QCOMPARE(listview->currentIndex(), 0);
QCOMPARE(currentIndexSpy.count(), 6);
}
releaseView(window);
}
void tst_QQuickListView::snapOneItemCurrentIndexRemoveAnimation()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("snapOneItemCurrentIndexRemoveAnimation.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = qobject_cast<QQuickListView*>(window->rootObject());
QTRY_VERIFY(listview != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QTRY_COMPARE(listview->currentIndex(), 0);
QSignalSpy currentIndexSpy(listview, SIGNAL(currentIndexChanged()));
QMetaObject::invokeMethod(window->rootObject(), "removeItemZero");
QTRY_COMPARE(listview->property("transitionsRun").toInt(), 1);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QCOMPARE(listview->currentIndex(), 0);
QCOMPARE(currentIndexSpy.count(), 0);
}
void tst_QQuickListView::attachedProperties_QTBUG_32836()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("attachedProperties.qml"));
window->show();
qApp->processEvents();
QQuickListView *listview = qobject_cast<QQuickListView*>(window->rootObject());
QVERIFY(listview != 0);
QQuickItem *header = listview->headerItem();
QVERIFY(header);
QCOMPARE(header->width(), listview->width());
QQuickItem *footer = listview->footerItem();
QVERIFY(footer);
QCOMPARE(footer->width(), listview->width());
QQuickItem *highlight = listview->highlightItem();
QVERIFY(highlight);
QCOMPARE(highlight->width(), listview->width());
QQuickItem *currentItem = listview->currentItem();
QVERIFY(currentItem);
QCOMPARE(currentItem->width(), listview->width());
QQuickItem *sectionItem = findItem<QQuickItem>(window->rootObject(), "sectionItem");
QVERIFY(sectionItem);
QCOMPARE(sectionItem->width(), listview->width());
}
void tst_QQuickListView::unrequestedVisibility()
{
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Item" + QString::number(i), QString::number(i));
QQuickView *window = new QQuickView(0);
window->setGeometry(0,0,240,320);
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
ctxt->setContextProperty("testWrap", QVariant(false));
window->setSource(testFileUrl("unrequestedItems.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *leftview;
QTRY_VERIFY((leftview = findItem<QQuickListView>(window->rootObject(), "leftList")));
QQuickListView *rightview;
QTRY_VERIFY((rightview = findItem<QQuickListView>(window->rootObject(), "rightList")));
QQuickItem *leftContent = leftview->contentItem();
QTRY_VERIFY((leftContent = leftview->contentItem()));
QQuickItem *rightContent;
QTRY_VERIFY((rightContent = rightview->contentItem()));
rightview->setCurrentIndex(20);
QTRY_COMPARE(leftview->contentY(), 0.0);
QTRY_COMPARE(rightview->contentY(), 100.0);
const QString wrapperObjectName = QStringLiteral("wrapper");
QQuickItem *item = findItem<QQuickItem>(leftContent, wrapperObjectName, 1);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 1);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 19);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 19);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 16);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 17);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 3);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 4);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
rightview->setCurrentIndex(0);
QTRY_COMPARE(leftview->contentY(), 0.0);
QTRY_COMPARE(rightview->contentY(), 0.0);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 1);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 1);
QVERIFY(item);
QTRY_COMPARE(delegateVisible(item), true);
QVERIFY(!findItem<QQuickItem>(leftContent, wrapperObjectName, 19));
QVERIFY(!findItem<QQuickItem>(rightContent, wrapperObjectName, 19));
leftview->setCurrentIndex(20);
QTRY_COMPARE(leftview->contentY(), 100.0);
QTRY_COMPARE(rightview->contentY(), 0.0);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 1);
QVERIFY(item);
QTRY_COMPARE(delegateVisible(item), false);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 1);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 19);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 19);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 3);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 4);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 16);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 17);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
model.moveItems(19, 1, 1);
QTRY_COMPARE(QQuickItemPrivate::get(leftview)->polishScheduled, false);
QTRY_VERIFY((item = findItem<QQuickItem>(leftContent, wrapperObjectName, 1)));
QCOMPARE(delegateVisible(item), false);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 1);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 19);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 19);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 4);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 5);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 16);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 17);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
model.moveItems(3, 4, 1);
QTRY_COMPARE(QQuickItemPrivate::get(leftview)->polishScheduled, false);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 4);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 5);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 16);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 17);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
model.moveItems(4, 3, 1);
QTRY_COMPARE(QQuickItemPrivate::get(leftview)->polishScheduled, false);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 4);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 5);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 16);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 17);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
model.moveItems(16, 17, 1);
QTRY_COMPARE(QQuickItemPrivate::get(leftview)->polishScheduled, false);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 4);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 5);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 16);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 17);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
model.moveItems(17, 16, 1);
QTRY_COMPARE(QQuickItemPrivate::get(leftview)->polishScheduled, false);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 4);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
item = findItem<QQuickItem>(leftContent, wrapperObjectName, 5);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 16);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(rightContent, wrapperObjectName, 17);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
delete window;
}
void tst_QQuickListView::populateTransitions()
{
QFETCH(bool, staticallyPopulate);
QFETCH(bool, dynamicallyPopulate);
QFETCH(bool, usePopulateTransition);
QPointF transitionFrom(-50, -50);
QPointF transitionVia(100, 100);
QaimModel model_transitionFrom;
QaimModel model_transitionVia;
QaimModel model;
if (staticallyPopulate) {
for (int i = 0; i < 30; i++)
model.addItem("item" + QString::number(i), "");
}
QQuickView *window = getView();
window->rootContext()->setContextProperty("testModel", &model);
window->rootContext()->setContextProperty("testObject", new TestObject(window->rootContext()));
window->rootContext()->setContextProperty("usePopulateTransition", usePopulateTransition);
window->rootContext()->setContextProperty("dynamicallyPopulate", dynamicallyPopulate);
window->rootContext()->setContextProperty("transitionFrom", transitionFrom);
window->rootContext()->setContextProperty("transitionVia", transitionVia);
window->rootContext()->setContextProperty("model_transitionFrom", &model_transitionFrom);
window->rootContext()->setContextProperty("model_transitionVia", &model_transitionVia);
window->setSource(testFileUrl("populateTransitions.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QVERIFY(listview);
QQuickItem *contentItem = listview->contentItem();
QVERIFY(contentItem);
if (staticallyPopulate && usePopulateTransition) {
QTRY_COMPARE(listview->property("countPopulateTransitions").toInt(), 16);
QTRY_COMPARE(listview->property("countAddTransitions").toInt(), 0);
} else if (dynamicallyPopulate) {
QTRY_COMPARE(listview->property("countPopulateTransitions").toInt(), 0);
QTRY_COMPARE(listview->property("countAddTransitions").toInt(), 16);
} else {
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QCOMPARE(listview->property("countPopulateTransitions").toInt(), 0);
QCOMPARE(listview->property("countAddTransitions").toInt(), 0);
}
int itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i=0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY2(item, QTest::toString(QString("Item %1 not found").arg(i)));
QTRY_COMPARE(item->x(), 0.0);
QTRY_COMPARE(item->y(), i*20.0);
QQuickText *name = findItem<QQuickText>(contentItem, "textName", i);
QVERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(i));
}
listview->setProperty("countPopulateTransitions", 0);
listview->setProperty("countAddTransitions", 0);
// add an item and check this is done with add transition, not populate
model.insertItem(0, "another item", "");
QTRY_COMPARE(listview->property("countAddTransitions").toInt(), 1);
QTRY_COMPARE(listview->property("countPopulateTransitions").toInt(), 0);
// clear the model
window->rootContext()->setContextProperty("testModel", QVariant());
listview->forceLayout();
QTRY_COMPARE(listview->count(), 0);
QTRY_COMPARE(findItems<QQuickItem>(contentItem, "wrapper").count(), 0);
listview->setProperty("countPopulateTransitions", 0);
listview->setProperty("countAddTransitions", 0);
// set to a valid model and check populate transition is run a second time
model.clear();
for (int i = 0; i < 30; i++)
model.addItem("item" + QString::number(i), "");
window->rootContext()->setContextProperty("testModel", &model);
QTRY_COMPARE(listview->property("countPopulateTransitions").toInt(), usePopulateTransition ? 16 : 0);
QTRY_COMPARE(listview->property("countAddTransitions").toInt(), 0);
itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i=0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY2(item, QTest::toString(QString("Item %1 not found").arg(i)));
QTRY_COMPARE(item->x(), 0.0);
QTRY_COMPARE(item->y(), i*20.0);
QQuickText *name = findItem<QQuickText>(contentItem, "textName", i);
QVERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(i));
}
// reset model and check populate transition is run again
listview->setProperty("countPopulateTransitions", 0);
listview->setProperty("countAddTransitions", 0);
model.reset();
QTRY_COMPARE(listview->property("countPopulateTransitions").toInt(), usePopulateTransition ? 16 : 0);
QTRY_COMPARE(listview->property("countAddTransitions").toInt(), 0);
itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i=0; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY2(item, QTest::toString(QString("Item %1 not found").arg(i)));
QTRY_COMPARE(item->x(), 0.0);
QTRY_COMPARE(item->y(), i*20.0);
QQuickText *name = findItem<QQuickText>(contentItem, "textName", i);
QVERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(i));
}
releaseView(window);
}
void tst_QQuickListView::populateTransitions_data()
{
QTest::addColumn<bool>("staticallyPopulate");
QTest::addColumn<bool>("dynamicallyPopulate");
QTest::addColumn<bool>("usePopulateTransition");
QTest::newRow("static") << true << false << true;
QTest::newRow("static, no populate") << true << false << false;
QTest::newRow("dynamic") << false << true << true;
QTest::newRow("dynamic, no populate") << false << true << false;
QTest::newRow("empty to start with") << false << false << true;
QTest::newRow("empty to start with, no populate") << false << false << false;
}
/*
* Tests if the first visible item is not repositioned if the same item
* resized + changes position during a transition. The test does not test the
* actual position while it is transitioning (since its timing sensitive), but
* rather tests if the transition has reached its target state properly.
**/
void tst_QQuickListView::sizeTransitions()
{
QFETCH(bool, topToBottom);
QQuickView *window = getView();
QQmlContext *ctxt = window->rootContext();
QaimModel model;
ctxt->setContextProperty("testModel", &model);
ctxt->setContextProperty("topToBottom", topToBottom);
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testObject", &model);
window->setSource(testFileUrl("sizeTransitions.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// the following will start the transition
model.addItem(QLatin1String("Test"), "");
// This ensures early failure in case of failure (in which case
// transitionFinished == true and scriptActionExecuted == false)
QTRY_COMPARE(listview->property("scriptActionExecuted").toBool() ||
listview->property("transitionFinished").toBool(), true);
QCOMPARE(listview->property("scriptActionExecuted").toBool(), true);
QCOMPARE(listview->property("transitionFinished").toBool(), true);
releaseView(window);
delete testObject;
}
void tst_QQuickListView::sizeTransitions_data()
{
QTest::addColumn<bool>("topToBottom");
QTest::newRow("TopToBottom")
<< true;
QTest::newRow("LeftToRight")
<< false;
}
void tst_QQuickListView::addTransitions()
{
QFETCH(int, initialItemCount);
QFETCH(bool, shouldAnimateTargets);
QFETCH(qreal, contentY);
QFETCH(int, insertionIndex);
QFETCH(int, insertionCount);
QFETCH(ListRange, expectedDisplacedIndexes);
// added items should start here
QPointF targetItems_transitionFrom(-50, -50);
// displaced items should pass through this point
QPointF displacedItems_transitionVia(100, 100);
QaimModel model;
for (int i = 0; i < initialItemCount; i++)
model.addItem("Original item" + QString::number(i), "");
QaimModel model_targetItems_transitionFrom;
QaimModel model_displacedItems_transitionVia;
QQuickView *window = getView();
QQmlContext *ctxt = window->rootContext();
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testModel", &model);
ctxt->setContextProperty("model_targetItems_transitionFrom", &model_targetItems_transitionFrom);
ctxt->setContextProperty("model_displacedItems_transitionVia", &model_displacedItems_transitionVia);
ctxt->setContextProperty("targetItems_transitionFrom", targetItems_transitionFrom);
ctxt->setContextProperty("displacedItems_transitionVia", displacedItems_transitionVia);
ctxt->setContextProperty("testObject", testObject);
window->setSource(testFileUrl("addTransitions.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QVERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
if (contentY != 0) {
listview->setContentY(contentY);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
}
QList<QPair<QString,QString> > expectedDisplacedValues = expectedDisplacedIndexes.getModelDataValues(model);
// only target items that will become visible should be animated
QList<QPair<QString, QString> > newData;
QList<QPair<QString, QString> > expectedTargetData;
QList<int> targetIndexes;
if (shouldAnimateTargets) {
for (int i=insertionIndex; i<insertionIndex+insertionCount; i++) {
newData << qMakePair(QString("New item %1").arg(i), QString(""));
if (i >= contentY / 20 && i < (contentY + listview->height()) / 20) { // only grab visible items
expectedTargetData << newData.last();
targetIndexes << i;
}
}
QVERIFY(expectedTargetData.count() > 0);
}
// start animation
if (!newData.isEmpty()) {
model.insertItems(insertionIndex, newData);
QTRY_COMPARE(model.count(), listview->count());
listview->forceLayout();
}
QList<QQuickItem *> targetItems = findItems<QQuickItem>(contentItem, "wrapper", targetIndexes);
if (shouldAnimateTargets) {
QTRY_COMPARE(listview->property("targetTransitionsDone").toInt(), expectedTargetData.count());
QTRY_COMPARE(listview->property("displaceTransitionsDone").toInt(),
expectedDisplacedIndexes.isValid() ? expectedDisplacedIndexes.count() : 0);
// check the target and displaced items were animated
model_targetItems_transitionFrom.matchAgainst(expectedTargetData, "wasn't animated from target 'from' pos", "shouldn't have been animated from target 'from' pos");
model_displacedItems_transitionVia.matchAgainst(expectedDisplacedValues, "wasn't animated with displaced anim", "shouldn't have been animated with displaced anim");
// check attached properties
matchItemsAndIndexes(listview->property("targetTrans_items").toMap(), model, targetIndexes);
matchIndexLists(listview->property("targetTrans_targetIndexes").toList(), targetIndexes);
matchItemLists(listview->property("targetTrans_targetItems").toList(), targetItems);
if (expectedDisplacedIndexes.isValid()) {
// adjust expectedDisplacedIndexes to their final values after the move
QList<int> displacedIndexes = adjustIndexesForAddDisplaced(expectedDisplacedIndexes.indexes, insertionIndex, insertionCount);
matchItemsAndIndexes(listview->property("displacedTrans_items").toMap(), model, displacedIndexes);
matchIndexLists(listview->property("displacedTrans_targetIndexes").toList(), targetIndexes);
matchItemLists(listview->property("displacedTrans_targetItems").toList(), targetItems);
}
} else {
QTRY_COMPARE(model_targetItems_transitionFrom.count(), 0);
QTRY_COMPARE(model_displacedItems_transitionVia.count(), 0);
}
QList<QQuickItem*> items = findItems<QQuickItem>(contentItem, "wrapper");
int firstVisibleIndex = -1;
int itemCount = items.count();
for (int i=0; i<items.count(); i++) {
if (items[i]->y() >= contentY) {
QQmlExpression e(qmlContext(items[i]), items[i], "index");
firstVisibleIndex = e.evaluate().toInt();
break;
}
}
QVERIFY2(firstVisibleIndex >= 0, QTest::toString(firstVisibleIndex));
// verify all items moved to the correct final positions
for (int i=firstVisibleIndex; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY2(item, QTest::toString(QString("Item %1 not found").arg(i)));
QTRY_COMPARE(item->y(), i*20.0);
QQuickText *name = findItem<QQuickText>(contentItem, "textName", i);
QVERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(i));
}
releaseView(window);
delete testObject;
}
void tst_QQuickListView::addTransitions_data()
{
QTest::addColumn<int>("initialItemCount");
QTest::addColumn<qreal>("contentY");
QTest::addColumn<bool>("shouldAnimateTargets");
QTest::addColumn<int>("insertionIndex");
QTest::addColumn<int>("insertionCount");
QTest::addColumn<ListRange>("expectedDisplacedIndexes");
// if inserting before visible index, items should not appear or animate in, even if there are > 1 new items
QTest::newRow("insert 1, just before start")
<< 30 << 20.0 << false
<< 0 << 1 << ListRange();
QTest::newRow("insert 1, way before start")
<< 30 << 20.0 << false
<< 0 << 1 << ListRange();
QTest::newRow("insert multiple, just before start")
<< 30 << 100.0 << false
<< 0 << 3 << ListRange();
QTest::newRow("insert multiple, way before start")
<< 30 << 100.0 << false
<< 0 << 3 << ListRange();
QTest::newRow("insert 1 at start")
<< 30 << 0.0 << true
<< 0 << 1 << ListRange(0, 15);
QTest::newRow("insert multiple at start")
<< 30 << 0.0 << true
<< 0 << 3 << ListRange(0, 15);
QTest::newRow("insert 1 at start, content y not 0")
<< 30 << 40.0 << true // first visible is index 2, so translate the displaced indexes by 2
<< 2 << 1 << ListRange(0 + 2, 15 + 2);
QTest::newRow("insert multiple at start, content y not 0")
<< 30 << 40.0 << true // first visible is index 2
<< 2 << 3 << ListRange(0 + 2, 15 + 2);
QTest::newRow("insert 1 at start, to empty list")
<< 0 << 0.0 << true
<< 0 << 1 << ListRange();
QTest::newRow("insert multiple at start, to empty list")
<< 0 << 0.0 << true
<< 0 << 3 << ListRange();
QTest::newRow("insert 1 at middle")
<< 30 << 0.0 << true
<< 5 << 1 << ListRange(5, 15);
QTest::newRow("insert multiple at middle")
<< 30 << 0.0 << true
<< 5 << 3 << ListRange(5, 15);
QTest::newRow("insert 1 at bottom")
<< 30 << 0.0 << true
<< 15 << 1 << ListRange(15, 15);
QTest::newRow("insert multiple at bottom")
<< 30 << 0.0 << true
<< 15 << 3 << ListRange(15, 15);
QTest::newRow("insert 1 at bottom, content y not 0")
<< 30 << 20.0 * 3 << true
<< 15 + 3 << 1 << ListRange(15 + 3, 15 + 3);
QTest::newRow("insert multiple at bottom, content y not 0")
<< 30 << 20.0 * 3 << true
<< 15 + 3 << 3 << ListRange(15 + 3, 15 + 3);
// items added after the last visible will not be animated in, since they
// do not appear in the final view
QTest::newRow("insert 1 after end")
<< 30 << 0.0 << false
<< 17 << 1 << ListRange();
QTest::newRow("insert multiple after end")
<< 30 << 0.0 << false
<< 17 << 3 << ListRange();
}
void tst_QQuickListView::moveTransitions()
{
QFETCH(int, initialItemCount);
QFETCH(qreal, contentY);
QFETCH(qreal, itemsOffsetAfterMove);
QFETCH(int, moveFrom);
QFETCH(int, moveTo);
QFETCH(int, moveCount);
QFETCH(ListRange, expectedDisplacedIndexes);
// target and displaced items should pass through these points
QPointF targetItems_transitionVia(-50, 50);
QPointF displacedItems_transitionVia(100, 100);
QaimModel model;
for (int i = 0; i < initialItemCount; i++)
model.addItem("Original item" + QString::number(i), "");
QaimModel model_targetItems_transitionVia;
QaimModel model_displacedItems_transitionVia;
QQuickView *window = getView();
QQmlContext *ctxt = window->rootContext();
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testModel", &model);
ctxt->setContextProperty("model_targetItems_transitionVia", &model_targetItems_transitionVia);
ctxt->setContextProperty("model_displacedItems_transitionVia", &model_displacedItems_transitionVia);
ctxt->setContextProperty("targetItems_transitionVia", targetItems_transitionVia);
ctxt->setContextProperty("displacedItems_transitionVia", displacedItems_transitionVia);
ctxt->setContextProperty("testObject", testObject);
window->setSource(testFileUrl("moveTransitions.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QVERIFY(contentItem != 0);
QQuickText *name;
if (contentY != 0) {
listview->setContentY(contentY);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
}
QList<QPair<QString,QString> > expectedDisplacedValues = expectedDisplacedIndexes.getModelDataValues(model);
// Items moving to *or* from visible positions should be animated.
// Otherwise, they should not be animated.
QList<QPair<QString, QString> > expectedTargetData;
QList<int> targetIndexes;
for (int i=moveFrom; i<moveFrom+moveCount; i++) {
int toIndex = moveTo + (i - moveFrom);
if (i <= (contentY + listview->height()) / 20
|| toIndex < (contentY + listview->height()) / 20) {
expectedTargetData << qMakePair(model.name(i), model.number(i));
targetIndexes << i;
}
}
// ViewTransition.index provides the indices that items are moving to, not from
targetIndexes = adjustIndexesForMove(targetIndexes, moveFrom, moveTo, moveCount);
// start animation
model.moveItems(moveFrom, moveTo, moveCount);
QTRY_COMPARE(listview->property("targetTransitionsDone").toInt(), expectedTargetData.count());
QTRY_COMPARE(listview->property("displaceTransitionsDone").toInt(),
expectedDisplacedIndexes.isValid() ? expectedDisplacedIndexes.count() : 0);
QList<QQuickItem *> targetItems = findItems<QQuickItem>(contentItem, "wrapper", targetIndexes);
// check the target and displaced items were animated
model_targetItems_transitionVia.matchAgainst(expectedTargetData, "wasn't animated from target 'from' pos", "shouldn't have been animated from target 'from' pos");
model_displacedItems_transitionVia.matchAgainst(expectedDisplacedValues, "wasn't animated with displaced anim", "shouldn't have been animated with displaced anim");
// check attached properties
matchItemsAndIndexes(listview->property("targetTrans_items").toMap(), model, targetIndexes);
matchIndexLists(listview->property("targetTrans_targetIndexes").toList(), targetIndexes);
matchItemLists(listview->property("targetTrans_targetItems").toList(), targetItems);
if (expectedDisplacedIndexes.isValid()) {
// adjust expectedDisplacedIndexes to their final values after the move
QList<int> displacedIndexes = adjustIndexesForMove(expectedDisplacedIndexes.indexes, moveFrom, moveTo, moveCount);
matchItemsAndIndexes(listview->property("displacedTrans_items").toMap(), model, displacedIndexes);
matchIndexLists(listview->property("displacedTrans_targetIndexes").toList(), targetIndexes);
matchItemLists(listview->property("displacedTrans_targetItems").toList(), targetItems);
}
QList<QQuickItem*> items = findItems<QQuickItem>(contentItem, "wrapper");
int firstVisibleIndex = -1;
for (int i=0; i<items.count(); i++) {
if (items[i]->y() >= contentY) {
QQmlExpression e(qmlContext(items[i]), items[i], "index");
firstVisibleIndex = e.evaluate().toInt();
break;
}
}
QVERIFY2(firstVisibleIndex >= 0, QTest::toString(firstVisibleIndex));
// verify all items moved to the correct final positions
int itemCount = findItems<QQuickItem>(contentItem, "wrapper").count();
for (int i=firstVisibleIndex; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY2(item, QTest::toString(QString("Item %1 not found").arg(i)));
QTRY_COMPARE(item->y(), i*20.0 + itemsOffsetAfterMove);
name = findItem<QQuickText>(contentItem, "textName", i);
QVERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(i));
}
releaseView(window);
delete testObject;
}
void tst_QQuickListView::moveTransitions_data()
{
QTest::addColumn<int>("initialItemCount");
QTest::addColumn<qreal>("contentY");
QTest::addColumn<qreal>("itemsOffsetAfterMove");
QTest::addColumn<int>("moveFrom");
QTest::addColumn<int>("moveTo");
QTest::addColumn<int>("moveCount");
QTest::addColumn<ListRange>("expectedDisplacedIndexes");
// when removing from above the visible, all items shift down depending on how many
// items have been removed from above the visible
QTest::newRow("move from above view, outside visible items, move 1") << 30 << 4*20.0 << 20.0
<< 1 << 10 << 1 << ListRange(11, 15+4);
QTest::newRow("move from above view, outside visible items, move 1 (first item)") << 30 << 4*20.0 << 20.0
<< 0 << 10 << 1 << ListRange(11, 15+4);
QTest::newRow("move from above view, outside visible items, move multiple") << 30 << 4*20.0 << 2*20.0
<< 1 << 10 << 2 << ListRange(12, 15+4);
QTest::newRow("move from above view, outside visible items, move multiple (first item)") << 30 << 4*20.0 << 3*20.0
<< 0 << 10 << 3 << ListRange(13, 15+4);
QTest::newRow("move from above view, mix of visible/non-visible") << 30 << 4*20.0 << 3*20.0
<< 1 << 10 << 5 << ListRange(6, 14) + ListRange(15, 15+4);
QTest::newRow("move from above view, mix of visible/non-visible (move first)") << 30 << 4*20.0 << 4*20.0
<< 0 << 10 << 5 << ListRange(5, 14) + ListRange(15, 15+4);
QTest::newRow("move within view, move 1 down") << 30 << 0.0 << 0.0
<< 1 << 10 << 1 << ListRange(2, 10);
QTest::newRow("move within view, move 1 down, move first item") << 30 << 0.0 << 0.0
<< 0 << 10 << 1 << ListRange(1, 10);
QTest::newRow("move within view, move 1 down, move first item, contentY not 0") << 30 << 4*20.0 << 0.0
<< 0+4 << 10+4 << 1 << ListRange(1+4, 10+4);
QTest::newRow("move within view, move 1 down, to last item") << 30 << 0.0 << 0.0
<< 10 << 15 << 1 << ListRange(11, 15);
QTest::newRow("move within view, move first->last") << 30 << 0.0 << 0.0
<< 0 << 15 << 1 << ListRange(1, 15);
QTest::newRow("move within view, move multiple down") << 30 << 0.0 << 0.0
<< 1 << 10 << 3 << ListRange(4, 12);
QTest::newRow("move within view, move multiple down, move first item") << 30 << 0.0 << 0.0
<< 0 << 10 << 3 << ListRange(3, 12);
QTest::newRow("move within view, move multiple down, move first item, contentY not 0") << 30 << 4*20.0 << 0.0
<< 0+4 << 10+4 << 3 << ListRange(3+4, 12+4);
QTest::newRow("move within view, move multiple down, displace last item") << 30 << 0.0 << 0.0
<< 5 << 13 << 3 << ListRange(8, 15);
QTest::newRow("move within view, move multiple down, move first->last") << 30 << 0.0 << 0.0
<< 0 << 13 << 3 << ListRange(3, 15);
QTest::newRow("move within view, move 1 up") << 30 << 0.0 << 0.0
<< 10 << 1 << 1 << ListRange(1, 9);
QTest::newRow("move within view, move 1 up, move to first index") << 30 << 0.0 << 0.0
<< 10 << 0 << 1 << ListRange(0, 9);
QTest::newRow("move within view, move 1 up, move to first index, contentY not 0") << 30 << 4*20.0 << 0.0
<< 10+4 << 0+4 << 1 << ListRange(0+4, 9+4);
QTest::newRow("move within view, move 1 up, move to first index, contentY not on item border") << 30 << 4*20.0 - 10 << 0.0
<< 10+4 << 0+4 << 1 << ListRange(0+4, 9+4);
QTest::newRow("move within view, move 1 up, move last item") << 30 << 0.0 << 0.0
<< 15 << 10 << 1 << ListRange(10, 14);
QTest::newRow("move within view, move 1 up, move last->first") << 30 << 0.0 << 0.0
<< 15 << 0 << 1 << ListRange(0, 14);
QTest::newRow("move within view, move multiple up") << 30 << 0.0 << 0.0
<< 10 << 1 << 3 << ListRange(1, 9);
QTest::newRow("move within view, move multiple up, move to first index") << 30 << 0.0 << 0.0
<< 10 << 0 << 3 << ListRange(0, 9);
QTest::newRow("move within view, move multiple up, move to first index, contentY not 0") << 30 << 4*20.0 << 0.0
<< 10+4 << 0+4 << 3 << ListRange(0+4, 9+4);
QTest::newRow("move within view, move multiple up, move last item") << 30 << 0.0 << 0.0
<< 13 << 5 << 3 << ListRange(5, 12);
QTest::newRow("move within view, move multiple up, move last->first") << 30 << 0.0 << 0.0
<< 13 << 0 << 3 << ListRange(0, 12);
QTest::newRow("move from below view, move 1 up, move to top") << 30 << 0.0 << 0.0
<< 20 << 0 << 1 << ListRange(0, 15);
QTest::newRow("move from below view, move 1 up, move to top, contentY not 0") << 30 << 4*20.0 << 0.0
<< 25 << 4 << 1 << ListRange(0+4, 15+4);
QTest::newRow("move from below view, move multiple up, move to top") << 30 << 0.0 << 0.0
<< 20 << 0 << 3 << ListRange(0, 15);
QTest::newRow("move from below view, move multiple up, move to top, contentY not 0") << 30 << 4*20.0 << 0.0
<< 25 << 4 << 3 << ListRange(0+4, 15+4);
QTest::newRow("move from below view, move 1 up, move to bottom") << 30 << 0.0 << 0.0
<< 20 << 15 << 1 << ListRange(15, 15);
QTest::newRow("move from below view, move 1 up, move to bottom, contentY not 0") << 30 << 4*20.0 << 0.0
<< 25 << 15+4 << 1 << ListRange(15+4, 15+4);
QTest::newRow("move from below view, move multiple up, move to bottom") << 30 << 0.0 << 0.0
<< 20 << 15 << 3 << ListRange(15, 15);
QTest::newRow("move from below view, move multiple up, move to bottom, contentY not 0") << 30 << 4*20.0 << 0.0
<< 25 << 15+4 << 3 << ListRange(15+4, 15+4);
}
void tst_QQuickListView::removeTransitions()
{
QFETCH(int, initialItemCount);
QFETCH(bool, shouldAnimateTargets);
QFETCH(qreal, contentY);
QFETCH(int, removalIndex);
QFETCH(int, removalCount);
QFETCH(ListRange, expectedDisplacedIndexes);
// added items should end here
QPointF targetItems_transitionTo(-50, -50);
// displaced items should pass through this points
QPointF displacedItems_transitionVia(100, 100);
QaimModel model;
for (int i = 0; i < initialItemCount; i++)
model.addItem("Original item" + QString::number(i), "");
QaimModel model_targetItems_transitionTo;
QaimModel model_displacedItems_transitionVia;
QQuickView *window = getView();
QQmlContext *ctxt = window->rootContext();
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testModel", &model);
ctxt->setContextProperty("model_targetItems_transitionTo", &model_targetItems_transitionTo);
ctxt->setContextProperty("model_displacedItems_transitionVia", &model_displacedItems_transitionVia);
ctxt->setContextProperty("targetItems_transitionTo", targetItems_transitionTo);
ctxt->setContextProperty("displacedItems_transitionVia", displacedItems_transitionVia);
ctxt->setContextProperty("testObject", testObject);
window->setSource(testFileUrl("removeTransitions.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QVERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
if (contentY != 0) {
listview->setContentY(contentY);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
}
QList<QPair<QString,QString> > expectedDisplacedValues = expectedDisplacedIndexes.getModelDataValues(model);
// only target items that are visible should be animated
QList<QPair<QString, QString> > expectedTargetData;
QList<int> targetIndexes;
if (shouldAnimateTargets) {
for (int i=removalIndex; i<removalIndex+removalCount; i++) {
if (i >= contentY / 20 && i < (contentY + listview->height()) / 20) {
expectedTargetData << qMakePair(model.name(i), model.number(i));
targetIndexes << i;
}
}
QVERIFY(expectedTargetData.count() > 0);
}
// calculate targetItems and expectedTargets before model changes
QList<QQuickItem *> targetItems = findItems<QQuickItem>(contentItem, "wrapper", targetIndexes);
QVariantMap expectedTargets;
for (int i=0; i<targetIndexes.count(); i++)
expectedTargets[model.name(targetIndexes[i])] = targetIndexes[i];
// start animation
model.removeItems(removalIndex, removalCount);
QTRY_COMPARE(model.count(), listview->count());
if (shouldAnimateTargets) {
QTRY_COMPARE(listview->property("targetTransitionsDone").toInt(), expectedTargetData.count());
QTRY_COMPARE(listview->property("displaceTransitionsDone").toInt(),
expectedDisplacedIndexes.isValid() ? expectedDisplacedIndexes.count() : 0);
// check the target and displaced items were animated
model_targetItems_transitionTo.matchAgainst(expectedTargetData, "wasn't animated to target 'to' pos", "shouldn't have been animated to target 'to' pos");
model_displacedItems_transitionVia.matchAgainst(expectedDisplacedValues, "wasn't animated with displaced anim", "shouldn't have been animated with displaced anim");
// check attached properties
QCOMPARE(listview->property("targetTrans_items").toMap(), expectedTargets);
matchIndexLists(listview->property("targetTrans_targetIndexes").toList(), targetIndexes);
matchItemLists(listview->property("targetTrans_targetItems").toList(), targetItems);
if (expectedDisplacedIndexes.isValid()) {
// adjust expectedDisplacedIndexes to their final values after the move
QList<int> displacedIndexes = adjustIndexesForRemoveDisplaced(expectedDisplacedIndexes.indexes, removalIndex, removalCount);
matchItemsAndIndexes(listview->property("displacedTrans_items").toMap(), model, displacedIndexes);
matchIndexLists(listview->property("displacedTrans_targetIndexes").toList(), targetIndexes);
matchItemLists(listview->property("displacedTrans_targetItems").toList(), targetItems);
}
} else {
QTRY_COMPARE(model_targetItems_transitionTo.count(), 0);
QTRY_COMPARE(model_displacedItems_transitionVia.count(), 0);
}
QList<QQuickItem*> items = findItems<QQuickItem>(contentItem, "wrapper");
int firstVisibleIndex = -1;
int itemCount = items.count();
for (int i=0; i<items.count(); i++) {
QQmlExpression e(qmlContext(items[i]), items[i], "index");
int index = e.evaluate().toInt();
if (firstVisibleIndex < 0 && items[i]->y() >= contentY)
firstVisibleIndex = index;
if (index < 0)
itemCount--; // exclude deleted items
}
QVERIFY2(firstVisibleIndex >= 0, QTest::toString(firstVisibleIndex));
// verify all items moved to the correct final positions
for (int i=firstVisibleIndex; i < model.count() && i < itemCount; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY2(item, QTest::toString(QString("Item %1 not found").arg(i)));
QCOMPARE(item->x(), 0.0);
QCOMPARE(item->y(), contentY + (i-firstVisibleIndex) * 20.0);
QQuickText *name = findItem<QQuickText>(contentItem, "textName", i);
QVERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(i));
}
releaseView(window);
delete testObject;
}
void tst_QQuickListView::removeTransitions_data()
{
QTest::addColumn<int>("initialItemCount");
QTest::addColumn<qreal>("contentY");
QTest::addColumn<bool>("shouldAnimateTargets");
QTest::addColumn<int>("removalIndex");
QTest::addColumn<int>("removalCount");
QTest::addColumn<ListRange>("expectedDisplacedIndexes");
// All items that are visible following the remove operation should be animated.
// Remove targets that are outside of the view should not be animated.
QTest::newRow("remove 1 before start")
<< 30 << 20.0 * 3 << false
<< 2 << 1 << ListRange();
QTest::newRow("remove multiple, all before start")
<< 30 << 20.0 * 3 << false
<< 0 << 3 << ListRange();
QTest::newRow("remove mix of before and after start")
<< 30 << 20.0 * 3 << true
<< 2 << 3 << ListRange(5, 20); // 5-20 are visible after the remove
QTest::newRow("remove 1 from start")
<< 30 << 0.0 << true
<< 0 << 1 << ListRange(1, 16); // 1-16 are visible after the remove
QTest::newRow("remove multiple from start")
<< 30 << 0.0 << true
<< 0 << 3 << ListRange(3, 18); // 3-18 are visible after the remove
QTest::newRow("remove 1 from start, content y not 0")
<< 30 << 20.0 * 2 << true // first visible is index 2, so translate the displaced indexes by 2
<< 2 << 1 << ListRange(1 + 2, 16 + 2);
QTest::newRow("remove multiple from start, content y not 0")
<< 30 << 20.0 * 2 << true // first visible is index 2
<< 2 << 3 << ListRange(3 + 2, 18 + 2);
QTest::newRow("remove 1 from middle")
<< 30 << 0.0 << true
<< 5 << 1 << ListRange(6, 16);
QTest::newRow("remove multiple from middle")
<< 30 << 0.0 << true
<< 5 << 3 << ListRange(8, 18);
QTest::newRow("remove 1 from bottom")
<< 30 << 0.0 << true
<< 15 << 1 << ListRange(16, 16);
// remove 15, 16, 17
// 15 will animate as the target item, 16 & 17 won't be animated since they are outside
// the view, and 18 will be animated as the displaced item to replace the last item
QTest::newRow("remove multiple from bottom")
<< 30 << 0.0 << true
<< 15 << 3 << ListRange(18, 18);
QTest::newRow("remove 1 from bottom, content y not 0")
<< 30 << 20.0 * 2 << true
<< 15 + 2 << 1 << ListRange(16 + 2, 16 + 2);
QTest::newRow("remove multiple from bottom, content y not 0")
<< 30 << 20.0 * 2 << true
<< 15 + 2 << 3 << ListRange(18 + 2, 18 + 2);
QTest::newRow("remove 1 after end")
<< 30 << 0.0 << false
<< 17 << 1 << ListRange();
QTest::newRow("remove multiple after end")
<< 30 << 0.0 << false
<< 17 << 3 << ListRange();
}
void tst_QQuickListView::displacedTransitions()
{
QFETCH(bool, useDisplaced);
QFETCH(bool, displacedEnabled);
QFETCH(bool, useAddDisplaced);
QFETCH(bool, addDisplacedEnabled);
QFETCH(bool, useMoveDisplaced);
QFETCH(bool, moveDisplacedEnabled);
QFETCH(bool, useRemoveDisplaced);
QFETCH(bool, removeDisplacedEnabled);
QFETCH(ListChange, change);
QFETCH(ListRange, expectedDisplacedIndexes);
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Original item" + QString::number(i), "");
QaimModel model_displaced_transitionVia;
QaimModel model_addDisplaced_transitionVia;
QaimModel model_moveDisplaced_transitionVia;
QaimModel model_removeDisplaced_transitionVia;
QPointF displaced_transitionVia(-50, -100);
QPointF addDisplaced_transitionVia(-150, 100);
QPointF moveDisplaced_transitionVia(50, -100);
QPointF removeDisplaced_transitionVia(150, 100);
QQuickView *window = getView();
QQmlContext *ctxt = window->rootContext();
TestObject *testObject = new TestObject(window);
ctxt->setContextProperty("testModel", &model);
ctxt->setContextProperty("testObject", testObject);
ctxt->setContextProperty("model_displaced_transitionVia", &model_displaced_transitionVia);
ctxt->setContextProperty("model_addDisplaced_transitionVia", &model_addDisplaced_transitionVia);
ctxt->setContextProperty("model_moveDisplaced_transitionVia", &model_moveDisplaced_transitionVia);
ctxt->setContextProperty("model_removeDisplaced_transitionVia", &model_removeDisplaced_transitionVia);
ctxt->setContextProperty("displaced_transitionVia", displaced_transitionVia);
ctxt->setContextProperty("addDisplaced_transitionVia", addDisplaced_transitionVia);
ctxt->setContextProperty("moveDisplaced_transitionVia", moveDisplaced_transitionVia);
ctxt->setContextProperty("removeDisplaced_transitionVia", removeDisplaced_transitionVia);
ctxt->setContextProperty("useDisplaced", useDisplaced);
ctxt->setContextProperty("displacedEnabled", displacedEnabled);
ctxt->setContextProperty("useAddDisplaced", useAddDisplaced);
ctxt->setContextProperty("addDisplacedEnabled", addDisplacedEnabled);
ctxt->setContextProperty("useMoveDisplaced", useMoveDisplaced);
ctxt->setContextProperty("moveDisplacedEnabled", moveDisplacedEnabled);
ctxt->setContextProperty("useRemoveDisplaced", useRemoveDisplaced);
ctxt->setContextProperty("removeDisplacedEnabled", removeDisplacedEnabled);
window->setSource(testFileUrl("displacedTransitions.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QVERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QList<QPair<QString,QString> > expectedDisplacedValues = expectedDisplacedIndexes.getModelDataValues(model);
listview->setProperty("displaceTransitionsDone", false);
switch (change.type) {
case ListChange::Inserted:
{
QList<QPair<QString, QString> > targetItemData;
for (int i=change.index; i<change.index + change.count; ++i)
targetItemData << qMakePair(QString("new item %1").arg(i), QString::number(i));
model.insertItems(change.index, targetItemData);
QTRY_COMPARE(model.count(), listview->count());
break;
}
case ListChange::Removed:
model.removeItems(change.index, change.count);
QTRY_COMPARE(model.count(), listview->count());
break;
case ListChange::Moved:
model.moveItems(change.index, change.to, change.count);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
break;
case ListChange::SetCurrent:
case ListChange::SetContentY:
case ListChange::Polish:
break;
}
listview->forceLayout();
QVariantList resultTargetIndexes = listview->property("displacedTargetIndexes").toList();
QVariantList resultTargetItems = listview->property("displacedTargetItems").toList();
if ((useDisplaced && displacedEnabled)
|| (useAddDisplaced && addDisplacedEnabled)
|| (useMoveDisplaced && moveDisplacedEnabled)
|| (useRemoveDisplaced && removeDisplacedEnabled)) {
QTRY_VERIFY(listview->property("displaceTransitionsDone").toBool());
// check the correct number of target items and indexes were received
QCOMPARE(resultTargetIndexes.count(), expectedDisplacedIndexes.count());
for (int i=0; i<resultTargetIndexes.count(); i++)
QCOMPARE(resultTargetIndexes[i].value<QList<int> >().count(), change.count);
QCOMPARE(resultTargetItems.count(), expectedDisplacedIndexes.count());
for (int i=0; i<resultTargetItems.count(); i++)
QCOMPARE(resultTargetItems[i].toList().count(), change.count);
} else {
QCOMPARE(resultTargetIndexes.count(), 0);
QCOMPARE(resultTargetItems.count(), 0);
}
if (change.type == ListChange::Inserted && useAddDisplaced && addDisplacedEnabled)
model_addDisplaced_transitionVia.matchAgainst(expectedDisplacedValues, "wasn't animated with add displaced", "shouldn't have been animated with add displaced");
else
QCOMPARE(model_addDisplaced_transitionVia.count(), 0);
if (change.type == ListChange::Moved && useMoveDisplaced && moveDisplacedEnabled)
model_moveDisplaced_transitionVia.matchAgainst(expectedDisplacedValues, "wasn't animated with move displaced", "shouldn't have been animated with move displaced");
else
QCOMPARE(model_moveDisplaced_transitionVia.count(), 0);
if (change.type == ListChange::Removed && useRemoveDisplaced && removeDisplacedEnabled)
model_removeDisplaced_transitionVia.matchAgainst(expectedDisplacedValues, "wasn't animated with remove displaced", "shouldn't have been animated with remove displaced");
else
QCOMPARE(model_removeDisplaced_transitionVia.count(), 0);
if (useDisplaced && displacedEnabled
&& ( (change.type == ListChange::Inserted && (!useAddDisplaced || !addDisplacedEnabled))
|| (change.type == ListChange::Moved && (!useMoveDisplaced || !moveDisplacedEnabled))
|| (change.type == ListChange::Removed && (!useRemoveDisplaced || !removeDisplacedEnabled))) ) {
model_displaced_transitionVia.matchAgainst(expectedDisplacedValues, "wasn't animated with generic displaced", "shouldn't have been animated with generic displaced");
} else {
QCOMPARE(model_displaced_transitionVia.count(), 0);
}
// verify all items moved to the correct final positions
QList<QQuickItem*> items = findItems<QQuickItem>(contentItem, "wrapper");
for (int i=0; i < model.count() && i < items.count(); ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY2(item, QTest::toString(QString("Item %1 not found").arg(i)));
QCOMPARE(item->x(), 0.0);
QCOMPARE(item->y(), i * 20.0);
QQuickText *name = findItem<QQuickText>(contentItem, "textName", i);
QVERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(i));
}
releaseView(window);
}
void tst_QQuickListView::displacedTransitions_data()
{
QTest::addColumn<bool>("useDisplaced");
QTest::addColumn<bool>("displacedEnabled");
QTest::addColumn<bool>("useAddDisplaced");
QTest::addColumn<bool>("addDisplacedEnabled");
QTest::addColumn<bool>("useMoveDisplaced");
QTest::addColumn<bool>("moveDisplacedEnabled");
QTest::addColumn<bool>("useRemoveDisplaced");
QTest::addColumn<bool>("removeDisplacedEnabled");
QTest::addColumn<ListChange>("change");
QTest::addColumn<ListRange>("expectedDisplacedIndexes");
QTest::newRow("no displaced transitions at all")
<< false << false
<< false << false
<< false << false
<< false << false
<< ListChange::insert(0, 1) << ListRange(0, 15);
QTest::newRow("just displaced")
<< true << true
<< false << false
<< false << false
<< false << false
<< ListChange::insert(0, 1) << ListRange(0, 15);
QTest::newRow("just displaced (not enabled)")
<< true << false
<< false << false
<< false << false
<< false << false
<< ListChange::insert(0, 1) << ListRange(0, 15);
QTest::newRow("displaced + addDisplaced")
<< true << true
<< true << true
<< false << false
<< false << false
<< ListChange::insert(0, 1) << ListRange(0, 15);
QTest::newRow("displaced + addDisplaced (not enabled)")
<< true << true
<< true << false
<< false << false
<< false << false
<< ListChange::insert(0, 1) << ListRange(0, 15);
QTest::newRow("displaced + moveDisplaced")
<< true << true
<< false << false
<< true << true
<< false << false
<< ListChange::move(0, 10, 1) << ListRange(1, 10);
QTest::newRow("displaced + moveDisplaced (not enabled)")
<< true << true
<< false << false
<< true << false
<< false << false
<< ListChange::move(0, 10, 1) << ListRange(1, 10);
QTest::newRow("displaced + removeDisplaced")
<< true << true
<< false << false
<< false << false
<< true << true
<< ListChange::remove(0, 1) << ListRange(1, 16);
QTest::newRow("displaced + removeDisplaced (not enabled)")
<< true << true
<< false << false
<< false << false
<< true << false
<< ListChange::remove(0, 1) << ListRange(1, 16);
QTest::newRow("displaced + add, should use generic displaced for a remove")
<< true << true
<< true << true
<< false << false
<< true << false
<< ListChange::remove(0, 1) << ListRange(1, 16);
}
void tst_QQuickListView::multipleTransitions()
{
// Tests that if you interrupt a transition in progress with another action that
// cancels the previous transition, the resulting items are still placed correctly.
QFETCH(int, initialCount);
QFETCH(qreal, contentY);
QFETCH(QList<ListChange>, changes);
QFETCH(bool, enableAddTransitions);
QFETCH(bool, enableMoveTransitions);
QFETCH(bool, enableRemoveTransitions);
QFETCH(bool, rippleAddDisplaced);
QPointF addTargets_transitionFrom(-50, -50);
QPointF addDisplaced_transitionFrom(-50, 50);
QPointF moveTargets_transitionFrom(50, -50);
QPointF moveDisplaced_transitionFrom(50, 50);
QPointF removeTargets_transitionTo(-100, 300);
QPointF removeDisplaced_transitionFrom(100, 300);
QaimModel model;
for (int i = 0; i < initialCount; i++)
model.addItem("Original item" + QString::number(i), "");
QQuickView *window = getView();
QQmlContext *ctxt = window->rootContext();
TestObject *testObject = new TestObject;
ctxt->setContextProperty("testModel", &model);
ctxt->setContextProperty("testObject", testObject);
ctxt->setContextProperty("addTargets_transitionFrom", addTargets_transitionFrom);
ctxt->setContextProperty("addDisplaced_transitionFrom", addDisplaced_transitionFrom);
ctxt->setContextProperty("moveTargets_transitionFrom", moveTargets_transitionFrom);
ctxt->setContextProperty("moveDisplaced_transitionFrom", moveDisplaced_transitionFrom);
ctxt->setContextProperty("removeTargets_transitionTo", removeTargets_transitionTo);
ctxt->setContextProperty("removeDisplaced_transitionFrom", removeDisplaced_transitionFrom);
ctxt->setContextProperty("enableAddTransitions", enableAddTransitions);
ctxt->setContextProperty("enableMoveTransitions", enableMoveTransitions);
ctxt->setContextProperty("enableRemoveTransitions", enableRemoveTransitions);
ctxt->setContextProperty("rippleAddDisplaced", rippleAddDisplaced);
window->setSource(testFileUrl("multipleTransitions.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QVERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
if (contentY != 0) {
listview->setContentY(contentY);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
}
int timeBetweenActions = window->rootObject()->property("timeBetweenActions").toInt();
for (int i=0; i<changes.count(); i++) {
switch (changes[i].type) {
case ListChange::Inserted:
{
QList<QPair<QString, QString> > targetItems;
for (int j=changes[i].index; j<changes[i].index + changes[i].count; ++j)
targetItems << qMakePair(QString("new item %1").arg(j), QString::number(j));
model.insertItems(changes[i].index, targetItems);
QTRY_COMPARE(model.count(), listview->count());
if (i == changes.count() - 1) {
QTRY_VERIFY(!listview->property("runningAddTargets").toBool());
QTRY_VERIFY(!listview->property("runningAddDisplaced").toBool());
} else {
QTest::qWait(timeBetweenActions);
}
break;
}
case ListChange::Removed:
model.removeItems(changes[i].index, changes[i].count);
QTRY_COMPARE(model.count(), listview->count());
if (i == changes.count() - 1) {
QTRY_VERIFY(!listview->property("runningRemoveTargets").toBool());
QTRY_VERIFY(!listview->property("runningRemoveDisplaced").toBool());
} else {
QTest::qWait(timeBetweenActions);
}
break;
case ListChange::Moved:
model.moveItems(changes[i].index, changes[i].to, changes[i].count);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
if (i == changes.count() - 1) {
QTRY_VERIFY(!listview->property("runningMoveTargets").toBool());
QTRY_VERIFY(!listview->property("runningMoveDisplaced").toBool());
} else {
QTest::qWait(timeBetweenActions);
}
break;
case ListChange::SetCurrent:
listview->setCurrentIndex(changes[i].index);
break;
case ListChange::SetContentY:
listview->setContentY(changes[i].pos);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
break;
case ListChange::Polish:
break;
}
}
listview->forceLayout();
QTest::qWait(200);
QCOMPARE(listview->count(), model.count());
// verify all items moved to the correct final positions
QList<QQuickItem*> items = findItems<QQuickItem>(contentItem, "wrapper");
for (int i=0; i < model.count() && i < items.count(); ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY2(item, QTest::toString(QString("Item %1 not found").arg(i)));
QTRY_COMPARE(item->x(), 0.0);
QTRY_COMPARE(item->y(), i*20.0);
QQuickText *name = findItem<QQuickText>(contentItem, "textName", i);
QVERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(i));
}
releaseView(window);
delete testObject;
}
void tst_QQuickListView::multipleTransitions_data()
{
QTest::addColumn<int>("initialCount");
QTest::addColumn<qreal>("contentY");
QTest::addColumn<QList<ListChange> >("changes");
QTest::addColumn<bool>("enableAddTransitions");
QTest::addColumn<bool>("enableMoveTransitions");
QTest::addColumn<bool>("enableRemoveTransitions");
QTest::addColumn<bool>("rippleAddDisplaced");
// the added item and displaced items should move to final dest correctly
QTest::newRow("add item, then move it immediately") << 10 << 0.0 << (QList<ListChange>()
<< ListChange::insert(0, 1)
<< ListChange::move(0, 3, 1)
)
<< true << true << true << false;
// items affected by the add should change from move to add transition
QTest::newRow("move, then insert item before the moved item") << 20 << 0.0 << (QList<ListChange>()
<< ListChange::move(1, 10, 3)
<< ListChange::insert(0, 1)
)
<< true << true << true << false;
// items should be placed correctly if you trigger a transition then refill for that index
QTest::newRow("add at 0, flick down, flick back to top and add at 0 again") << 20 << 0.0 << (QList<ListChange>()
<< ListChange::insert(0, 1)
<< ListChange::setContentY(80.0)
<< ListChange::setContentY(0.0)
<< ListChange::insert(0, 1)
)
<< true << true << true << false;
QTest::newRow("insert then remove same index, with ripple effect on add displaced") << 20 << 0.0 << (QList<ListChange>()
<< ListChange::insert(1, 1)
<< ListChange::remove(1, 1)
)
<< true << true << true << true;
// if item is removed while undergoing a displaced transition, all other items should end up at their correct positions,
// even if a remove-displace transition is not present to re-animate them
QTest::newRow("insert then remove, with remove disabled") << 20 << 0.0 << (QList<ListChange>()
<< ListChange::insert(0, 1)
<< ListChange::remove(2, 1)
)
<< true << true << false << false;
// if last item is not flush with the edge of the view, it should still be refilled in correctly after a
// remove has changed the position of where it will move to
QTest::newRow("insert twice then remove, with remove disabled") << 20 << 0.0 << (QList<ListChange>()
<< ListChange::setContentY(-10.0)
<< ListChange::insert(0, 1)
<< ListChange::insert(0, 1)
<< ListChange::remove(2, 1)
)
<< true << true << false << false;
}
void tst_QQuickListView::multipleDisplaced()
{
// multiple move() operations should only restart displace transitions for items that
// moved from previously set positions, and not those that have moved from their current
// item positions (which may e.g. still be changing from easing bounces in the last transition)
QaimModel model;
for (int i = 0; i < 30; i++)
model.addItem("Original item" + QString::number(i), "");
QQuickView *window = getView();
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
ctxt->setContextProperty("testObject", new TestObject(window));
window->setSource(testFileUrl("multipleDisplaced.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QVERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
model.moveItems(12, 8, 1);
QTest::qWait(window->rootObject()->property("duration").toInt() / 2);
model.moveItems(8, 3, 1);
QTRY_VERIFY(listview->property("displaceTransitionsDone").toBool());
QVariantMap transitionsStarted = listview->property("displaceTransitionsStarted").toMap();
foreach (const QString &name, transitionsStarted.keys()) {
QVERIFY2(transitionsStarted[name] == 1,
QTest::toString(QString("%1 was displaced %2 times").arg(name).arg(transitionsStarted[name].toInt())));
}
// verify all items moved to the correct final positions
QList<QQuickItem*> items = findItems<QQuickItem>(contentItem, "wrapper");
for (int i=0; i < model.count() && i < items.count(); ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
QVERIFY2(item, QTest::toString(QString("Item %1 not found").arg(i)));
QTRY_COMPARE(item->x(), 0.0);
QTRY_COMPARE(item->y(), i*20.0);
QQuickText *name = findItem<QQuickText>(contentItem, "textName", i);
QVERIFY(name != 0);
QTRY_COMPARE(name->text(), model.name(i));
}
releaseView(window);
}
QList<int> tst_QQuickListView::toIntList(const QVariantList &list)
{
QList<int> ret;
bool ok = true;
for (int i=0; i<list.count(); i++) {
ret << list[i].toInt(&ok);
if (!ok)
qWarning() << "tst_QQuickListView::toIntList(): not a number:" << list[i];
}
return ret;
}
void tst_QQuickListView::matchIndexLists(const QVariantList &indexLists, const QList<int> &expectedIndexes)
{
for (int i=0; i<indexLists.count(); i++) {
QSet<int> current = indexLists[i].value<QList<int> >().toSet();
if (current != expectedIndexes.toSet())
qDebug() << "Cannot match actual targets" << current << "with expected" << expectedIndexes;
QCOMPARE(current, expectedIndexes.toSet());
}
}
void tst_QQuickListView::matchItemsAndIndexes(const QVariantMap &items, const QaimModel &model, const QList<int> &expectedIndexes)
{
for (QVariantMap::const_iterator it = items.begin(); it != items.end(); ++it) {
QCOMPARE(it.value().type(), QVariant::Int);
QString name = it.key();
int itemIndex = it.value().toInt();
QVERIFY2(expectedIndexes.contains(itemIndex), QTest::toString(QString("Index %1 not found in expectedIndexes").arg(itemIndex)));
if (model.name(itemIndex) != name)
qDebug() << itemIndex;
QCOMPARE(model.name(itemIndex), name);
}
QCOMPARE(items.count(), expectedIndexes.count());
}
void tst_QQuickListView::matchItemLists(const QVariantList &itemLists, const QList<QQuickItem *> &expectedItems)
{
for (int i=0; i<itemLists.count(); i++) {
QCOMPARE(itemLists[i].type(), QVariant::List);
QVariantList current = itemLists[i].toList();
for (int j=0; j<current.count(); j++) {
QQuickItem *o = qobject_cast<QQuickItem*>(current[j].value<QObject*>());
QVERIFY2(o, QTest::toString(QString("Invalid actual item at %1").arg(j)));
QVERIFY2(expectedItems.contains(o), QTest::toString(QString("Cannot match item %1").arg(j)));
}
QCOMPARE(current.count(), expectedItems.count());
}
}
void tst_QQuickListView::flickBeyondBounds()
{
QScopedPointer<QQuickView> window(createView());
QQuickViewTestUtil::moveMouseAway(window.data());
window->setSource(testFileUrl("flickBeyondBoundsBug.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QTRY_VERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
// Flick view up beyond bounds
flick(window.data(), QPoint(10, 10), QPoint(10, -2000), 180);
#ifdef Q_OS_MAC
QSKIP("Disabled due to flaky behavior on CI system (QTBUG-44493)");
QTRY_COMPARE(findItems<QQuickItem>(contentItem, "wrapper").count(), 0);
#endif
// We're really testing that we don't get stuck in a loop,
// but also confirm items positioned correctly.
QTRY_COMPARE(findItems<QQuickItem>(contentItem, "wrapper").count(), 2);
for (int i = 0; i < 2; ++i) {
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", i);
if (!item) qWarning() << "Item" << i << "not found";
QTRY_VERIFY(item);
QTRY_COMPARE(item->y(), qreal(i*45));
}
}
void tst_QQuickListView::flickBothDirections()
{
QFETCH(bool, initValues);
QFETCH(QQuickListView::Orientation, orientation);
QFETCH(QQuickFlickable::FlickableDirection, flickableDirection);
QFETCH(qreal, contentWidth);
QFETCH(qreal, contentHeight);
QFETCH(QPointF, targetPos);
QQuickView *window = getView();
QQuickViewTestUtil::moveMouseAway(window);
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("initialOrientation", initValues ? orientation : QQuickListView::Vertical);
ctxt->setContextProperty("initialFlickableDirection", initValues ? flickableDirection : QQuickFlickable::VerticalFlick);
ctxt->setContextProperty("initialContentWidth", initValues ? contentWidth : -1);
ctxt->setContextProperty("initialContentHeight", initValues ? contentHeight : -1);
window->setSource(testFileUrl("flickBothDirections.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowActive(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QVERIFY(listview);
if (!initValues) {
listview->setOrientation(orientation);
listview->setFlickableDirection(flickableDirection);
if (contentWidth > 0)
listview->setContentWidth(contentWidth);
if (contentHeight > 0)
listview->setContentHeight(contentHeight);
}
flick(window, QPoint(100, 100), QPoint(25, 25), 50);
QVERIFY(listview->isMoving());
QTRY_VERIFY(!listview->isMoving());
QCOMPARE(listview->contentX(), targetPos.x());
QCOMPARE(listview->contentY(), targetPos.y());
}
void tst_QQuickListView::flickBothDirections_data()
{
QTest::addColumn<bool>("initValues");
QTest::addColumn<QQuickListView::Orientation>("orientation");
QTest::addColumn<QQuickFlickable::FlickableDirection>("flickableDirection");
QTest::addColumn<qreal>("contentWidth");
QTest::addColumn<qreal>("contentHeight");
QTest::addColumn<QPointF>("targetPos");
// model: 20
// listview: 100x100
// vertical delegate: 120x20 -> contentHeight: 20x20=400
// horizontal delegate: 10x110 -> contentWidth: 20x10=200
QTest::newRow("init:vertical,-1") << true << QQuickListView::Vertical << QQuickFlickable::VerticalFlick << -1. << -1. << QPointF(0, 300);
QTest::newRow("init:vertical,120") << true << QQuickListView::Vertical << QQuickFlickable::VerticalFlick<< 120. << -1. << QPointF(0, 300);
QTest::newRow("init:vertical,auto,-1") << true << QQuickListView::Vertical << QQuickFlickable::AutoFlickDirection << -1. << -1. << QPointF(0, 300);
QTest::newRow("init:vertical,auto,120") << true << QQuickListView::Vertical << QQuickFlickable::AutoFlickDirection << 120. << -1. << QPointF(20, 300);
QTest::newRow("completed:vertical,-1") << false << QQuickListView::Vertical << QQuickFlickable::VerticalFlick << -1. << -1. << QPointF(0, 300);
QTest::newRow("completed:vertical,120") << false << QQuickListView::Vertical << QQuickFlickable::VerticalFlick << 120. << -1. << QPointF(0, 300);
QTest::newRow("completed:vertical,auto,-1") << false << QQuickListView::Vertical << QQuickListView::AutoFlickDirection << -1. << -1. << QPointF(0, 300);
QTest::newRow("completed:vertical,auto,120") << false << QQuickListView::Vertical << QQuickListView::AutoFlickDirection << 120. << -1. << QPointF(20, 300);
QTest::newRow("init:horizontal,-1") << true << QQuickListView::Horizontal << QQuickFlickable::HorizontalFlick << -1. << -1. << QPointF(100, 0);
QTest::newRow("init:horizontal,110") << true << QQuickListView::Horizontal << QQuickFlickable::HorizontalFlick <<-1. << 110. << QPointF(100, 0);
QTest::newRow("init:horizontal,auto,-1") << true << QQuickListView::Horizontal << QQuickListView::AutoFlickDirection << -1. << -1. << QPointF(100, 0);
QTest::newRow("init:horizontal,auto,110") << true << QQuickListView::Horizontal << QQuickListView::AutoFlickDirection << -1. << 110. << QPointF(100, 10);
QTest::newRow("completed:horizontal,-1") << false << QQuickListView::Horizontal << QQuickFlickable::HorizontalFlick << -1. << -1. << QPointF(100, 0);
QTest::newRow("completed:horizontal,110") << false << QQuickListView::Horizontal << QQuickFlickable::HorizontalFlick << -1. << 110. << QPointF(100, 0);
QTest::newRow("completed:horizontal,auto,-1") << false << QQuickListView::Horizontal << QQuickListView::AutoFlickDirection << -1. << -1. << QPointF(100, 0);
QTest::newRow("completed:horizontal,auto,110") << false << QQuickListView::Horizontal << QQuickListView::AutoFlickDirection << -1. << 110. << QPointF(100, 10);
}
void tst_QQuickListView::destroyItemOnCreation()
{
QaimModel model;
QScopedPointer<QQuickView> window(createView());
window->rootContext()->setContextProperty("testModel", &model);
window->setSource(testFileUrl("destroyItemOnCreation.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QVERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QVERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QCOMPARE(window->rootObject()->property("createdIndex").toInt(), -1);
model.addItem("new item", "");
QTRY_COMPARE(window->rootObject()->property("createdIndex").toInt(), 0);
QTRY_COMPARE(findItems<QQuickItem>(contentItem, "wrapper").count(), 0);
QCOMPARE(model.count(), 0);
}
void tst_QQuickListView::parentBinding()
{
QScopedPointer<QQuickView> window(createView());
QQmlTestMessageHandler messageHandler;
window->setSource(testFileUrl("parentBinding.qml"));
window->show();
QTest::qWaitForWindowExposed(window.data());
QQuickListView *listview = qobject_cast<QQuickListView*>(window->rootObject());
QVERIFY(listview != 0);
QQuickItem *contentItem = listview->contentItem();
QVERIFY(contentItem != 0);
QTRY_COMPARE(QQuickItemPrivate::get(listview)->polishScheduled, false);
QQuickItem *item = findItem<QQuickItem>(contentItem, "wrapper", 0);
QVERIFY(item);
QCOMPARE(item->width(), listview->width());
QCOMPARE(item->height(), listview->height()/12);
// there should be no transient binding error
QVERIFY2(messageHandler.messages().isEmpty(), qPrintable(messageHandler.messageString()));
}
void tst_QQuickListView::defaultHighlightMoveDuration()
{
QQmlEngine engine;
QQmlComponent component(&engine);
component.setData("import QtQuick 2.0; ListView {}", QUrl::fromLocalFile(""));
QObject *obj = component.create();
QVERIFY(obj);
QCOMPARE(obj->property("highlightMoveDuration").toInt(), -1);
}
void tst_QQuickListView::accessEmptyCurrentItem_QTBUG_30227()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("emptymodel.qml"));
QQuickListView *listview = window->rootObject()->findChild<QQuickListView*>();
QTRY_VERIFY(listview != 0);
listview->forceLayout();
QMetaObject::invokeMethod(window->rootObject(), "remove");
QVERIFY(window->rootObject()->property("isCurrentItemNull").toBool());
QMetaObject::invokeMethod(window->rootObject(), "add");
QVERIFY(!window->rootObject()->property("isCurrentItemNull").toBool());
}
void tst_QQuickListView::delayedChanges_QTBUG_30555()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("delayedChanges.qml"));
QQuickListView *listview = window->rootObject()->findChild<QQuickListView*>();
QTRY_VERIFY(listview != 0);
QCOMPARE(listview->count(), 10);
//Takes two just like in the bug report
QMetaObject::invokeMethod(window->rootObject(), "takeTwo");
QTRY_COMPARE(listview->count(), 8);
QMetaObject::invokeMethod(window->rootObject(), "takeTwo_sync");
QCOMPARE(listview->count(), 6);
}
void tst_QQuickListView::outsideViewportChangeNotAffectingView()
{
QScopedPointer<QQuickView> window(createView());
QQuickViewTestUtil::moveMouseAway(window.data());
window->setSource(testFileUrl("outsideViewportChangeNotAffectingView.qml"));
QQuickListView *listview = window->rootObject()->findChild<QQuickListView*>();
QTRY_VERIFY(listview != 0);
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
listview->setContentY(1250);
QTRY_COMPARE(listview->indexAt(0, listview->contentY()), 4);
QTRY_COMPARE(listview->itemAt(0, listview->contentY())->y(), 1200.);
QMetaObject::invokeMethod(window->rootObject(), "resizeThirdItem", Q_ARG(QVariant, 290));
QTRY_COMPARE(listview->indexAt(0, listview->contentY()), 4);
QTRY_COMPARE(listview->itemAt(0, listview->contentY())->y(), 1200.);
QMetaObject::invokeMethod(window->rootObject(), "resizeThirdItem", Q_ARG(QVariant, 300));
QTRY_COMPARE(listview->indexAt(0, listview->contentY()), 4);
QTRY_COMPARE(listview->itemAt(0, listview->contentY())->y(), 1200.);
QMetaObject::invokeMethod(window->rootObject(), "resizeThirdItem", Q_ARG(QVariant, 310));
QTRY_COMPARE(listview->indexAt(0, listview->contentY()), 4);
QTRY_COMPARE(listview->itemAt(0, listview->contentY())->y(), 1200.);
QMetaObject::invokeMethod(window->rootObject(), "resizeThirdItem", Q_ARG(QVariant, 400));
QTRY_COMPARE(listview->indexAt(0, listview->contentY()), 4);
QTRY_COMPARE(listview->itemAt(0, listview->contentY())->y(), 1200.);
}
void tst_QQuickListView::testProxyModelChangedAfterMove()
{
QScopedPointer<QQuickView> window(createView());
QQuickViewTestUtil::moveMouseAway(window.data());
window->setSource(testFileUrl("proxytest.qml"));
QQuickListView *listview = window->rootObject()->findChild<QQuickListView*>();
QTRY_VERIFY(listview != 0);
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QTRY_COMPARE(listview->count(), 3);
}
void tst_QQuickListView::typedModel()
{
QQmlEngine engine;
QQmlComponent component(&engine, testFileUrl("typedModel.qml"));
QScopedPointer<QObject> object(component.create());
QQuickListView *listview = qobject_cast<QQuickListView *>(object.data());
QVERIFY(listview);
QCOMPARE(listview->count(), 6);
QQmlListModel *listModel = 0;
listview->setModel(QVariant::fromValue(listModel));
QCOMPARE(listview->count(), 0);
}
void tst_QQuickListView::displayMargin()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("displayMargin.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = window->rootObject()->findChild<QQuickListView*>();
QVERIFY(listview != 0);
QQuickItem *content = listview->contentItem();
QVERIFY(content != 0);
QQuickItem *item0 = findItem<QQuickItem>(content, "delegate", 0);
QVERIFY(item0);
QCOMPARE(delegateVisible(item0), true);
// the 14th item should be within the end margin
QQuickItem *item14 = findItem<QQuickItem>(content, "delegate", 13);
QVERIFY(item14);
QCOMPARE(delegateVisible(item14), true);
// the 15th item should be outside the end margin
QVERIFY(findItem<QQuickItem>(content, "delegate", 14) == 0);
// the first delegate should still be within the begin margin
listview->positionViewAtIndex(3, QQuickListView::Beginning);
QCOMPARE(delegateVisible(item0), true);
// the first delegate should now be outside the begin margin
listview->positionViewAtIndex(4, QQuickListView::Beginning);
QCOMPARE(delegateVisible(item0), false);
}
void tst_QQuickListView::negativeDisplayMargin()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("negativeDisplayMargin.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickItem *listview = window->rootObject();
QQuickListView *innerList = findItem<QQuickListView>(window->rootObject(), "innerList");
QVERIFY(innerList != 0);
QTRY_COMPARE(innerList->property("createdItems").toInt(), 11);
QCOMPARE(innerList->property("destroyedItem").toInt(), 0);
QQuickItem *content = innerList->contentItem();
QVERIFY(content != 0);
QQuickItem *item = findItem<QQuickItem>(content, "delegate", 0);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(content, "delegate", 7);
QVERIFY(item);
QCOMPARE(delegateVisible(item), true);
item = findItem<QQuickItem>(content, "delegate", 8);
QVERIFY(item);
QCOMPARE(delegateVisible(item), false);
// Flick until contentY means that delegate8 should be visible
listview->setProperty("contentY", 500);
item = findItem<QQuickItem>(content, "delegate", 8);
QVERIFY(item);
QTRY_COMPARE(delegateVisible(item), true);
listview->setProperty("contentY", 1000);
QTRY_VERIFY((item = findItem<QQuickItem>(content, "delegate", 14)));
QTRY_COMPARE(delegateVisible(item), true);
listview->setProperty("contentY", 0);
QTRY_VERIFY(item = findItem<QQuickItem>(content, "delegate", 4));
QTRY_COMPARE(delegateVisible(item), true);
}
void tst_QQuickListView::highlightItemGeometryChanges()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("HighlightResize.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = qobject_cast<QQuickListView *>(window->rootObject());
QVERIFY(listview);
QCOMPARE(listview->count(), 5);
for (int i = 0; i < listview->count(); ++i) {
listview->setCurrentIndex(i);
QTRY_COMPARE(listview->highlightItem()->width(), qreal(100 + i * 20));
QTRY_COMPARE(listview->highlightItem()->height(), qreal(100 + i * 10));
}
}
void tst_QQuickListView::QTBUG_36481()
{
QQmlEngine engine;
QQmlComponent component(&engine, testFileUrl("headerCrash.qml"));
// just testing that we don't crash when creating
QScopedPointer<QObject> object(component.create());
}
void tst_QQuickListView::QTBUG_35920()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("qtbug35920.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = qobject_cast<QQuickListView *>(window->rootObject());
QVERIFY(listview);
QTest::mousePress(window.data(), Qt::LeftButton, 0, QPoint(10,0));
for (int i = 0; i < 100; ++i) {
QTest::mouseMove(window.data(), QPoint(10,i));
if (listview->isMoving()) {
// do not fixup() the position while in movement to avoid flicker
const qreal contentY = listview->contentY();
listview->setPreferredHighlightBegin(i);
QCOMPARE(listview->contentY(), contentY);
listview->resetPreferredHighlightBegin();
QCOMPARE(listview->contentY(), contentY);
listview->setPreferredHighlightEnd(i+10);
QCOMPARE(listview->contentY(), contentY);
listview->resetPreferredHighlightEnd();
QCOMPARE(listview->contentY(), contentY);
}
}
QTest::mouseRelease(window.data(), Qt::LeftButton, 0, QPoint(10,100));
}
Q_DECLARE_METATYPE(Qt::Orientation)
void tst_QQuickListView::stickyPositioning()
{
QFETCH(QString, fileName);
QFETCH(Qt::Orientation, orientation);
QFETCH(Qt::LayoutDirection, layoutDirection);
QFETCH(QQuickItemView::VerticalLayoutDirection, verticalLayoutDirection);
QFETCH(int, positionIndex);
QFETCH(QQuickItemView::PositionMode, positionMode);
QFETCH(QList<QPointF>, movement);
QFETCH(QPointF, headerPos);
QFETCH(QPointF, footerPos);
QQuickView *window = getView();
QaimModel model;
for (int i = 0; i < 20; i++)
model.addItem(QString::number(i), QString::number(i/10));
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
ctxt->setContextProperty("testOrientation", orientation);
ctxt->setContextProperty("testLayoutDirection", layoutDirection);
ctxt->setContextProperty("testVerticalLayoutDirection", verticalLayoutDirection);
window->setSource(testFileUrl(fileName));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QVERIFY(listview);
QQuickItem *contentItem = listview->contentItem();
QVERIFY(contentItem);
listview->positionViewAtIndex(positionIndex, positionMode);
foreach (const QPointF &offset, movement) {
listview->setContentX(listview->contentX() + offset.x());
listview->setContentY(listview->contentY() + offset.y());
}
if (listview->header()) {
QQuickItem *headerItem = listview->headerItem();
QVERIFY(headerItem);
QPointF actualPos = listview->mapFromItem(contentItem, headerItem->position());
QCOMPARE(actualPos, headerPos);
}
if (listview->footer()) {
QQuickItem *footerItem = listview->footerItem();
QVERIFY(footerItem);
QPointF actualPos = listview->mapFromItem(contentItem, footerItem->position());
QCOMPARE(actualPos, footerPos);
}
releaseView(window);
}
void tst_QQuickListView::stickyPositioning_data()
{
qRegisterMetaType<Qt::Orientation>();
qRegisterMetaType<Qt::LayoutDirection>();
qRegisterMetaType<QQuickItemView::VerticalLayoutDirection>();
qRegisterMetaType<QQuickItemView::PositionMode>();
QTest::addColumn<QString>("fileName");
QTest::addColumn<Qt::Orientation>("orientation");
QTest::addColumn<Qt::LayoutDirection>("layoutDirection");
QTest::addColumn<QQuickItemView::VerticalLayoutDirection>("verticalLayoutDirection");
QTest::addColumn<int>("positionIndex");
QTest::addColumn<QQuickItemView::PositionMode>("positionMode");
QTest::addColumn<QList<QPointF> >("movement");
QTest::addColumn<QPointF>("headerPos");
QTest::addColumn<QPointF>("footerPos");
// header at the top
QTest::newRow("top header") << "stickyPositioning-header.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 0 << QQuickItemView::Beginning << QList<QPointF>()
<< QPointF(0,0) << QPointF();
QTest::newRow("top header: 1/2 up") << "stickyPositioning-header.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 1 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(0,-5))
<< QPointF(0,-5) << QPointF();
QTest::newRow("top header: up") << "stickyPositioning-header.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 2 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(0,-15))
<< QPointF(0,0) << QPointF();
QTest::newRow("top header: 1/2 down") << "stickyPositioning-header.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 3 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(0,-15) << QPointF(0,5))
<< QPointF(0,-5) << QPointF();
QTest::newRow("top header: down") << "stickyPositioning-header.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 4 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(0,-15) << QPointF(0,10))
<< QPointF(0,-10) << QPointF();
// footer at the top
QTest::newRow("top footer") << "stickyPositioning-footer.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::BottomToTop
<< 19 << QQuickItemView::End << QList<QPointF>()
<< QPointF() << QPointF(0,0);
QTest::newRow("top footer: 1/2 up") << "stickyPositioning-footer.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::BottomToTop
<< 18 << QQuickItemView::End << (QList<QPointF>() << QPointF(0,-5))
<< QPointF() << QPointF(0,-5);
QTest::newRow("top footer: up") << "stickyPositioning-footer.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::BottomToTop
<< 17 << QQuickItemView::End << (QList<QPointF>() << QPointF(0,-15))
<< QPointF() << QPointF(0,0);
QTest::newRow("top footer: 1/2 down") << "stickyPositioning-footer.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::BottomToTop
<< 16 << QQuickItemView::End << (QList<QPointF>() << QPointF(0,-15) << QPointF(0,5))
<< QPointF() << QPointF(0,-5);
QTest::newRow("top footer: down") << "stickyPositioning-footer.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::BottomToTop
<< 15 << QQuickItemView::End << (QList<QPointF>() << QPointF(0,-15) << QPointF(0,10))
<< QPointF() << QPointF(0,-10);
// header at the bottom
QTest::newRow("bottom header") << "stickyPositioning-header.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::BottomToTop
<< 0 << QQuickItemView::Beginning << QList<QPointF>()
<< QPointF(0,90) << QPointF();
QTest::newRow("bottom header: 1/2 down") << "stickyPositioning-header.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::BottomToTop
<< 1 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(0,5))
<< QPointF(0,95) << QPointF();
QTest::newRow("bottom header: down") << "stickyPositioning-header.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::BottomToTop
<< 2 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(0,15))
<< QPointF(0,90) << QPointF();
QTest::newRow("bottom header: 1/2 up") << "stickyPositioning-header.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::BottomToTop
<< 3 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(0,15) << QPointF(0,-5))
<< QPointF(0,95) << QPointF();
QTest::newRow("bottom header: up") << "stickyPositioning-header.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::BottomToTop
<< 4 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(0,15) << QPointF(0,-10))
<< QPointF(0,100) << QPointF();
// footer at the bottom
QTest::newRow("bottom footer") << "stickyPositioning-footer.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 19 << QQuickItemView::End << QList<QPointF>()
<< QPointF() << QPointF(0,90);
QTest::newRow("bottom footer: 1/2 down") << "stickyPositioning-footer.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 18 << QQuickItemView::End << (QList<QPointF>() << QPointF(0,5))
<< QPointF() << QPointF(0,95);
QTest::newRow("bottom footer: down") << "stickyPositioning-footer.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 17 << QQuickItemView::End << (QList<QPointF>() << QPointF(0,15))
<< QPointF() << QPointF(0,90);
QTest::newRow("bottom footer: 1/2 up") << "stickyPositioning-footer.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 16 << QQuickItemView::End << (QList<QPointF>() << QPointF(0,15) << QPointF(0,-5))
<< QPointF() << QPointF(0,95);
QTest::newRow("bottom footer: up") << "stickyPositioning-footer.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 15 << QQuickItemView::End << (QList<QPointF>() << QPointF(0,15) << QPointF(0,-10))
<< QPointF() << QPointF(0,100);
// header at the top (& footer at the bottom)
QTest::newRow("top header & bottom footer") << "stickyPositioning-both.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 0 << QQuickItemView::Beginning << QList<QPointF>()
<< QPointF(0,0) << QPointF(0,100);
QTest::newRow("top header & bottom footer: 1/2 up") << "stickyPositioning-both.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 1 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(0,-5))
<< QPointF(0,-5) << QPointF(0,95);
QTest::newRow("top header & bottom footer: up") << "stickyPositioning-both.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 2 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(0,-15))
<< QPointF(0,0) << QPointF(0,100);
QTest::newRow("top header & bottom footer: 1/2 down") << "stickyPositioning-both.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 3 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(0,-15) << QPointF(0,5))
<< QPointF(0,-5) << QPointF(0,95);
QTest::newRow("top header & bottom footer: down") << "stickyPositioning-both.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 4 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(0,-15) << QPointF(0,10))
<< QPointF(0,-10) << QPointF(0,90);
// footer at the bottom (& header at the top)
QTest::newRow("bottom footer & top header") << "stickyPositioning-both.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 1 << QQuickItemView::Beginning << QList<QPointF>()
<< QPointF(0,-10) << QPointF(0,90);
QTest::newRow("bottom footer & top header: 1/2 down") << "stickyPositioning-both.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 1 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(0,5))
<< QPointF(0,-10) << QPointF(0,90);
QTest::newRow("bottom footer & top header: down") << "stickyPositioning-both.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 2 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(0,15))
<< QPointF(0,-10) << QPointF(0,90);
QTest::newRow("bottom footer & top header: 1/2 up") << "stickyPositioning-both.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 3 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(0,15) << QPointF(0,-5))
<< QPointF(0,-5) << QPointF(0,95);
QTest::newRow("bottom footer & top header: up") << "stickyPositioning-both.qml"
<< Qt::Vertical << Qt::LeftToRight << QQuickListView::TopToBottom
<< 4 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(0,15) << QPointF(0,-10))
<< QPointF(0,0) << QPointF(0,100);
// header on the left
QTest::newRow("left header") << "stickyPositioning-header.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 0 << QQuickItemView::Beginning << QList<QPointF>()
<< QPointF(0,0) << QPointF();
QTest::newRow("left header: 1/2 left") << "stickyPositioning-header.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 1 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(-5,0))
<< QPointF(-5,0) << QPointF();
QTest::newRow("left header: left") << "stickyPositioning-header.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 2 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(-15,0))
<< QPointF(0,0) << QPointF();
QTest::newRow("left header: 1/2 right") << "stickyPositioning-header.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 3 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(-15,0) << QPointF(5,0))
<< QPointF(-5,0) << QPointF();
QTest::newRow("left header: right") << "stickyPositioning-header.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 4 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(-15,0) << QPointF(10,0))
<< QPointF(-10,0) << QPointF();
// footer on the left
QTest::newRow("left footer") << "stickyPositioning-footer.qml"
<< Qt::Horizontal << Qt::RightToLeft << QQuickListView::TopToBottom
<< 19 << QQuickItemView::End << QList<QPointF>()
<< QPointF() << QPointF(0,0);
QTest::newRow("left footer: 1/2 left") << "stickyPositioning-footer.qml"
<< Qt::Horizontal << Qt::RightToLeft << QQuickListView::TopToBottom
<< 18 << QQuickItemView::End << (QList<QPointF>() << QPointF(-5,0))
<< QPointF() << QPointF(-5,0);
QTest::newRow("left footer: left") << "stickyPositioning-footer.qml"
<< Qt::Horizontal << Qt::RightToLeft << QQuickListView::TopToBottom
<< 17 << QQuickItemView::End << (QList<QPointF>() << QPointF(-15,0))
<< QPointF() << QPointF(0,0);
QTest::newRow("left footer: 1/2 right") << "stickyPositioning-footer.qml"
<< Qt::Horizontal << Qt::RightToLeft << QQuickListView::TopToBottom
<< 16 << QQuickItemView::End << (QList<QPointF>() << QPointF(-15,0) << QPointF(5,0))
<< QPointF() << QPointF(-5,0);
QTest::newRow("left footer: right") << "stickyPositioning-footer.qml"
<< Qt::Horizontal << Qt::RightToLeft << QQuickListView::TopToBottom
<< 15 << QQuickItemView::End << (QList<QPointF>() << QPointF(-15,0) << QPointF(10,0))
<< QPointF() << QPointF(-10,0);
// header on the right
QTest::newRow("right header") << "stickyPositioning-header.qml"
<< Qt::Horizontal << Qt::RightToLeft << QQuickListView::TopToBottom
<< 0 << QQuickItemView::Beginning << QList<QPointF>()
<< QPointF(90,0) << QPointF();
QTest::newRow("right header: 1/2 right") << "stickyPositioning-header.qml"
<< Qt::Horizontal << Qt::RightToLeft << QQuickListView::TopToBottom
<< 1 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(5,0))
<< QPointF(95,0) << QPointF();
QTest::newRow("right header: right") << "stickyPositioning-header.qml"
<< Qt::Horizontal << Qt::RightToLeft << QQuickListView::TopToBottom
<< 2 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(15,0))
<< QPointF(90,0) << QPointF();
QTest::newRow("right header: 1/2 left") << "stickyPositioning-header.qml"
<< Qt::Horizontal << Qt::RightToLeft << QQuickListView::TopToBottom
<< 3 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(15,0) << QPointF(-5,0))
<< QPointF(95,0) << QPointF();
QTest::newRow("right header: left") << "stickyPositioning-header.qml"
<< Qt::Horizontal << Qt::RightToLeft << QQuickListView::TopToBottom
<< 4 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(15,0) << QPointF(-10,0))
<< QPointF(100,0) << QPointF();
// footer on the right
QTest::newRow("right footer") << "stickyPositioning-footer.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 19 << QQuickItemView::End << QList<QPointF>()
<< QPointF() << QPointF(90,0);
QTest::newRow("right footer: 1/2 right") << "stickyPositioning-footer.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 18 << QQuickItemView::End << (QList<QPointF>() << QPointF(5,0))
<< QPointF() << QPointF(95,0);
QTest::newRow("right footer: right") << "stickyPositioning-footer.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 17 << QQuickItemView::End << (QList<QPointF>() << QPointF(15,0))
<< QPointF() << QPointF(90,0);
QTest::newRow("right footer: 1/2 left") << "stickyPositioning-footer.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 16 << QQuickItemView::End << (QList<QPointF>() << QPointF(15,0) << QPointF(-5,0))
<< QPointF() << QPointF(95,0);
QTest::newRow("right footer: left") << "stickyPositioning-footer.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 15 << QQuickItemView::End << (QList<QPointF>() << QPointF(15,0) << QPointF(-10,0))
<< QPointF() << QPointF(100,0);
// header on the left (& footer on the right)
QTest::newRow("left header & right footer") << "stickyPositioning-both.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 0 << QQuickItemView::Beginning << QList<QPointF>()
<< QPointF(0,0) << QPointF(100,0);
QTest::newRow("left header & right footer: 1/2 left") << "stickyPositioning-both.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 1 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(-5,0))
<< QPointF(-5,0) << QPointF(95,0);
QTest::newRow("left header & right footer: left") << "stickyPositioning-both.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 2 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(-15,0))
<< QPointF(0,0) << QPointF(100,0);
QTest::newRow("left header & right footer: 1/2 right") << "stickyPositioning-both.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 3 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(-15,0) << QPointF(5,0))
<< QPointF(-5,0) << QPointF(95,0);
QTest::newRow("left header & right footer: right") << "stickyPositioning-both.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 4 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(-15,0) << QPointF(10,0))
<< QPointF(-10,0) << QPointF(90,0);
// footer on the right (& header on the left)
QTest::newRow("right footer & left header") << "stickyPositioning-both.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 1 << QQuickItemView::Beginning << QList<QPointF>()
<< QPointF(-10,0) << QPointF(90,0);
QTest::newRow("right footer & left header: 1/2 right") << "stickyPositioning-both.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 1 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(5,0))
<< QPointF(-10,0) << QPointF(90,0);
QTest::newRow("right footer & left header: right") << "stickyPositioning-both.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 2 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(15,0))
<< QPointF(-10,0) << QPointF(90,0);
QTest::newRow("right footer & left header: 1/2 left") << "stickyPositioning-both.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 3 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(15,0) << QPointF(-5,0))
<< QPointF(-5,0) << QPointF(95,0);
QTest::newRow("right footer & left header: left") << "stickyPositioning-both.qml"
<< Qt::Horizontal << Qt::LeftToRight << QQuickListView::TopToBottom
<< 4 << QQuickItemView::Beginning << (QList<QPointF>() << QPointF(15,0) << QPointF(-10,0))
<< QPointF(0,0) << QPointF(100,0);
}
void tst_QQuickListView::roundingErrors()
{
QFETCH(bool, pixelAligned);
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("roundingErrors.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = qobject_cast<QQuickListView *>(window->rootObject());
QVERIFY(listview);
listview->setPixelAligned(pixelAligned);
listview->positionViewAtIndex(20, QQuickListView::Beginning);
QQuickItem *content = listview->contentItem();
QVERIFY(content);
const QPoint viewPos(150, 36);
const QPointF contentPos = content->mapFromItem(listview, viewPos);
QPointer<QQuickItem> item = listview->itemAt(contentPos.x(), contentPos.y());
QVERIFY(item);
// QTBUG-37339: drag an item and verify that it doesn't
// get prematurely released due to rounding errors
QTest::mousePress(window.data(), Qt::LeftButton, 0, viewPos);
for (int i = 0; i < 150; i += 5) {
QTest::mouseMove(window.data(), viewPos - QPoint(i, 0));
QVERIFY(item);
}
QTest::mouseRelease(window.data(), Qt::LeftButton, 0, QPoint(0, 36));
// maintain position relative to the right edge
listview->setLayoutDirection(Qt::RightToLeft);
const qreal contentX = listview->contentX();
listview->setContentX(contentX + 0.2);
QCOMPARE(listview->contentX(), pixelAligned ? qRound(contentX + 0.2) : contentX + 0.2);
listview->setWidth(listview->width() - 0.2);
QCOMPARE(listview->contentX(), pixelAligned ? qRound(contentX + 0.2) : contentX + 0.2);
// maintain position relative to the bottom edge
listview->setOrientation(QQuickListView::Vertical);
listview->setVerticalLayoutDirection(QQuickListView::BottomToTop);
const qreal contentY = listview->contentY();
listview->setContentY(contentY + 0.2);
QCOMPARE(listview->contentY(), pixelAligned ? qRound(contentY + 0.2) : contentY + 0.2);
listview->setHeight(listview->height() - 0.2);
QCOMPARE(listview->contentY(), pixelAligned ? qRound(contentY + 0.2) : contentY + 0.2);
}
void tst_QQuickListView::roundingErrors_data()
{
QTest::addColumn<bool>("pixelAligned");
QTest::newRow("pixelAligned=true") << true;
QTest::newRow("pixelAligned=false") << false;
}
void tst_QQuickListView::QTBUG_38209()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("simplelistview.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = qobject_cast<QQuickListView *>(window->rootObject());
QVERIFY(listview);
// simulate mouse flick
flick(window.data(), QPoint(200, 200), QPoint(200, 50), 100);
QTRY_VERIFY(!listview->isMoving());
qreal contentY = listview->contentY();
// flick down
listview->flick(0, 1000);
// ensure we move more than just a couple pixels
QTRY_VERIFY(contentY - listview->contentY() > qreal(100.0));
}
void tst_QQuickListView::programmaticFlickAtBounds()
{
QSKIP("Disabled due to false negatives (QTBUG-41228)");
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("simplelistview.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = qobject_cast<QQuickListView *>(window->rootObject());
QVERIFY(listview);
QSignalSpy spy(listview, SIGNAL(contentYChanged()));
// flick down
listview->flick(0, 1000);
// verify that there is movement beyond bounds
QVERIFY(spy.wait(100));
// reset, and test with StopAtBounds
listview->cancelFlick();
listview->returnToBounds();
QTRY_COMPARE(listview->contentY(), qreal(0.0));
listview->setBoundsBehavior(QQuickFlickable::StopAtBounds);
// flick down
listview->flick(0, 1000);
// verify that there is no movement beyond bounds
QVERIFY(!spy.wait(100));
}
void tst_QQuickListView::programmaticFlickAtBounds2()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("programmaticFlickAtBounds2.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = qobject_cast<QQuickListView *>(window->rootObject());
QVERIFY(listview);
// move exactly one item
qreal velocity = -qSqrt(2 * 50 * listview->flickDeceleration());
// flick down
listview->flick(0, velocity);
QTRY_COMPARE(listview->contentY(), qreal(50.0));
// flick down
listview->flick(0, velocity);
QTRY_COMPARE(listview->contentY(), qreal(100.0));
}
void tst_QQuickListView::layoutChange()
{
RandomSortModel *model = new RandomSortModel;
QSortFilterProxyModel *sortModel = new QSortFilterProxyModel;
sortModel->setSourceModel(model);
sortModel->setSortRole(Qt::UserRole);
sortModel->setDynamicSortFilter(true);
sortModel->sort(0);
QScopedPointer<QQuickView> window(createView());
window->rootContext()->setContextProperty("testModel", QVariant::fromValue(sortModel));
window->setSource(testFileUrl("layoutChangeSort.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = window->rootObject()->findChild<QQuickListView *>("listView");
QVERIFY(listview);
for (int iter = 0; iter < 100; iter++) {
for (int i = 0; i < sortModel->rowCount(); ++i) {
QQuickItem *delegateItem = listview->itemAt(10, 10 + 2 * i * 20 + 20); // item + group
QVERIFY(delegateItem);
QQuickItem *delegateText = delegateItem->findChild<QQuickItem *>("delegateText");
QVERIFY(delegateText);
QCOMPARE(delegateText->property("text").toString(),
sortModel->index(i, 0, QModelIndex()).data().toString());
}
model->randomize();
listview->forceLayout();
QTest::qWait(5); // give view a chance to update
}
}
void tst_QQuickListView::QTBUG_39492_data()
{
QStandardItemModel *sourceModel = new QStandardItemModel(this);
for (int i = 0; i < 5; ++i) {
QStandardItem *item = new QStandardItem(QString::number(i));
for (int j = 0; j < 5; ++j) {
QStandardItem *subItem = new QStandardItem(QString("%1-%2").arg(i).arg(j));
item->appendRow(subItem);
}
sourceModel->appendRow(item);
}
QSortFilterProxyModel *sortModel = new QSortFilterProxyModel(this);
sortModel->setSourceModel(sourceModel);
QTest::addColumn<QSortFilterProxyModel*>("model");
QTest::addColumn<QPersistentModelIndex>("rootIndex");
QTest::newRow("invalid rootIndex")
<< sortModel
<< QPersistentModelIndex();
QTest::newRow("rootIndex 1")
<< sortModel
<< QPersistentModelIndex(sortModel->index(1, 0));
QTest::newRow("rootIndex 3")
<< sortModel
<< QPersistentModelIndex(sortModel->index(3, 0));
const QModelIndex rootIndex2 = sortModel->index(2, 0);
QTest::newRow("rootIndex 2-1")
<< sortModel
<< QPersistentModelIndex(sortModel->index(1, 0, rootIndex2));
}
void tst_QQuickListView::QTBUG_39492()
{
QFETCH(QSortFilterProxyModel*, model);
QFETCH(QPersistentModelIndex, rootIndex);
QQuickView *window = getView();
window->rootContext()->setContextProperty("testModel", QVariant::fromValue(model));
window->setSource(testFileUrl("qtbug39492.qml"));
QQuickListView *listview = window->rootObject()->findChild<QQuickListView *>("listView");
QVERIFY(listview);
QQmlDelegateModel *delegateModel = window->rootObject()->findChild<QQmlDelegateModel *>("delegateModel");
QVERIFY(delegateModel);
delegateModel->setRootIndex(QVariant::fromValue(QModelIndex(rootIndex)));
model->sort(0, Qt::AscendingOrder);
listview->forceLayout();
for (int i = 0; i < model->rowCount(rootIndex); ++i) {
QQuickItem *delegateItem = listview->itemAt(10, 10 + i * 20);
QVERIFY(delegateItem);
QQuickItem *delegateText = delegateItem->findChild<QQuickItem *>("delegateText");
QVERIFY(delegateText);
QCOMPARE(delegateText->property("text").toString(),
model->index(i, 0, rootIndex).data().toString());
}
model->sort(0, Qt::DescendingOrder);
listview->forceLayout();
for (int i = 0; i < model->rowCount(rootIndex); ++i) {
QQuickItem *delegateItem = listview->itemAt(10, 10 + i * 20);
QVERIFY(delegateItem);
QQuickItem *delegateText = delegateItem->findChild<QQuickItem *>("delegateText");
QVERIFY(delegateText);
QCOMPARE(delegateText->property("text").toString(),
model->index(i, 0, rootIndex).data().toString());
}
releaseView(window);
}
void tst_QQuickListView::jsArrayChange()
{
QQmlEngine engine;
QQmlComponent component(&engine);
component.setData("import QtQuick 2.4; ListView {}", QUrl());
QScopedPointer<QQuickListView> view(qobject_cast<QQuickListView *>(component.create()));
QVERIFY(!view.isNull());
QSignalSpy spy(view.data(), SIGNAL(modelChanged()));
QVERIFY(spy.isValid());
QJSValue array1 = engine.newArray(3);
QJSValue array2 = engine.newArray(3);
for (int i = 0; i < 3; ++i) {
array1.setProperty(i, i);
array2.setProperty(i, i);
}
view->setModel(QVariant::fromValue(array1));
QCOMPARE(spy.count(), 1);
// no change
view->setModel(QVariant::fromValue(array2));
QCOMPARE(spy.count(), 1);
}
static bool compareObjectModel(QQuickListView *listview, QQmlObjectModel *model)
{
if (listview->count() != model->count())
return false;
for (int i = 0; i < listview->count(); ++i) {
listview->setCurrentIndex(i);
if (listview->currentItem() != model->get(i))
return false;
}
return true;
}
void tst_QQuickListView::objectModel()
{
QQmlEngine engine;
QQmlComponent component(&engine, testFileUrl("objectmodel.qml"));
QQuickListView *listview = qobject_cast<QQuickListView *>(component.create());
QVERIFY(listview);
QQmlObjectModel *model = listview->model().value<QQmlObjectModel *>();
QVERIFY(model);
listview->setCurrentIndex(0);
QVERIFY(listview->currentItem());
QCOMPARE(listview->currentItem()->property("color").toString(), QColor("red").name());
listview->setCurrentIndex(1);
QVERIFY(listview->currentItem());
QCOMPARE(listview->currentItem()->property("color").toString(), QColor("green").name());
listview->setCurrentIndex(2);
QVERIFY(listview->currentItem());
QCOMPARE(listview->currentItem()->property("color").toString(), QColor("blue").name());
QQuickItem *item0 = new QQuickItem(listview);
item0->setSize(QSizeF(20, 20));
model->append(item0);
QCOMPARE(model->count(), 4);
QVERIFY(compareObjectModel(listview, model));
QQuickItem *item1 = new QQuickItem(listview);
item1->setSize(QSizeF(20, 20));
model->insert(0, item1);
QCOMPARE(model->count(), 5);
QVERIFY(compareObjectModel(listview, model));
model->move(1, 2, 3);
QVERIFY(compareObjectModel(listview, model));
model->remove(2, 2);
QCOMPARE(model->count(), 3);
QVERIFY(compareObjectModel(listview, model));
model->clear();
QCOMPARE(model->count(), 0);
QCOMPARE(listview->count(), 0);
delete listview;
}
void tst_QQuickListView::contentHeightWithDelayRemove_data()
{
QTest::addColumn<bool>("useDelayRemove");
QTest::addColumn<QByteArray>("removeFunc");
QTest::addColumn<int>("countDelta");
QTest::addColumn<qreal>("contentHeightDelta");
QTest::newRow("remove without delayRemove")
<< false
<< QByteArray("takeOne")
<< -1
<< qreal(-1 * 100.0);
QTest::newRow("remove with delayRemove")
<< true
<< QByteArray("takeOne")
<< -1
<< qreal(-1 * 100.0);
QTest::newRow("remove with multiple delayRemove")
<< true
<< QByteArray("takeThree")
<< -3
<< qreal(-3 * 100.0);
QTest::newRow("clear with delayRemove")
<< true
<< QByteArray("takeAll")
<< -5
<< qreal(-5 * 100.0);
}
void tst_QQuickListView::contentHeightWithDelayRemove()
{
QFETCH(bool, useDelayRemove);
QFETCH(QByteArray, removeFunc);
QFETCH(int, countDelta);
QFETCH(qreal, contentHeightDelta);
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("contentHeightWithDelayRemove.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = window->rootObject()->findChild<QQuickListView*>();
QTRY_VERIFY(listview != 0);
const int initialCount(listview->count());
const int eventualCount(initialCount + countDelta);
const qreal initialContentHeight(listview->contentHeight());
const int eventualContentHeight(qRound(initialContentHeight + contentHeightDelta));
listview->setProperty("useDelayRemove", useDelayRemove);
QMetaObject::invokeMethod(window->rootObject(), removeFunc.constData());
QTest::qWait(50);
QCOMPARE(listview->count(), eventualCount);
if (useDelayRemove) {
QCOMPARE(qRound(listview->contentHeight()), qRound(initialContentHeight));
QTRY_COMPARE(qRound(listview->contentHeight()), eventualContentHeight);
} else {
QCOMPARE(qRound(listview->contentHeight()), eventualContentHeight);
}
}
void tst_QQuickListView::QTBUG_48044_currentItemNotVisibleAfterTransition()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("qtbug48044.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = window->rootObject()->findChild<QQuickListView*>();
QTRY_VERIFY(listview != 0);
// Expand 2nd header
listview->setProperty("transitionsDone", QVariant(false));
QTest::mouseClick(window.data(), Qt::LeftButton, Qt::NoModifier, QPoint(window->width() / 2, 75));
QTRY_VERIFY(listview->property("transitionsDone").toBool());
// Flick listview to the bottom
flick(window.data(), QPoint(window->width() / 2, 400), QPoint(window->width() / 2, 0), 100);
QTRY_VERIFY(!listview->isMoving());
// Expand 3rd header
listview->setProperty("transitionsDone", QVariant(false));
QTest::mouseClick(window.data(), Qt::LeftButton, Qt::NoModifier, QPoint(window->width() / 2, window->height() - 25));
QTRY_VERIFY(listview->property("transitionsDone").toBool());
// Check current item is what we expect
QCOMPARE(listview->currentIndex(), 2);
QQuickItem *currentItem = listview->currentItem();
QVERIFY(currentItem);
QVERIFY(currentItem->isVisible());
// This is the actual test
QQuickItemPrivate *currentPriv = QQuickItemPrivate::get(currentItem);
QVERIFY(!currentPriv->culled);
}
void tst_QQuickListView::keyNavigationEnabled()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("keyNavigationEnabled.qml"));
window->show();
window->requestActivate();
QVERIFY(QTest::qWaitForWindowActive(window.data()));
QQuickListView *listView = qobject_cast<QQuickListView *>(window->rootObject());
QVERIFY(listView);
QCOMPARE(listView->isKeyNavigationEnabled(), true);
listView->setFocus(true);
QVERIFY(listView->hasActiveFocus());
listView->setHighlightMoveDuration(0);
// If keyNavigationEnabled is not explicitly set to true, respect the original behavior
// of disabling both mouse and keyboard interaction.
QSignalSpy enabledSpy(listView, SIGNAL(keyNavigationEnabledChanged()));
listView->setInteractive(false);
QCOMPARE(enabledSpy.count(), 1);
QCOMPARE(listView->isKeyNavigationEnabled(), false);
flick(window.data(), QPoint(200, 200), QPoint(200, 50), 100);
QVERIFY(!listView->isMoving());
QCOMPARE(listView->contentY(), 0.0);
QCOMPARE(listView->currentIndex(), 0);
QTest::keyClick(window.data(), Qt::Key_Down);
QCOMPARE(listView->currentIndex(), 0);
// Check that isKeyNavigationEnabled implicitly follows the value of interactive.
listView->setInteractive(true);
QCOMPARE(enabledSpy.count(), 2);
QCOMPARE(listView->isKeyNavigationEnabled(), true);
// Change it back again for the next check.
listView->setInteractive(false);
QCOMPARE(enabledSpy.count(), 3);
QCOMPARE(listView->isKeyNavigationEnabled(), false);
// Setting keyNavigationEnabled to true shouldn't enable mouse interaction.
listView->setKeyNavigationEnabled(true);
QCOMPARE(enabledSpy.count(), 4);
flick(window.data(), QPoint(200, 200), QPoint(200, 50), 100);
QVERIFY(!listView->isMoving());
QCOMPARE(listView->contentY(), 0.0);
QCOMPARE(listView->currentIndex(), 0);
// Should now work.
QTest::keyClick(window.data(), Qt::Key_Down);
QCOMPARE(listView->currentIndex(), 1);
// contentY won't change for one index change in a view this high.
// Changing interactive now shouldn't result in keyNavigationEnabled changing,
// since we broke the "binding".
listView->setInteractive(true);
QCOMPARE(enabledSpy.count(), 4);
// Keyboard interaction shouldn't work now.
listView->setKeyNavigationEnabled(false);
QTest::keyClick(window.data(), Qt::Key_Down);
QCOMPARE(listView->currentIndex(), 1);
}
void tst_QQuickListView::QTBUG_48870_fastModelUpdates()
{
StressTestModel model;
QScopedPointer<QQuickView> window(createView());
QQmlContext *ctxt = window->rootContext();
ctxt->setContextProperty("testModel", &model);
window->setSource(testFileUrl("qtbug48870.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = findItem<QQuickListView>(window->rootObject(), "list");
QTRY_VERIFY(listview != 0);
QQuickItemViewPrivate *priv = QQuickItemViewPrivate::get(listview);
bool nonUnique;
FxViewItem *item = Q_NULLPTR;
int expectedIdx;
QVERIFY(testVisibleItems(priv, &nonUnique, &item, &expectedIdx));
for (int i = 0; i < 10; i++) {
QTest::qWait(100);
QVERIFY2(testVisibleItems(priv, &nonUnique, &item, &expectedIdx),
qPrintable(!item ? QString("Unexpected null item")
: nonUnique ? QString("Non-unique item at %1 and %2").arg(item->index).arg(expectedIdx)
: QString("Found index %1, expected index is %3").arg(item->index).arg(expectedIdx)));
if (i % 3 != 0) {
if (i & 1)
flick(window.data(), QPoint(100, 200), QPoint(100, 0), 100);
else
flick(window.data(), QPoint(100, 200), QPoint(100, 400), 100);
}
}
}
// infinite loop in overlay header positioning due to undesired rounding in QQuickFlickablePrivate::fixup()
void tst_QQuickListView::QTBUG_50105()
{
QQmlEngine engine;
QQmlComponent component(&engine);
component.loadUrl(testFileUrl("qtbug50105.qml"));
QScopedPointer<QQuickWindow> window(qobject_cast<QQuickWindow *>(component.create()));
QVERIFY(window.data());
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
}
void tst_QQuickListView::QTBUG_50097_stickyHeader_positionViewAtIndex()
{
QScopedPointer<QQuickView> window(createView());
window->setSource(testFileUrl("qtbug50097.qml"));
window->show();
QVERIFY(QTest::qWaitForWindowExposed(window.data()));
QQuickListView *listview = qobject_cast<QQuickListView*>(window->rootObject());
QVERIFY(listview != 0);
QTRY_COMPARE(listview->contentY(), -100.0); // the header size, since the header is overlaid
listview->setProperty("currentPage", 2);
QTRY_COMPARE(listview->contentY(), 400.0); // a full page of items down, sans the original negative header position
listview->setProperty("currentPage", 1);
QTRY_COMPARE(listview->contentY(), -100.0); // back to the same position: header visible, items not under the header.
}
void tst_QQuickListView::itemFiltered()
{
QStringListModel model(QStringList() << "one" << "two" << "three" << "four" << "five" << "six");
QSortFilterProxyModel proxy1;
proxy1.setSourceModel(&model);
proxy1.setSortRole(Qt::DisplayRole);
proxy1.setDynamicSortFilter(true);
proxy1.sort(0);
QSortFilterProxyModel proxy2;
proxy2.setSourceModel(&proxy1);
proxy2.setFilterRole(Qt::DisplayRole);
proxy2.setFilterRegExp("^[^ ]*$");
proxy2.setDynamicSortFilter(true);
QScopedPointer<QQuickView> window(createView());
window->engine()->rootContext()->setContextProperty("_model", &proxy2);
QQmlComponent component(window->engine());
component.setData("import QtQuick 2.4; ListView { "
"anchors.fill: parent; model: _model; delegate: Text { width: parent.width;"
"text: model.display; } }",
QUrl());
window->setContent(QUrl(), &component, component.create());
window->show();
QTest::qWaitForWindowExposed(window.data());
// this should not crash
model.setData(model.index(2), QStringLiteral("modified three"), Qt::DisplayRole);
}
QTEST_MAIN(tst_QQuickListView)
#include "tst_qquicklistview.moc"
| geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtdeclarative/tests/auto/quick/qquicklistview/tst_qquicklistview.cpp | C++ | gpl-3.0 | 332,798 |
/*****************************************************************
* This file is part of Managing Agricultural Research for Learning &
* Outcomes Platform (MARLO).
* MARLO is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* at your option) any later version.
* MARLO is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with MARLO. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************/
package org.cgiar.ccafs.marlo.action.summaries;
import org.cgiar.ccafs.marlo.data.manager.GlobalUnitManager;
import org.cgiar.ccafs.marlo.data.manager.PhaseManager;
import org.cgiar.ccafs.marlo.data.manager.ProjectExpectedStudyCountryManager;
import org.cgiar.ccafs.marlo.data.manager.ProjectManager;
import org.cgiar.ccafs.marlo.data.model.ExpectedStudyProject;
import org.cgiar.ccafs.marlo.data.model.ProgramType;
import org.cgiar.ccafs.marlo.data.model.ProjectExpectedStudyCountry;
import org.cgiar.ccafs.marlo.data.model.ProjectExpectedStudyCrp;
import org.cgiar.ccafs.marlo.data.model.ProjectExpectedStudyFlagship;
import org.cgiar.ccafs.marlo.data.model.ProjectExpectedStudyGeographicScope;
import org.cgiar.ccafs.marlo.data.model.ProjectExpectedStudyInfo;
import org.cgiar.ccafs.marlo.data.model.ProjectExpectedStudyInnovation;
import org.cgiar.ccafs.marlo.data.model.ProjectExpectedStudyInstitution;
import org.cgiar.ccafs.marlo.data.model.ProjectExpectedStudyLink;
import org.cgiar.ccafs.marlo.data.model.ProjectExpectedStudyPolicy;
import org.cgiar.ccafs.marlo.data.model.ProjectExpectedStudyReference;
import org.cgiar.ccafs.marlo.data.model.ProjectExpectedStudyRegion;
import org.cgiar.ccafs.marlo.data.model.ProjectExpectedStudySrfTarget;
import org.cgiar.ccafs.marlo.data.model.ProjectExpectedStudySubIdo;
import org.cgiar.ccafs.marlo.utils.APConfig;
import org.cgiar.ccafs.marlo.utils.HTMLParser;
import org.cgiar.ccafs.marlo.utils.URLShortener;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.util.TypedTableModel;
public class BaseStudySummaryData extends BaseSummariesAction {
private static final long serialVersionUID = -3643067302492726266L;
private final HTMLParser htmlParser;
private final ProjectExpectedStudyCountryManager projectExpectedStudyCountryManager;
public BaseStudySummaryData(APConfig config, GlobalUnitManager crpManager, PhaseManager phaseManager,
ProjectManager projectManager, HTMLParser htmlParser,
ProjectExpectedStudyCountryManager projectExpectedStudyCountryManager) {
super(config, crpManager, phaseManager, projectManager);
this.htmlParser = htmlParser;
this.projectExpectedStudyCountryManager = projectExpectedStudyCountryManager;
}
/**
* Method to add i8n parameters to masterReport in Pentaho
*
* @param masterReport
* @return masterReport with i8n parameters added
*/
public MasterReport addi8nParameters(MasterReport masterReport) {
masterReport.getParameterValues().put("i8nStudies", this.getText("menu.studies"));
masterReport.getParameterValues().put("i8nStudiesRNoData", this.getText("summaries.study.noData"));
masterReport.getParameterValues().put("i8nStudiesRCaseStudy", this.getText("summaries.study"));
masterReport.getParameterValues().put("i8nCaseStudiesRStudyProjects",
this.getText("summaries.study.studyContributingProjects"));
masterReport.getParameterValues().put("i8nCaseStudiesRPartI", this.getText("summaries.study.partI"));
masterReport.getParameterValues().put("i8nStudiesRType", this.getText("study.type"));
masterReport.getParameterValues().put("i8nStudiesRStatus", this.getText("study.status"));
masterReport.getParameterValues().put("i8nStudiesRYear", this.getText("summaries.study.year"));
masterReport.getParameterValues().put("i8nStudiesRTagged", this.getText("summaries.study.tagged"));
masterReport.getParameterValues().put("i8nStudiesRTitle", this.getText("summaries.study.title"));
masterReport.getParameterValues().put("i8nStudiesROutcomeImpactStatement",
this.getText("summaries.study.outcomeStatement"));
masterReport.getParameterValues().put("i8nCaseStudiesROutcomeStory", this.getText("study.outcomestory.readText"));
masterReport.getParameterValues().put("i8nCaseStudiesROutcomestoryLinks",
this.getText("study.outcomestoryLinks.readText"));
masterReport.getParameterValues().put("i8nCaseStudiesRPartII", this.getText("summaries.study.partII"));
masterReport.getParameterValues().put("i8nStudiesRIsContributionText",
this.getText("summaries.study.reportingIndicatorThree"));
masterReport.getParameterValues().put("i8nCaseStudiesRPolicies", this.getText("study.policies.readText"));
masterReport.getParameterValues().put("i8nStudiesRStageStudy", this.getText("summaries.study.maturityChange"));
masterReport.getParameterValues().put("i8nStudiesRStrategicResults",
this.getText("summaries.study.stratgicResultsLink"));
masterReport.getParameterValues().put("i8nStudiesRSubIdos",
this.getText("summaries.study.stratgicResultsLink.subIDOs"));
masterReport.getParameterValues().put("i8nCaseStudiesRTargetOption", this.getText("study.targetsOption"));
masterReport.getParameterValues().put("i8nStudiesRSRFTargets",
this.getText("summaries.study.stratgicResultsLink.srfTargets"));
masterReport.getParameterValues().put("i8nStudiesRTopLevelCommentst",
this.getText("summaries.study.stratgicResultsLink.comments"));
masterReport.getParameterValues().put("i8nStudiesRGeographicScope", this.getText("study.geographicScope"));
masterReport.getParameterValues().put("i8nStudiesRRegion", this.getText("study.region"));
masterReport.getParameterValues().put("i8nStudiesRContries", this.getText("involveParticipants.countries"));
masterReport.getParameterValues().put("i8nStudiesRScopeComments",
this.getText("study.geographicScopeComments.readText"));
masterReport.getParameterValues().put("i8nStudiesRKeyContributors",
this.getText("summaries.study.keyContributors"));
masterReport.getParameterValues().put("i8nStudiesRCrps", this.getText("study.keyContributors.crps"));
masterReport.getParameterValues().put("i8nStudiesRFlagships", this.getText("study.keyContributors.flagships"));
masterReport.getParameterValues().put("i8nStudiesRRegions", this.getText("study.keyContributors.regions"));
masterReport.getParameterValues().put("i8nStudiesRInstitutions",
this.getText("study.keyContributors.externalPartners"));
masterReport.getParameterValues().put("i8nStudiesCGIARInnovation",
this.getText("study.innovationsNarrative.readText"));
masterReport.getParameterValues().put("i8nStudiesCGIARInnovations", this.getText("study.innovationsList"));
masterReport.getParameterValues().put("i8nStudiesRElaborationOutcomeImpactStatement",
this.getText("summaries.study.elaborationStatement"));
masterReport.getParameterValues().put("i8nStudiesRReferenceText", this.getText("summaries.study.referencesCited"));
masterReport.getParameterValues().put("i8nStudiesRGenderDevelopment",
this.getText("summaries.study.crossCuttingRelevance"));
masterReport.getParameterValues().put("i8nStudiesRGenderRelevance", this.getText("study.genderRelevance"));
masterReport.getParameterValues().put("i8nStudiesRYouthRelevance", this.getText("study.youthRelevance"));
masterReport.getParameterValues().put("i8nStudiesRCapacityRelevance", this.getText("study.capDevRelevance"));
masterReport.getParameterValues().put("i8nStudiesRClimateRelevance", this.getText("study.climateRelevance"));
masterReport.getParameterValues().put("i8nStudiesROtherCrossCuttingDimensions",
this.getText("study.otherCrossCutting.readText"));
masterReport.getParameterValues().put("i8nStudiesROtherCrossCuttingDimensionsComments",
this.getText("study.otherCrossCutting.comments.readText"));
masterReport.getParameterValues().put("i8nStudiesRContacts", this.getText("summaries.study.contacts"));
masterReport.getParameterValues().put("i8nStudiesRCommissioningStudy",
this.getText("study.commissioningStudy.readText"));
masterReport.getParameterValues().put("i8nStudiesRStudyLink", this.getText("summaries.study.link"));
masterReport.getParameterValues().put("i8nStudiesRQuantification", this.getText("study.quantification.readText"));
masterReport.getParameterValues().put("i8nStudiesRQuantificationType", this.getText("study.quantificationType"));
masterReport.getParameterValues().put("i8nStudiesRQuantificationNumber",
this.getText("study.quantification.number"));
masterReport.getParameterValues().put("i8nStudiesRQuantificationTargetUnit",
this.getText("study.quantification.targetUnit"));
masterReport.getParameterValues().put("i8nStudiesRQuantificationComments",
this.getText("study.quantification.comments.readText"));
masterReport.getParameterValues().put("i8nStudiesRQuantificationType1",
this.getText("study.quantification.quantificationType-1"));
masterReport.getParameterValues().put("i8nStudiesRQuantificationType2",
this.getText("study.quantification.quantificationType-2"));
return masterReport;
}
public TypedTableModel getCaseStudiesTableModel(List<ProjectExpectedStudyInfo> projectExpectedStudyInfos) {
TypedTableModel model = new TypedTableModel(
new String[] {"id", "year", "title", "commissioningStudy", "status", "type", "outcomeImpactStatement",
"isContributionText", "stageStudy", "srfTargets", "subIdos", "topLevelComments", "geographicScopes", "regions",
"countries", "scopeComments", "crps", "flagships", "regionalPrograms", "institutions",
"elaborationOutcomeImpactStatement", "referenceText", "quantification", "genderRelevance", "youthRelevance",
"capacityRelevance", "otherCrossCuttingDimensions", "comunicationsMaterial", "contacts", "studyProjects",
"tagged", "cgiarInnovation", "cgiarInnovations", "climateRelevance", "link", "links", "studyPolicies",
"isSrfTargetText", "otherCrossCuttingDimensionsSelection", "isContribution", "isRegional", "isNational",
"isOutcomeCaseStudy", "isSrfTarget", "url", "studiesReference"},
new Class[] {Long.class, Integer.class, String.class, String.class, String.class, String.class, String.class,
String.class, String.class, String.class, String.class, String.class, String.class, String.class, String.class,
String.class, String.class, String.class, String.class, String.class, String.class, String.class, String.class,
String.class, String.class, String.class, String.class, String.class, String.class, String.class, String.class,
String.class, String.class, String.class, String.class, String.class, String.class, String.class, String.class,
Boolean.class, Boolean.class, Boolean.class, Boolean.class, Boolean.class, String.class, String.class},
0);
URLShortener urlShortener = new URLShortener();
if (projectExpectedStudyInfos != null && !projectExpectedStudyInfos.isEmpty()) {
projectExpectedStudyInfos
.sort((p1, p2) -> p1.getProjectExpectedStudy().getId().compareTo(p2.getProjectExpectedStudy().getId()));
for (ProjectExpectedStudyInfo projectExpectedStudyInfo : projectExpectedStudyInfos) {
Long id = null;
Integer year = null;
String title = null, commissioningStudy = null, status = null, type = null, outcomeImpactStatement = null,
isContributionText = null, stageStudy = null, srfTargets = null, subIdos = null, topLevelComments = null,
geographicScopes = null, regions = null, countries = null, scopeComments = null, crps = null,
flagships = null, regionalPrograms = null, institutions = null, elaborationOutcomeImpactStatement = null,
quantification = null, genderRelevance = null, youthRelevance = null, capacityRelevance = null,
otherCrossCuttingDimensions = null, comunicationsMaterial = null, contacts = null, studyProjects = null,
tagged = null, cgiarInnovation = null, cgiarInnovations = null, climateRelevance = null, link = null,
links = null, studyPolicies = null, isSrfTargetText = null, otherCrossCuttingDimensionsSelection = null,
url = null, studiesReference = null;
Boolean isContribution = false, isRegional = false, isNational = false, isOutcomeCaseStudy = false,
isSrfTarget = false;
StringBuffer referenceText = new StringBuffer();
id = projectExpectedStudyInfo.getProjectExpectedStudy().getId();
// Type
if (projectExpectedStudyInfo.getStudyType() != null) {
type = projectExpectedStudyInfo.getStudyType().getName();
if (projectExpectedStudyInfo.getStudyType().getId().intValue() == 1) {
isOutcomeCaseStudy = true;
}
}
// Status
if (projectExpectedStudyInfo.getStatus() != null) {
status = projectExpectedStudyInfo.getStatus().getName();
}
// Year
if (projectExpectedStudyInfo.getProjectExpectedStudy().getProjectExpectedStudyInfo(this.getSelectedPhase())
.getYear() != null) {
year = projectExpectedStudyInfo.getProjectExpectedStudy().getProjectExpectedStudyInfo(this.getSelectedPhase())
.getYear();
}
// Tagged
if (projectExpectedStudyInfo != null && projectExpectedStudyInfo.getEvidenceTag() != null
&& projectExpectedStudyInfo.getEvidenceTag().getName() != null) {
tagged = projectExpectedStudyInfo.getEvidenceTag().getName();
}
// Title
if (projectExpectedStudyInfo.getTitle() != null && !projectExpectedStudyInfo.getTitle().trim().isEmpty()) {
title = projectExpectedStudyInfo.getTitle();
}
// Commissioning Study
if (projectExpectedStudyInfo.getCommissioningStudy() != null
&& !projectExpectedStudyInfo.getCommissioningStudy().trim().isEmpty()) {
commissioningStudy = projectExpectedStudyInfo.getCommissioningStudy();
}
// Outcome Impact Statement
if (projectExpectedStudyInfo.getOutcomeImpactStatement() != null
&& !projectExpectedStudyInfo.getOutcomeImpactStatement().trim().isEmpty()) {
outcomeImpactStatement = projectExpectedStudyInfo.getOutcomeImpactStatement();
}
// Communications materials
if (projectExpectedStudyInfo.getComunicationsMaterial() != null
&& !projectExpectedStudyInfo.getComunicationsMaterial().trim().isEmpty()) {
comunicationsMaterial = htmlParser.plainTextToHtml(projectExpectedStudyInfo.getComunicationsMaterial());
if (this.isSelectedPhaseAR2021() && StringUtils.isBlank(comunicationsMaterial)) {
comunicationsMaterial = this.getText("global.AR2021.notRequired");
}
}
// Links
List<ProjectExpectedStudyLink> linksList =
projectExpectedStudyInfo.getProjectExpectedStudy().getProjectExpectedStudyLinks().stream()
.filter(s -> s.isActive() && s.getPhase() != null && s.getPhase().equals(this.getSelectedPhase()))
.collect(Collectors.toList());
Set<String> linkSet = new HashSet<>();
if (linksList != null && linksList.size() > 0) {
linksList.sort((l1, l2) -> l1.getId().compareTo(l2.getId()));
for (ProjectExpectedStudyLink projectExpectedStudyLink : linksList) {
if (!projectExpectedStudyLink.getLink().isEmpty() && projectExpectedStudyLink.getLink() != null) {
/*
* Get short url calling tinyURL service
*/
linkSet.add(
"<br> ● " + urlShortener.getShortUrlService(projectExpectedStudyLink.getLink()));
}
}
links = String.join("", linkSet);
}
// isContribution
if (projectExpectedStudyInfo.getIsContribution() != null) {
isContribution = projectExpectedStudyInfo.getIsContribution();
isContributionText = projectExpectedStudyInfo.getIsContribution() ? "Yes" : "No";
if (isContribution) {
// Policies Contribution
List<ProjectExpectedStudyPolicy> studyPoliciesList =
projectExpectedStudyInfo.getProjectExpectedStudy().getProjectExpectedStudyPolicies().stream()
.filter(s -> s.isActive() && s.getPhase() != null && s.getPhase().equals(this.getSelectedPhase()))
.collect(Collectors.toList());
Set<String> studyPoliciesSet = new HashSet<>();
if (studyPoliciesList != null && studyPoliciesList.size() > 0) {
for (ProjectExpectedStudyPolicy projectExpectedStudyPolicy : studyPoliciesList) {
if (projectExpectedStudyPolicy.getProjectPolicy()
.getProjectPolicyInfo(this.getSelectedPhase()) != null) {
studyPoliciesSet.add(
"<br> ● " + projectExpectedStudyPolicy.getProjectPolicy().getComposedName());
}
}
studyPolicies = String.join("", studyPoliciesSet);
}
}
}
// Level of maturity
if (projectExpectedStudyInfo.getRepIndStageStudy() != null) {
stageStudy = projectExpectedStudyInfo.getRepIndStageStudy().getName();
}
// SubIdos
List<ProjectExpectedStudySubIdo> subIdosList =
projectExpectedStudyInfo.getProjectExpectedStudy().getProjectExpectedStudySubIdos().stream()
.filter(s -> s.isActive() && s.getPhase() != null && s.getPhase().equals(this.getSelectedPhase()))
.collect(Collectors.toList());
Set<String> subIdoSet = new HashSet<>();
if (subIdosList != null && subIdosList.size() > 0) {
for (ProjectExpectedStudySubIdo studySrfTarget : subIdosList) {
subIdoSet.add("<br> ● " + studySrfTarget.getSrfSubIdo().getDescription());
}
subIdos = String.join("", subIdoSet);
}
// is SRF Target
if (projectExpectedStudyInfo.getIsSrfTarget() != null && !projectExpectedStudyInfo.getIsSrfTarget().isEmpty()) {
isSrfTargetText = this.getText("study." + projectExpectedStudyInfo.getIsSrfTarget());
if (projectExpectedStudyInfo.getIsSrfTarget().equals("targetsOptionYes")) {
isSrfTarget = true;
// SRF Targets
List<ProjectExpectedStudySrfTarget> studySrfTargets =
projectExpectedStudyInfo.getProjectExpectedStudy().getProjectExpectedStudySrfTargets().stream()
.filter(s -> s.isActive() && s.getPhase() != null && s.getPhase().equals(this.getSelectedPhase()))
.collect(Collectors.toList());
Set<String> srfTargetSet = new HashSet<>();
if (studySrfTargets != null && studySrfTargets.size() > 0) {
for (ProjectExpectedStudySrfTarget studySrfTarget : studySrfTargets) {
srfTargetSet.add("<br> ● " + studySrfTarget.getSrfSloIndicator().getTitle());
}
srfTargets = String.join("", srfTargetSet);
}
}
}
// Comments
if (projectExpectedStudyInfo.getTopLevelComments() != null
&& !projectExpectedStudyInfo.getTopLevelComments().trim().isEmpty()) {
topLevelComments = htmlParser.plainTextToHtml(projectExpectedStudyInfo.getTopLevelComments());
}
// Geographic Scopes
List<ProjectExpectedStudyGeographicScope> geographicScopeList =
projectExpectedStudyInfo.getProjectExpectedStudy().getProjectExpectedStudyGeographicScopes().stream()
.filter(s -> s.isActive() && s.getPhase() != null && s.getPhase().equals(this.getSelectedPhase()))
.collect(Collectors.toList());
Set<String> geographicScopeSet = new HashSet<>();
if (geographicScopeList != null && geographicScopeList.size() > 0) {
for (ProjectExpectedStudyGeographicScope geographicScope : geographicScopeList) {
if (!geographicScope.getRepIndGeographicScope().getId().equals(this.getReportingIndGeographicScopeGlobal())
&& !geographicScope.getRepIndGeographicScope().getId()
.equals(this.getReportingIndGeographicScopeRegional())) {
isNational = true;
}
if (geographicScope.getRepIndGeographicScope().getId()
.equals(this.getReportingIndGeographicScopeRegional())) {
isRegional = true;
}
geographicScopeSet
.add("<br> ● " + geographicScope.getRepIndGeographicScope().getName());
}
geographicScopes = String.join("", geographicScopeSet);
}
// Country(s)
if (isNational) {
List<ProjectExpectedStudyCountry> studyCountries = this.projectExpectedStudyCountryManager
.getProjectExpectedStudyCountrybyPhase(projectExpectedStudyInfo.getProjectExpectedStudy().getId(),
this.getSelectedPhase().getId())
.stream().filter(le -> le.isActive() && le.getLocElement().getLocElementType().getId() == 2)
.collect(Collectors.toList());
if (studyCountries != null && studyCountries.size() > 0) {
Set<String> countriesSet = new HashSet<>();
for (ProjectExpectedStudyCountry projectExpectedStudyCountry : studyCountries) {
countriesSet
.add("<br> ● " + projectExpectedStudyCountry.getLocElement().getName());
}
countries = String.join("", countriesSet);
}
}
// Region(s)
if (isRegional) {
List<ProjectExpectedStudyRegion> studyRegions =
projectExpectedStudyInfo.getProjectExpectedStudy().getProjectExpectedStudyRegions().stream()
.filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(this.getSelectedPhase()))
.collect(Collectors.toList());
if (studyRegions != null && studyRegions.size() > 0) {
Set<String> regionsSet = new HashSet<>();
for (ProjectExpectedStudyRegion projectExpectedStudyRegion : studyRegions) {
regionsSet.add("<br> ● " + projectExpectedStudyRegion.getLocElement().getName());
}
regions = String.join("", regionsSet);
}
}
// Geographic Scope comment
if (projectExpectedStudyInfo.getScopeComments() != null
&& !projectExpectedStudyInfo.getScopeComments().trim().isEmpty()) {
scopeComments = htmlParser.plainTextToHtml(projectExpectedStudyInfo.getScopeComments());
/*
* Get short url calling tinyURL service
*/
scopeComments = urlShortener.detectAndShortenLinks(scopeComments);
}
// Key Contributions
// CRPs/Platforms
List<ProjectExpectedStudyCrp> studyCrpsList =
projectExpectedStudyInfo.getProjectExpectedStudy().getProjectExpectedStudyCrps().stream()
.filter(s -> s.isActive() && s.getPhase() != null && s.getPhase().equals(this.getSelectedPhase()))
.collect(Collectors.toList());
Set<String> crpsSet = new HashSet<>();
if (studyCrpsList != null && studyCrpsList.size() > 0) {
for (ProjectExpectedStudyCrp studyCrp : studyCrpsList) {
crpsSet.add("<br> ● " + studyCrp.getGlobalUnit().getComposedName());
}
crps = String.join("", crpsSet);
}
// Crp Programs
List<ProjectExpectedStudyFlagship> studyProgramsList =
projectExpectedStudyInfo.getProjectExpectedStudy().getProjectExpectedStudyFlagships().stream()
.filter(s -> s.isActive() && s.getPhase() != null && s.getPhase().equals(this.getSelectedPhase()))
.collect(Collectors.toList());
// Flagships
List<ProjectExpectedStudyFlagship> studyFlagshipList = studyProgramsList.stream()
.filter(f -> f.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue())
.collect(Collectors.toList());
Set<String> flaghipsSet = new HashSet<>();
if (studyFlagshipList != null && studyFlagshipList.size() > 0) {
for (ProjectExpectedStudyFlagship studyFlagship : studyFlagshipList) {
flaghipsSet.add("<br> ● " + studyFlagship.getCrpProgram().getComposedName());
}
flagships = String.join("", flaghipsSet);
}
// Regional Programs
List<ProjectExpectedStudyFlagship> studyRegionsList = studyProgramsList.stream()
.filter(f -> f.getCrpProgram().getProgramType() == ProgramType.REGIONAL_PROGRAM_TYPE.getValue())
.collect(Collectors.toList());
Set<String> regionSet = new HashSet<>();
if (studyRegionsList != null && studyRegionsList.size() > 0) {
for (ProjectExpectedStudyFlagship studyFlagship : studyRegionsList) {
regionSet.add("<br> ● " + studyFlagship.getCrpProgram().getComposedName());
}
regionalPrograms = String.join("", regionSet);
}
// External Partners
List<ProjectExpectedStudyInstitution> studyInstitutionList =
projectExpectedStudyInfo.getProjectExpectedStudy().getProjectExpectedStudyInstitutions().stream()
.filter(s -> s.isActive() && s.getPhase() != null && s.getPhase().equals(this.getSelectedPhase()))
.collect(Collectors.toList());
Set<String> institutionSet = new HashSet<>();
if (studyInstitutionList != null && studyInstitutionList.size() > 0) {
for (ProjectExpectedStudyInstitution studyinstitution : studyInstitutionList) {
institutionSet.add("<br> ● " + studyinstitution.getInstitution().getComposedName());
}
institutions = String.join("", institutionSet);
}
// cgiarInnovations
if (projectExpectedStudyInfo.getCgiarInnovation() != null) {
cgiarInnovation = projectExpectedStudyInfo.getCgiarInnovation();
}
// Innovations
List<ProjectExpectedStudyInnovation> studyInnovationList =
projectExpectedStudyInfo.getProjectExpectedStudy().getProjectExpectedStudyInnovations().stream()
.filter(s -> s.isActive() && s.getPhase() != null && s.getPhase().equals(this.getSelectedPhase()))
.collect(Collectors.toList());
Set<String> innovationSet = new HashSet<>();
if (studyInnovationList != null && studyInnovationList.size() > 0) {
for (ProjectExpectedStudyInnovation studyInnovation : studyInnovationList) {
studyInnovation.getProjectInnovation().getProjectInnovationInfo(this.getSelectedPhase());
innovationSet
.add("<br> ● " + studyInnovation.getProjectInnovation().getComposedName());
}
cgiarInnovations = String.join("", innovationSet);
}
// Elaboration of Outcome/Impact Statement
if (projectExpectedStudyInfo.getElaborationOutcomeImpactStatement() != null
&& !projectExpectedStudyInfo.getElaborationOutcomeImpactStatement().trim().isEmpty()) {
elaborationOutcomeImpactStatement =
htmlParser.plainTextToHtml(projectExpectedStudyInfo.getElaborationOutcomeImpactStatement());
}
// References cited
if (("AR".equals(this.getSelectedPhase().getName()) && 2021 == this.getSelectedPhase().getYear())
|| this.getSelectedPhase().getYear() > 2021) {
if (this.isNotEmpty(projectExpectedStudyInfo.getProjectExpectedStudy().getProjectExpectedStudyReferences())) {
List<ProjectExpectedStudyReference> currentPhaseReferences =
projectExpectedStudyInfo.getProjectExpectedStudy().getProjectExpectedStudyReferences().stream()
.filter(l -> l != null && l.getId() != null && l.getPhase() != null && l.getPhase().getId() != null
&& l.getPhase().equals(this.getSelectedPhase()))
.collect(Collectors.toList());
for (ProjectExpectedStudyReference studyReferenceObject : currentPhaseReferences) {
if (StringUtils.isNotEmpty(studyReferenceObject.getReference())) {
String reference = StringUtils.trimToEmpty(studyReferenceObject.getReference());
referenceText = referenceText.append("• ").append(reference).append("\\r\\n");
}
}
} else {
referenceText = referenceText.append(notProvided);
}
} else {
if (StringUtils.isNotEmpty(
projectExpectedStudyInfo.getProjectExpectedStudy().getProjectExpectedStudyInfo().getReferencesText())) {
/*
* Get short url calling tinyURL service
*/
referenceText = referenceText.append(
projectExpectedStudyInfo.getProjectExpectedStudy().getProjectExpectedStudyInfo().getReferencesText());
} else {
referenceText = referenceText.append(notProvided);
}
}
// TODO: Add Quantifications in Pentaho/MySQL
// Gender, Youth, and Capacity Development
// Gender
if (projectExpectedStudyInfo.getGenderLevel() != null) {
genderRelevance = projectExpectedStudyInfo.getGenderLevel().getPowbName();
if (!projectExpectedStudyInfo.getGenderLevel().getId().equals(1l)
&& !projectExpectedStudyInfo.getGenderLevel().getId().equals(4l)
&& projectExpectedStudyInfo.getDescribeGender() != null
&& !projectExpectedStudyInfo.getDescribeGender().isEmpty()) {
genderRelevance += "<br>" + this.getText("study.achievementsGenderRelevance.readText") + ": "
+ htmlParser.plainTextToHtml(projectExpectedStudyInfo.getDescribeGender());
}
}
// Youth
if (projectExpectedStudyInfo.getYouthLevel() != null) {
youthRelevance = projectExpectedStudyInfo.getYouthLevel().getPowbName();
if (!projectExpectedStudyInfo.getYouthLevel().getId().equals(1l)
&& !projectExpectedStudyInfo.getYouthLevel().getId().equals(4l)
&& projectExpectedStudyInfo.getDescribeYouth() != null
&& !projectExpectedStudyInfo.getDescribeYouth().isEmpty()) {
youthRelevance += "<br>" + this.getText("study.achievementsYouthRelevance.readText") + ": "
+ htmlParser.plainTextToHtml(projectExpectedStudyInfo.getDescribeYouth());
}
}
// Capacity Development
if (projectExpectedStudyInfo.getCapdevLevel() != null) {
capacityRelevance = projectExpectedStudyInfo.getCapdevLevel().getPowbName();
if (!projectExpectedStudyInfo.getCapdevLevel().getId().equals(1l)
&& !projectExpectedStudyInfo.getCapdevLevel().getId().equals(4l)
&& projectExpectedStudyInfo.getDescribeCapdev() != null
&& !projectExpectedStudyInfo.getDescribeCapdev().isEmpty()) {
capacityRelevance += "<br>" + this.getText("study.achievementsCapDevRelevance.readText") + ": "
+ htmlParser.plainTextToHtml(projectExpectedStudyInfo.getDescribeCapdev());
}
}
// Climate change
if (projectExpectedStudyInfo.getClimateChangeLevel() != null) {
climateRelevance = projectExpectedStudyInfo.getClimateChangeLevel().getPowbName();
if (!projectExpectedStudyInfo.getClimateChangeLevel().getId().equals(1l)
&& !projectExpectedStudyInfo.getClimateChangeLevel().getId().equals(4l)
&& projectExpectedStudyInfo.getDescribeClimateChange() != null
&& !projectExpectedStudyInfo.getDescribeClimateChange().isEmpty()) {
climateRelevance += "<br>" + this.getText("study.achievementsClimateChangeRelevance.readText") + ": "
+ htmlParser.plainTextToHtml(projectExpectedStudyInfo.getDescribeClimateChange());
}
}
if (projectExpectedStudyInfo.getOtherCrossCuttingSelection() != null
&& !projectExpectedStudyInfo.getOtherCrossCuttingSelection().isEmpty()) {
otherCrossCuttingDimensionsSelection = projectExpectedStudyInfo.getOtherCrossCuttingSelection();
}
// Other cross-cutting dimensions
if (projectExpectedStudyInfo.getOtherCrossCuttingDimensions() != null
&& !projectExpectedStudyInfo.getOtherCrossCuttingDimensions().trim().isEmpty()) {
otherCrossCuttingDimensions =
htmlParser.plainTextToHtml(projectExpectedStudyInfo.getOtherCrossCuttingDimensions());
if (this.isSelectedPhaseAR2021()) {
otherCrossCuttingDimensions = htmlParser.plainTextToHtml(this.getText("global.AR2021.notRequired"));
}
}
// Contact person
if (projectExpectedStudyInfo.getContacts() != null
&& !projectExpectedStudyInfo.getContacts().trim().isEmpty()) {
contacts = htmlParser.plainTextToHtml(projectExpectedStudyInfo.getContacts());
}
/*
* Generate link url from parameters
*/
if (projectExpectedStudyInfo.getIsPublic() != null && projectExpectedStudyInfo.getIsPublic()
&& projectExpectedStudyInfo.getPhase() != null && this.getBaseUrl() != null) {
link = this.getBaseUrl() + "/projects/" + this.getCrpSession() + "/studySummary.do?studyID="
+ projectExpectedStudyInfo.getProjectExpectedStudy().getId() + "&cycle=Reporting&year="
+ this.getSelectedPhase().getYear();
}
// Projects
List<ExpectedStudyProject> studyProjectList =
projectExpectedStudyInfo.getProjectExpectedStudy().getExpectedStudyProjects().stream()
.filter(e -> e.isActive() && e.getPhase() != null && e.getPhase().equals(this.getSelectedPhase()))
.sorted((sp1, sp2) -> sp2.getProject().getId().compareTo(sp1.getProject().getId()))
.collect(Collectors.toList());
Set<String> studyProjectSet = new HashSet<>();
if (projectExpectedStudyInfo.getProjectExpectedStudy().getProject() != null) {
studyProjectSet.add("<br> ● P"
+ projectExpectedStudyInfo.getProjectExpectedStudy().getProject().getId() + " - " + projectExpectedStudyInfo
.getProjectExpectedStudy().getProject().getProjecInfoPhase(this.getSelectedPhase()).getTitle());
}
if (studyProjectList != null && !studyProjectList.isEmpty()) {
for (ExpectedStudyProject studyProject : studyProjectList) {
if (studyProject.getProject() != null
&& studyProject.getProject().getProjecInfoPhase(this.getSelectedPhase()) != null
&& studyProject.getProject().getProjecInfoPhase(this.getSelectedPhase()).getTitle() != null) {
studyProjectSet.add("<br> ● P" + studyProject.getProject().getId() + " - "
+ studyProject.getProject().getProjecInfoPhase(this.getSelectedPhase()).getTitle());
}
}
}
if (studyProjectSet != null && !studyProjectSet.isEmpty()) {
studyProjects = String.join("", studyProjectSet);
}
model.addRow(
new Object[] {id, year, title, commissioningStudy, status, type, outcomeImpactStatement, isContributionText,
stageStudy, srfTargets, subIdos, topLevelComments, geographicScopes, regions, countries, scopeComments,
crps, flagships, regionalPrograms, institutions, elaborationOutcomeImpactStatement, referenceText,
quantification, genderRelevance, youthRelevance, capacityRelevance, otherCrossCuttingDimensions,
comunicationsMaterial, contacts, studyProjects, tagged, cgiarInnovation, cgiarInnovations, climateRelevance,
link, links, studyPolicies, isSrfTargetText, otherCrossCuttingDimensionsSelection, isContribution,
isRegional, isNational, isOutcomeCaseStudy, isSrfTarget, url, studiesReference});
}
}
return model;
}
}
| CCAFS/MARLO | marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/summaries/BaseStudySummaryData.java | Java | gpl-3.0 | 37,009 |
var util = require('util');
var Publisher = require('clickberry-nsq-publisher');
var Q = require('q');
var publishAsync;
function Bus(options) {
Publisher.call(this, options);
publishAsync = Q.nbind(this.publish, this);
}
util.inherits(Bus, Publisher);
Bus.prototype.publishVideoUpload = function (video, storageSpace, callback) {
Q.all([
publishAsync('video-creates', video),
publishAsync('video-storage-updates', storageSpace)
]).then(function () {
callback();
}).catch(function (err) {
callback(err);
});
};
Bus.prototype.publishVideoRemove = function (video, storageSpace, callback) {
Q.all([
publishAsync('video-deletes', video),
publishAsync('video-storage-updates', storageSpace)
]).then(function(){
callback();
}).catch(function(err){
callback(err);
});
};
module.exports = Bus; | clickberry/videos-api-nodejs | lib/bus-service.js | JavaScript | gpl-3.0 | 895 |
/**
* Copyright (C) 2016 Stuart Howarth <showarth@marxoft.co.uk>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "solvemediarecaptchaplugin.h"
#include "captchatype.h"
#include "json.h"
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#if QT_VERSION < 0x050000
#include <QtPlugin>
#endif
const QString SolveMediaRecaptchaPlugin::CAPTCHA_CHALLENGE_URL("http://api.solvemedia.com/papi/_challenge.js?k=");
const QString SolveMediaRecaptchaPlugin::CAPTCHA_IMAGE_URL("http://api.solvemedia.com/papi/media?c=");
SolveMediaRecaptchaPlugin::SolveMediaRecaptchaPlugin(QObject *parent) :
RecaptchaPlugin(parent),
m_nam(0),
m_ownManager(false)
{
}
QNetworkAccessManager* SolveMediaRecaptchaPlugin::networkAccessManager() {
if (!m_nam) {
m_nam = new QNetworkAccessManager(this);
m_ownManager = true;
}
return m_nam;
}
void SolveMediaRecaptchaPlugin::setNetworkAccessManager(QNetworkAccessManager *manager) {
if (!manager) {
return;
}
if ((m_ownManager) && (m_nam)) {
delete m_nam;
m_nam = 0;
}
m_nam = manager;
m_ownManager = false;
}
bool SolveMediaRecaptchaPlugin::cancelCurrentOperation() {
emit currentOperationCanceled();
return true;
}
void SolveMediaRecaptchaPlugin::getCaptcha(int captchaType, const QString &captchaKey, const QVariantMap &) {
if (captchaType != CaptchaType::Image) {
error(tr("Captcha type %1 not supported").arg(captchaType));
return;
}
QUrl url(CAPTCHA_CHALLENGE_URL + captchaKey);
QNetworkRequest request(url);
QNetworkReply *reply = networkAccessManager()->get(request);
connect(reply, SIGNAL(finished()), this, SLOT(onCaptchaDownloaded()));
connect(this, SIGNAL(currentOperationCanceled()), reply, SLOT(deleteLater()));
}
void SolveMediaRecaptchaPlugin::onCaptchaDownloaded() {
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
if (!reply) {
emit error(tr("Network error"));
return;
}
switch (reply->error()) {
case QNetworkReply::NoError:
break;
case QNetworkReply::OperationCanceledError:
reply->deleteLater();
return;
default:
emit error(reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString());
reply->deleteLater();
return;
}
const QVariantMap map = QtJson::Json::parse(QString::fromUtf8(reply->readAll())).toMap();
reply->deleteLater();
if (map.contains("ACChallengeResult")) {
const QVariantMap result = map.value("ACChallengeResult").toMap();
if (result.contains("chid")) {
const QString challenge = result.value("chid").toString();
if (!challenge.isEmpty()) {
downloadCaptchaImage(challenge);
return;
}
}
}
emit error(tr("No captcha challenge found"));
}
void SolveMediaRecaptchaPlugin::downloadCaptchaImage(const QString &challenge) {
m_challenge = challenge;
QUrl url(CAPTCHA_IMAGE_URL + challenge);
QNetworkRequest request(url);
QNetworkReply *reply = networkAccessManager()->get(request);
connect(reply, SIGNAL(finished()), this, SLOT(onCaptchaImageDownloaded()));
connect(this, SIGNAL(currentOperationCanceled()), reply, SLOT(deleteLater()));
}
void SolveMediaRecaptchaPlugin::onCaptchaImageDownloaded() {
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
if (!reply) {
emit error(tr("Network error"));
return;
}
switch (reply->error()) {
case QNetworkReply::NoError:
break;
case QNetworkReply::OperationCanceledError:
reply->deleteLater();
return;
default:
emit error(reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString());
reply->deleteLater();
return;
}
emit captcha(CaptchaType::Image, QByteArray(m_challenge.toUtf8() + "\n" + reply->readAll().toBase64()));
reply->deleteLater();
}
RecaptchaPlugin* SolveMediaRecaptchaPluginFactory::createPlugin(QObject *parent) {
return new SolveMediaRecaptchaPlugin(parent);
}
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(qdl2-solvemediarecaptcha, SolveMediaRecaptchaPluginFactory)
#endif
| marxoft/qdl2 | plugins/recaptcha/solvemedia/solvemediarecaptchaplugin.cpp | C++ | gpl-3.0 | 4,816 |
/**
* @file: greyhead_customisations.js
*
* Little JS nips and tucks go in here.
*/
var Drupal = Drupal || {};
(function($, Drupal){
"use strict";
/**
* If we're on a node edit page and the URL slug field is present, copy the
* menu title into the URL slug field converted to lowercase alphanumeric-
* only.
*/
Drupal.behaviors.greyheadAutoPopulateURLSlugField = {
attach: function (context, settings) {
// Are we on a node edit/add page?
var nodeFormSelector = 'form.node-form';
var nodeForm = $(nodeFormSelector);
if (nodeForm.length) {
// Do we have a URL slug field?
var urlSlugField = $(nodeFormSelector + ' #edit-field-parapg-url-slug-und-0-value');
if (urlSlugField.length) {
// Yes, we are Go. Add a watcher to add a data-manuallyEdited=yes
// attribute if the field is changed.
urlSlugField.data('manuallyEdited', 'no').blur(function() {
$(this).data('manuallyEdited', 'yes');
});
// Get the node title field.
var nodeTitleField = $(nodeFormSelector + ' #edit-title');
nodeTitleField.blur(function() {
greyheadCopyNodeTitleToURLSlugField($(this).val(), urlSlugField);
});
}
}
/**
* Copy the node title to the menu title if the menu title field doesn't
* have a data-manuallyEdited attribute.
*
* @param nodeTitle
* @param menuTitleField
*/
function greyheadCopyNodeTitleToURLSlugField(nodeTitle, urlSlugField) {
// Is the URL slug field empty?
if (urlSlugField.data('manuallyEdited') !== 'yes') {
var nodeTitleConverted = nodeTitle.replace(/\W/g, '').toLowerCase();
urlSlugField.val(nodeTitleConverted);
}
}
}
};
/**
* If we're on an admin page, get the height of the admin toolbar and set the
* body's top margin accordingly.
*/
Drupal.behaviors.greyheadCorrectBodyMarginForAdminMenu = {
attach: function(context, settings) {
if ($('body', context).hasClass('admin-menu')) {
var height = $('#admin-menu').height();
if (!(height === null) && (height > 0)) {
console.log('Setting body top-margin to ' + height + 'px.');
$('body', context).attr('style', 'margin-top: ' + $('#admin-menu').height() + 'px !important');
}
}
}
};
})(jQuery, Drupal);
| alexharries/greyhead_customisations | js/greyhead_customisations.js | JavaScript | gpl-3.0 | 2,442 |
/**
*
* Copyright (C) 2015 - Daniel Hams, Modular Audio Limited
* daniel.hams@gmail.com
*
* Mad is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Mad is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Mad. If not, see <http://www.gnu.org/licenses/>.
*
*/
package uk.co.modularaudio.util.audio.mad.ioqueue;
import uk.co.modularaudio.util.audio.mad.MadInstance;
public class MadNullLocklessQueueBridge<I extends MadInstance<?, I> >
extends MadLocklessQueueBridge<I>
{
public MadNullLocklessQueueBridge()
{
super( 0, 0, 0, 0 );
}
@Override
public void receiveQueuedEventsToInstance( final I instance, final ThreadSpecificTemporaryEventStorage tses, final long periodTimestamp, final IOQueueEvent queueEvent )
{
}
}
| danielhams/mad-java | 3UTIL/util-audio/src/uk/co/modularaudio/util/audio/mad/ioqueue/MadNullLocklessQueueBridge.java | Java | gpl-3.0 | 1,213 |
////////////////////////////////////////////////////////
//
// GEM - Graphics Environment for Multimedia
//
// Implementation file
//
// Copyright (c) 2002-2011 IOhannes m zmölnig. forum::für::umläute. IEM. zmoelnig@iem.at
// zmoelnig@iem.kug.ac.at
// For information on usage and redistribution, and for a DISCLAIMER
// * OF ALL WARRANTIES, see the file, "GEM.LICENSE.TERMS"
//
// this file has been generated...
////////////////////////////////////////////////////////
#include "GEMglVertex3iv.h"
CPPEXTERN_NEW_WITH_THREE_ARGS ( GEMglVertex3iv , t_floatarg, A_DEFFLOAT, t_floatarg, A_DEFFLOAT, t_floatarg, A_DEFFLOAT);
/////////////////////////////////////////////////////////
//
// GEMglVertex3iv
//
/////////////////////////////////////////////////////////
// Constructor
//
GEMglVertex3iv :: GEMglVertex3iv (t_floatarg arg0=0, t_floatarg arg1=0, t_floatarg arg2=0) {
vMess(arg0, arg1, arg2);
m_inlet = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("v"));
}
/////////////////////////////////////////////////////////
// Destructor
//
GEMglVertex3iv :: ~GEMglVertex3iv () {
inlet_free(m_inlet);
}
/////////////////////////////////////////////////////////
// Render
//
void GEMglVertex3iv :: render(GemState *state) {
glVertex3iv (v);
}
/////////////////////////////////////////////////////////
// variable
//
void GEMglVertex3iv :: vMess (t_float arg0, t_float arg1, t_float arg2) { // FUN
v[0]=static_cast<GLint>(arg0);
v[1]=static_cast<GLint>(arg1);
v[2]=static_cast<GLint>(arg2);
setModified();
}
/////////////////////////////////////////////////////////
// static member functions
//
void GEMglVertex3iv :: obj_setupCallback(t_class *classPtr) {
class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglVertex3iv::vMessCallback), gensym("v"), A_DEFFLOAT, A_DEFFLOAT, A_DEFFLOAT, A_NULL);
}
void GEMglVertex3iv :: vMessCallback (void* data, t_floatarg arg0, t_floatarg arg1, t_floatarg arg2) {
GetMyClass(data)->vMess ( arg0, arg1, arg2);
}
| rvega/morphasynth | vendors/pd-extended-0.43.4/externals/Gem/src/openGL/GEMglVertex3iv.cpp | C++ | gpl-3.0 | 1,990 |
package org.app.portofolio.webui.hr.transaction.employee.model;
import org.module.hr.model.TrsEmployeeDependent;
import org.module.hr.model.dto.RelationshipType;
import org.module.hr.service.EmployeeService;
import org.zkoss.bind.BindUtils;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zkplus.spring.SpringUtil;
import org.zkoss.zul.Button;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
public class DependentListItemRenderer implements ListitemRenderer<TrsEmployeeDependent> {
private EmployeeService employeeService = (EmployeeService) SpringUtil
.getBean("employeeService");
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void render(Listitem item, final TrsEmployeeDependent trsEmployeeDependent, int index) throws Exception {
Listcell listcell;
final Button buttonSave = new Button();
buttonSave.setImage("/images/icons/btn_save.gif");
final Button buttonEdit = new Button();
buttonEdit.setImage("/images/icons/btn_edit.gif");
final Button buttonDelete = new Button();
buttonDelete.setImage("/images/icons/btn_delete.gif");
final Button buttonCancel = new Button();
buttonCancel.setImage("/images/icons/btn_cancel.gif");
final Label labelName = new Label();
final Label labelRelationship = new Label();
final Label labelDateOfBirth = new Label();
final Textbox textboxName = new Textbox();
final Combobox comboboxRelationshipType = new Combobox();
final Datebox dateboxDateOfBirth = new Datebox();
listcell = new Listcell();
buttonEdit.setParent(listcell);
buttonSave.setParent(listcell);
buttonCancel.setParent(listcell);
buttonDelete.setParent(listcell);
listcell.setParent(item);
listcell = new Listcell();
textboxName.setParent(listcell);
labelName.setParent(listcell);
listcell.setParent(item);
listcell = new Listcell();
comboboxRelationshipType.setParent(listcell);
comboboxRelationshipType.setReadonly(true);
labelRelationship.setParent(listcell);
listcell.setParent(item);
listcell = new Listcell();
dateboxDateOfBirth.setParent(listcell);
dateboxDateOfBirth.setReadonly(true);
labelDateOfBirth.setParent(listcell);
listcell.setParent(item);
if (trsEmployeeDependent.getIdDependent() == null){
buttonEdit.setVisible(false);
buttonDelete.setVisible(false);
comboboxRelationshipType.setModel(new ListModelList<RelationshipType>(employeeService.getAllRelationshipType()));
comboboxRelationshipType.setItemRenderer(new RelationshipListItemRenderer());
} else {
buttonSave.setVisible(false);
buttonCancel.setVisible(false);
buttonDelete.setVisible(false);
RelationshipType relationshipType = employeeService.getRelationshipTypeById(trsEmployeeDependent.getRelationship());
labelName.setValue(trsEmployeeDependent.getName());
labelRelationship.setValue(relationshipType.getStpTypname());
labelDateOfBirth.setValue(trsEmployeeDependent.getDateOfBirth() != null ? trsEmployeeDependent.getDateOfBirth().toString() : "");
textboxName.setVisible(false);
comboboxRelationshipType.setVisible(false);
dateboxDateOfBirth.setVisible(false);
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Function CRUD Event
*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
buttonSave.addEventListener(Events.ON_CLICK, new EventListener() {
@Override
public void onEvent(Event event) throws Exception {
if(trsEmployeeDependent.getIdDependent() == null){
Comboitem model = comboboxRelationshipType.getSelectedItem();
RelationshipType RelationshipType = (RelationshipType) model.getAttribute("data");
trsEmployeeDependent.setName(textboxName.getValue());
trsEmployeeDependent.setRelationship(RelationshipType.getStpId());
trsEmployeeDependent.setDateOfBirth(dateboxDateOfBirth.getValue());
employeeService.save(trsEmployeeDependent);
BindUtils.postGlobalCommand(null, null, "refreshAfterSaveOrUpdateEmployeeDependent", null);
}else{
Comboitem model = comboboxRelationshipType.getSelectedItem();
RelationshipType RelationshipType = (RelationshipType) model.getAttribute("data");
trsEmployeeDependent.setName(textboxName.getValue());
trsEmployeeDependent.setRelationship(RelationshipType.getStpId());
trsEmployeeDependent.setDateOfBirth(dateboxDateOfBirth.getValue());
employeeService.update(trsEmployeeDependent);
BindUtils.postGlobalCommand(null, null, "refreshAfterSaveOrUpdateEmployeeDependent", null);
}
}
});
buttonEdit.addEventListener(Events.ON_CLICK, new EventListener() {
public void onEvent(Event event) throws Exception {
buttonEdit.setVisible(false);
buttonSave.setVisible(true);
buttonDelete.setVisible(true);
textboxName.setVisible(true);
comboboxRelationshipType.setVisible(true);
dateboxDateOfBirth.setVisible(true);
labelName.setVisible(false);
labelRelationship.setVisible(false);
labelDateOfBirth.setVisible(false);
textboxName.setValue(trsEmployeeDependent.getName());
dateboxDateOfBirth.setValue(trsEmployeeDependent.getDateOfBirth());
RelationshipType relationshipType = employeeService.getRelationshipTypeById(trsEmployeeDependent.getRelationship());
comboboxRelationshipType.setModel(new ListModelList<RelationshipType>(employeeService.getAllRelationshipType()));
comboboxRelationshipType.setItemRenderer(new RelationshipListItemRenderer());
comboboxRelationshipType.setValue(relationshipType.getStpTypname());
}
});
buttonDelete.addEventListener(Events.ON_CLICK, new EventListener() {
@Override
public void onEvent(Event event) throws Exception {
Messagebox.show("Do you really want to remove item?", "Confirm", Messagebox.OK | Messagebox.CANCEL, Messagebox.EXCLAMATION, new EventListener() {
public void onEvent(Event event) throws Exception {
if (((Integer) event.getData()).intValue() == Messagebox.OK) {
employeeService.delete(trsEmployeeDependent);
BindUtils.postGlobalCommand(null, null, "refreshAfterSaveOrUpdateEmployeeDependent", null);
}else{
return;
}
}
});
}
});
buttonCancel.addEventListener(Events.ON_CLICK, new EventListener() {
@Override
public void onEvent(Event event) throws Exception {
BindUtils.postGlobalCommand(null, null, "refreshAfterSaveOrUpdateEmployeeDependent", null);
}
});
}
}
| sugarpramana/JHRM | Module-Parent/Module-Run/src/main/java/org/app/portofolio/webui/hr/transaction/employee/model/DependentListItemRenderer.java | Java | gpl-3.0 | 7,268 |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HelpersLibrary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jaex")]
[assembly: AssemblyProduct("HelpersLibrary")]
[assembly: AssemblyCopyright("Copyright (C) Jaex")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ff0b4228-8358-45a5-9778-23cf48b81697")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | Jaex/SMBStats | HelpersLibrary/Properties/AssemblyInfo.cs | C# | gpl-3.0 | 1,363 |
# =======================================================================
# Copyright 2013 Christos Sioutis <christos.sioutis@gmail.com>
# =======================================================================
# This file is part of indicator-internode.
#
# indicator-internode is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# indicator-internode is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public
# Licensse along with indicator-internode.
# If not, see <http://www.gnu.org/licenses/>.
# =======================================================================
import gconf
import appindicator as appi
import gtk
GCONF_ROOT = "/apps"
class IndicatorBase(appi.Indicator):
def __init__(self,strAppId, strIconName, strIconThemePath):
self.ind = appi.Indicator(strAppId, strIconName, appi.CATEGORY_APPLICATION_STATUS, strIconThemePath)
self.gc = gconf.client_get_default()
self.ind.set_status (appi.STATUS_ACTIVE)
self.menus = {"root":gtk.Menu()}
self.labels = {}
self.cfgpath = GCONF_ROOT + "/" + strAppId + "/"
def finalize_menu(self):
self.ind.set_menu(self.menus["root"])
def add_submenu(self,strParent,strLabel):
item = gtk.MenuItem(strLabel)
submenu = gtk.Menu()
item.set_submenu(submenu)
self.menus[strLabel] = submenu
self.menus[strParent].append(item)
item.show()
return submenu
def add_btn_menuitem(self,strParent,strLabel):
item = gtk.MenuItem(strLabel)
self.menus[strParent].append(item)
item.connect("activate",self.on_btn_menuitem_activated,strLabel)
item.show()
return item
def on_btn_menuitem_activated(self,gtkMenuItem,strSelection):
print "IndicatorBase.on_cmd_menuitem_activated selection="+strSelection
def add_chk_menuitem(self,strParent,strLabel,boolActive):
item = gtk.CheckMenuItem(strLabel)
if self.get_config(strLabel) == None:
item.set_active(boolActive)
self.set_config(strLabel,str(boolActive))
else:
item.set_active(self.get_config_bool(strLabel))
self.menus[strParent].append(item)
item.connect("toggled",self.on_chk_menuitem_toggled,strLabel)
item.show()
return item
def on_chk_menuitem_toggled(self,gtkMenuItem,strSelection):
self.set_config(strSelection, str(gtkMenuItem.get_active()))
def add_separator(self,strParent):
separator = gtk.SeparatorMenuItem()
separator.show()
self.menus[strParent].append(separator)
def add_lbl_menuitem(self,strParent,strID,strLabel):
item = gtk.MenuItem()
lbl = gtk.Label(strLabel)
self.labels[strID] = lbl
item.add(lbl)
item.show()
self.menus[strParent].append(item)
return item
def set_lbl_menuitem(self,strID,strLabel):
self.labels[strID].set_text(strLabel)
def set_lbl_main(self,strLabel):
self.ind.set_label(strLabel)
def set_icn_main(self,strIconPath):
self.ind.set_icon(strIconPath)
def set_config(self,strKey,strValue):
return self.gc.set_string(str(self.cfgpath)+strKey,strValue)
def get_config(self,strKey):
return self.gc.get_string(str(self.cfgpath)+strKey)
def get_config_bool(self,strKey):
val = self.get_config(strKey)
if val == "True":
return True;
return False
| sioutisc/indicator-internode | src/pynode/indicatorbase.py | Python | gpl-3.0 | 3,516 |
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) Statoil ASA
// Copyright (C) Ceetron Solutions AS
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
//==================================================================================================
///
//==================================================================================================
#include "RigGeoMechWellLogExtractor.h"
#include "RiaDefines.h"
#include "RiaLogging.h"
#include "RiaResultNames.h"
#include "RiaWeightedMeanCalculator.h"
#include "RigFemPart.h"
#include "RigFemPartCollection.h"
#include "RigFemPartResultsCollection.h"
#include "RigFemTypes.h"
#include "RigGeoMechBoreHoleStressCalculator.h"
#include "RigGeoMechCaseData.h"
#include "RiaWellLogUnitTools.h"
#include "RigWellLogExtractionTools.h"
#include "RigWellPath.h"
#include "RigWellPathGeometryTools.h"
#include "RigWellPathIntersectionTools.h"
#include "cafTensor3.h"
#include "cvfGeometryTools.h"
#include "cvfMath.h"
#include <QDebug>
#include <QPolygonF>
#include <type_traits>
const double RigGeoMechWellLogExtractor::PURE_WATER_DENSITY_GCM3 = 1.0; // g / cm^3
const double RigGeoMechWellLogExtractor::GRAVITY_ACCEL = 9.81; // m / s^2
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RigGeoMechWellLogExtractor::RigGeoMechWellLogExtractor( gsl::not_null<RigGeoMechCaseData*> aCase,
gsl::not_null<const RigWellPath*> wellpath,
const std::string& wellCaseErrorMsgName )
: RigWellLogExtractor( wellpath, wellCaseErrorMsgName )
, m_caseData( aCase )
{
calculateIntersection();
m_waterDepth = calculateWaterDepth();
for ( RigWbsParameter parameter : RigWbsParameter::allParameters() )
{
m_parameterSources[parameter] = parameter.sources().front();
m_lasFileValues[parameter] = std::vector<std::pair<double, double>>();
m_userDefinedValues[parameter] = std::numeric_limits<double>::infinity();
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RigGeoMechWellLogExtractor::performCurveDataSmoothing( int frameIndex,
std::vector<double>* mds,
std::vector<double>* tvds,
std::vector<double>* values,
const double smoothingTreshold )
{
CVF_ASSERT( mds && tvds && values );
RigFemPartResultsCollection* resultCollection = m_caseData->femPartResults();
RigFemResultAddress shAddr( RIG_ELEMENT_NODAL, "ST", "S3" );
RigFemResultAddress porBarResAddr( RIG_ELEMENT_NODAL, "POR-Bar", "" );
const std::vector<float>& unscaledShValues = resultCollection->resultValues( shAddr, 0, frameIndex );
const std::vector<float>& porePressures = resultCollection->resultValues( porBarResAddr, 0, frameIndex );
std::vector<float> interfaceShValues = interpolateInterfaceValues( shAddr, frameIndex, unscaledShValues );
std::vector<float> interfacePorePressures = interpolateInterfaceValues( porBarResAddr, frameIndex, porePressures );
std::vector<double> interfaceShValuesDbl( interfaceShValues.size(), std::numeric_limits<double>::infinity() );
std::vector<double> interfacePorePressuresDbl( interfacePorePressures.size(), std::numeric_limits<double>::infinity() );
#pragma omp parallel for
for ( int64_t i = 0; i < int64_t( m_intersections.size() ); ++i )
{
double hydroStaticPorePressureBar = hydroStaticPorePressureForSegment( i );
interfaceShValuesDbl[i] = interfaceShValues[i] / hydroStaticPorePressureBar;
interfacePorePressuresDbl[i] = interfacePorePressures[i];
}
if ( !mds->empty() && !values->empty() )
{
std::vector<unsigned char> smoothOrFilterSegments = determineFilteringOrSmoothing( interfacePorePressuresDbl );
smoothSegments( mds, tvds, values, interfaceShValuesDbl, smoothOrFilterSegments, smoothingTreshold );
}
}
//--------------------------------------------------------------------------------------------------
/// Get curve data for a given parameter. Returns the output units of the data.
//--------------------------------------------------------------------------------------------------
QString RigGeoMechWellLogExtractor::curveData( const RigFemResultAddress& resAddr, int frameIndex, std::vector<double>* values )
{
CVF_TIGHT_ASSERT( values );
if ( resAddr.resultPosType == RIG_WELLPATH_DERIVED )
{
if ( m_wellPathGeometry->rkbDiff() == HUGE_VAL )
{
RiaLogging::error( "Well path has an invalid datum elevation and we cannot estimate TVDRKB. No well bore "
"stability curves created." );
return "";
}
if ( !isValid( m_waterDepth ) )
{
RiaLogging::error( "Well path does not intersect with sea floor. No well bore "
"stability curves created." );
return "";
}
if ( resAddr.fieldName == RiaResultNames::wbsFGResult().toStdString() )
{
wellBoreWallCurveData( resAddr, frameIndex, values );
// Try to replace invalid values with Shale-values
wellBoreFGShale( frameIndex, values );
values->front() = wbsCurveValuesAtMsl();
}
else if ( resAddr.fieldName == RiaResultNames::wbsSFGResult().toStdString() )
{
wellBoreWallCurveData( resAddr, frameIndex, values );
}
else if ( resAddr.fieldName == RiaResultNames::wbsPPResult().toStdString() ||
resAddr.fieldName == RiaResultNames::wbsOBGResult().toStdString() ||
resAddr.fieldName == RiaResultNames::wbsSHResult().toStdString() )
{
wellPathScaledCurveData( resAddr, frameIndex, values );
values->front() = wbsCurveValuesAtMsl();
}
else if ( resAddr.fieldName == RiaResultNames::wbsAzimuthResult().toStdString() ||
resAddr.fieldName == RiaResultNames::wbsInclinationResult().toStdString() )
{
wellPathAngles( resAddr, values );
}
else if ( resAddr.fieldName == RiaResultNames::wbsSHMkResult().toStdString() )
{
wellBoreSH_MatthewsKelly( frameIndex, values );
values->front() = wbsCurveValuesAtMsl();
}
else
{
// Plotting parameters as curves
RigWbsParameter param;
if ( RigWbsParameter::findParameter( QString::fromStdString( resAddr.fieldName ), ¶m ) )
{
if ( param == RigWbsParameter::FG_Shale() )
{
wellBoreFGShale( frameIndex, values );
}
else
{
if ( param == RigWbsParameter::OBG0() )
{
frameIndex = 0;
}
calculateWbsParameterForAllSegments( param, frameIndex, values, true );
if ( param == RigWbsParameter::UCS() ) // UCS is reported as UCS/100
{
for ( double& value : *values )
{
if ( isValid( value ) ) value /= 100.0;
}
return RiaWellLogUnitTools<double>::barX100UnitString();
}
else if ( param == RigWbsParameter::DF() || param == RigWbsParameter::poissonRatio() )
{
return RiaWellLogUnitTools<double>::noUnitString();
}
}
}
}
return RiaWellLogUnitTools<double>::sg_emwUnitString();
}
else if ( resAddr.isValid() )
{
RigFemResultAddress convResAddr = resAddr;
// When showing POR results, always use the element nodal result,
// to get correct handling of elements without POR results
if ( convResAddr.fieldName == "POR-Bar" ) convResAddr.resultPosType = RIG_ELEMENT_NODAL;
CVF_ASSERT( resAddr.resultPosType != RIG_WELLPATH_DERIVED );
const std::vector<float>& resultValues = m_caseData->femPartResults()->resultValues( convResAddr, 0, frameIndex );
if ( !resultValues.empty() )
{
std::vector<float> interfaceValues = interpolateInterfaceValues( convResAddr, frameIndex, resultValues );
values->resize( interfaceValues.size(), std::numeric_limits<double>::infinity() );
#pragma omp parallel for
for ( int64_t intersectionIdx = 0; intersectionIdx < (int64_t)m_intersections.size(); ++intersectionIdx )
{
( *values )[intersectionIdx] = static_cast<double>( interfaceValues[intersectionIdx] );
}
}
}
return RiaWellLogUnitTools<double>::barUnitString();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<RigGeoMechWellLogExtractor::WbsParameterSource>
RigGeoMechWellLogExtractor::calculateWbsParameterForAllSegments( const RigWbsParameter& parameter,
WbsParameterSource primarySource,
int frameIndex,
std::vector<double>* outputValues,
bool allowNormalization )
{
RigFemPartResultsCollection* resultCollection = m_caseData->femPartResults();
std::vector<WbsParameterSource> finalSourcesPerSegment( m_intersections.size(), RigWbsParameter::UNDEFINED );
if ( primarySource == RigWbsParameter::UNDEFINED )
{
return finalSourcesPerSegment;
}
bool isPPResResult = parameter == RigWbsParameter::PP_Reservoir();
bool isPPresult = isPPResResult || parameter == RigWbsParameter::PP_NonReservoir();
std::vector<WbsParameterSource> allSources = parameter.sources();
auto primary_it = std::find( allSources.begin(), allSources.end(), primarySource );
CVF_ASSERT( primary_it != allSources.end() );
std::vector<double> gridValues;
if ( std::find( allSources.begin(), allSources.end(), RigWbsParameter::GRID ) != allSources.end() ||
parameter == RigWbsParameter::PP_Reservoir() )
{
RigFemResultAddress nativeAddr = parameter.femAddress( RigWbsParameter::GRID );
const std::vector<float>& unscaledResultValues = resultCollection->resultValues( nativeAddr, 0, frameIndex );
std::vector<float> interpolatedInterfaceValues =
interpolateInterfaceValues( nativeAddr, frameIndex, unscaledResultValues );
gridValues.resize( m_intersections.size(), std::numeric_limits<double>::infinity() );
#pragma omp parallel for
for ( int64_t intersectionIdx = 0; intersectionIdx < (int64_t)m_intersections.size(); ++intersectionIdx )
{
float averageUnscaledValue = std::numeric_limits<float>::infinity();
averageIntersectionValuesToSegmentValue( intersectionIdx,
interpolatedInterfaceValues,
std::numeric_limits<float>::infinity(),
&averageUnscaledValue );
gridValues[intersectionIdx] = static_cast<double>( averageUnscaledValue );
}
}
const std::vector<std::pair<double, double>>& lasFileValues = m_lasFileValues.at( parameter );
const double& userDefinedValue = m_userDefinedValues.at( parameter );
std::vector<float> elementPropertyValues;
if ( std::find( allSources.begin(), allSources.end(), RigWbsParameter::ELEMENT_PROPERTY_TABLE ) != allSources.end() )
{
const std::vector<float>* elementPropertyValuesInput = nullptr;
std::vector<float> tvdRKBs;
for ( double tvdValue : m_intersectionTVDs )
{
tvdRKBs.push_back( tvdValue + m_wellPathGeometry->rkbDiff() );
}
RigFemResultAddress elementPropertyAddr = parameter.femAddress( RigWbsParameter::ELEMENT_PROPERTY_TABLE );
elementPropertyValuesInput = &( resultCollection->resultValues( elementPropertyAddr, 0, frameIndex ) );
if ( elementPropertyValuesInput )
{
RiaWellLogUnitTools<float>::convertValues( tvdRKBs,
*elementPropertyValuesInput,
&elementPropertyValues,
parameter.units( RigWbsParameter::ELEMENT_PROPERTY_TABLE ),
parameterInputUnits( parameter ) );
}
}
std::vector<double> unscaledValues( m_intersections.size(), std::numeric_limits<double>::infinity() );
double waterDensityGCM3 = m_userDefinedValues[RigWbsParameter::waterDensity()];
for ( int64_t intersectionIdx = 0; intersectionIdx < (int64_t)m_intersections.size(); ++intersectionIdx )
{
// Loop from primary source and out for each value
for ( auto it = primary_it; it != allSources.end(); ++it )
{
if ( *it == RigWbsParameter::GRID ) // Priority 0: Grid
{
if ( intersectionIdx < (int64_t)gridValues.size() &&
gridValues[intersectionIdx] != std::numeric_limits<double>::infinity() )
{
unscaledValues[intersectionIdx] = gridValues[intersectionIdx];
finalSourcesPerSegment[intersectionIdx] = RigWbsParameter::GRID;
break;
}
}
else if ( *it == RigWbsParameter::LAS_FILE ) // Priority 1: Las-file value
{
if ( !lasFileValues.empty() )
{
double lasValue = getWellLogIntersectionValue( intersectionIdx, lasFileValues );
// Only accept las-values for PP_reservoir if the grid result is valid
bool validLasRegion = true;
if ( isPPResResult )
{
validLasRegion = intersectionIdx < static_cast<int64_t>( gridValues.size() ) &&
gridValues[intersectionIdx] != std::numeric_limits<double>::infinity();
}
if ( validLasRegion && lasValue != std::numeric_limits<double>::infinity() )
{
unscaledValues[intersectionIdx] = lasValue;
finalSourcesPerSegment[intersectionIdx] = RigWbsParameter::LAS_FILE;
break;
}
}
}
else if ( *it == RigWbsParameter::ELEMENT_PROPERTY_TABLE ) // Priority 2: Element property table value
{
if ( !elementPropertyValues.empty() )
{
size_t elmIdx = m_intersectedCellsGlobIdx[intersectionIdx];
if ( elmIdx < elementPropertyValues.size() )
{
unscaledValues[intersectionIdx] = elementPropertyValues[elmIdx];
finalSourcesPerSegment[intersectionIdx] = RigWbsParameter::ELEMENT_PROPERTY_TABLE;
break;
}
}
}
else if ( *it == RigWbsParameter::HYDROSTATIC && isPPresult )
{
unscaledValues[intersectionIdx] =
userDefinedValue * hydroStaticPorePressureForIntersection( intersectionIdx, waterDensityGCM3 );
finalSourcesPerSegment[intersectionIdx] = RigWbsParameter::HYDROSTATIC;
break;
}
else if ( *it == RigWbsParameter::USER_DEFINED )
{
unscaledValues[intersectionIdx] = userDefinedValue;
finalSourcesPerSegment[intersectionIdx] = RigWbsParameter::USER_DEFINED;
break;
}
}
}
if ( allowNormalization && parameter.normalizeByHydrostaticPP() )
{
outputValues->resize( unscaledValues.size(), std::numeric_limits<double>::infinity() );
#pragma omp parallel for
for ( int64_t intersectionIdx = 0; intersectionIdx < (int64_t)m_intersections.size(); ++intersectionIdx )
{
RigWbsParameter::Source source = finalSourcesPerSegment[intersectionIdx];
if ( source == RigWbsParameter::ELEMENT_PROPERTY_TABLE || source == RigWbsParameter::GRID )
{
( *outputValues )[intersectionIdx] =
unscaledValues[intersectionIdx] / hydroStaticPorePressureForSegment( intersectionIdx );
}
else
{
( *outputValues )[intersectionIdx] =
unscaledValues[intersectionIdx] / hydroStaticPorePressureForIntersection( intersectionIdx );
}
}
}
else
{
outputValues->swap( unscaledValues );
}
return finalSourcesPerSegment;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<RigGeoMechWellLogExtractor::WbsParameterSource>
RigGeoMechWellLogExtractor::calculateWbsParameterForAllSegments( const RigWbsParameter& parameter,
int frameIndex,
std::vector<double>* outputValues,
bool allowNormalization )
{
return calculateWbsParameterForAllSegments( parameter,
m_parameterSources.at( parameter ),
frameIndex,
outputValues,
allowNormalization );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<RigGeoMechWellLogExtractor::WbsParameterSource>
RigGeoMechWellLogExtractor::calculateWbsParametersForAllSegments( const RigFemResultAddress& resAddr,
int frameIndex,
std::vector<double>* values,
bool allowNormalization )
{
CVF_ASSERT( values );
RigWbsParameter param;
if ( !RigWbsParameter::findParameter( QString::fromStdString( resAddr.fieldName ), ¶m ) )
{
CVF_ASSERT( false && "wbsParameters() called on something that isn't a wbs parameter" );
}
return calculateWbsParameterForAllSegments( param, m_userDefinedValues.at( param ), values, allowNormalization );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RigGeoMechWellLogExtractor::wellPathAngles( const RigFemResultAddress& resAddr, std::vector<double>* values )
{
CVF_ASSERT( values );
CVF_ASSERT( resAddr.fieldName == "Azimuth" || resAddr.fieldName == "Inclination" );
values->resize( m_intersections.size(), 0.0f );
const double epsilon = 1.0e-6 * 360;
const cvf::Vec3d trueNorth( 0.0, 1.0, 0.0 );
const cvf::Vec3d up( 0.0, 0.0, 1.0 );
double previousAzimuth = 0.0;
for ( int64_t intersectionIdx = 0; intersectionIdx < (int64_t)m_intersections.size(); ++intersectionIdx )
{
cvf::Vec3d wellPathTangent = calculateWellPathTangent( intersectionIdx, TangentFollowWellPathSegments );
// Deviation from vertical. Since well path is tending downwards we compare with negative z.
double inclination =
cvf::Math::toDegrees( std::acos( cvf::Vec3d( 0.0, 0.0, -1.0 ) * wellPathTangent.getNormalized() ) );
if ( resAddr.fieldName == "Azimuth" )
{
double azimuth = HUGE_VAL;
// Azimuth is not defined when well path is vertical. We define it as infinite to avoid it showing up in the
// plot.
if ( cvf::Math::valueInRange( inclination, epsilon, 180.0 - epsilon ) )
{
cvf::Vec3d projectedTangentXY = wellPathTangent;
projectedTangentXY.z() = 0.0;
// Do tangentXY to true north for clockwise angles.
double dotProduct = projectedTangentXY * trueNorth;
double crossProduct = ( projectedTangentXY ^ trueNorth ) * up;
// http://www.glossary.oilfield.slb.com/Terms/a/azimuth.aspx
azimuth = cvf::Math::toDegrees( std::atan2( crossProduct, dotProduct ) );
if ( azimuth < 0.0 )
{
// Straight atan2 gives angle from -PI to PI yielding angles from -180 to 180
// where the negative angles are counter clockwise.
// To get all positive clockwise angles, we add 360 degrees to negative angles.
azimuth = azimuth + 360.0;
}
}
// Make azimuth continuous in most cases
if ( azimuth - previousAzimuth > 300.0 )
{
azimuth -= 360.0;
}
else if ( previousAzimuth - azimuth > 300.0 )
{
azimuth += 360.0;
}
( *values )[intersectionIdx] = azimuth;
previousAzimuth = azimuth;
}
else
{
( *values )[intersectionIdx] = inclination;
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<RigGeoMechWellLogExtractor::WbsParameterSource>
RigGeoMechWellLogExtractor::wellPathScaledCurveData( const RigFemResultAddress& resAddr,
int frameIndex,
std::vector<double>* values,
bool forceGridSourceForPPReservoir /*=false*/ )
{
CVF_ASSERT( values );
values->resize( m_intersections.size(), std::numeric_limits<double>::infinity() );
std::vector<WbsParameterSource> sources( m_intersections.size(), RigWbsParameter::UNDEFINED );
if ( resAddr.fieldName == RiaResultNames::wbsPPResult().toStdString() )
{
// Las or element property table values
std::vector<double> ppSandValues( m_intersections.size(), std::numeric_limits<double>::infinity() );
std::vector<double> ppShaleValues( m_intersections.size(), std::numeric_limits<double>::infinity() );
std::vector<WbsParameterSource> ppSandSources;
if ( forceGridSourceForPPReservoir )
{
ppSandSources = calculateWbsParameterForAllSegments( RigWbsParameter::PP_Reservoir(),
RigWbsParameter::GRID,
frameIndex,
&ppSandValues,
true );
}
else
{
ppSandSources =
calculateWbsParameterForAllSegments( RigWbsParameter::PP_Reservoir(), frameIndex, &ppSandValues, true );
}
std::vector<WbsParameterSource> ppShaleSources =
calculateWbsParameterForAllSegments( RigWbsParameter::PP_NonReservoir(), 0, &ppShaleValues, true );
#pragma omp parallel for
for ( int64_t intersectionIdx = 0; intersectionIdx < (int64_t)m_intersections.size(); ++intersectionIdx )
{
if ( ( *values )[intersectionIdx] == std::numeric_limits<double>::infinity() )
{
if ( ppSandValues[intersectionIdx] != std::numeric_limits<double>::infinity() )
{
( *values )[intersectionIdx] = ppSandValues[intersectionIdx];
sources[intersectionIdx] = ppSandSources[intersectionIdx];
}
else if ( ppShaleValues[intersectionIdx] != std::numeric_limits<double>::infinity() )
{
( *values )[intersectionIdx] = ppShaleValues[intersectionIdx];
sources[intersectionIdx] = ppShaleSources[intersectionIdx];
}
else
{
( *values )[intersectionIdx] = 1.0;
sources[intersectionIdx] = RigWbsParameter::HYDROSTATIC;
}
}
}
}
else if ( resAddr.fieldName == RiaResultNames::wbsOBGResult().toStdString() )
{
sources = calculateWbsParameterForAllSegments( RigWbsParameter::OBG(), frameIndex, values, true );
}
else
{
sources = calculateWbsParameterForAllSegments( RigWbsParameter::SH(), frameIndex, values, true );
}
return sources;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RigGeoMechWellLogExtractor::wellBoreWallCurveData( const RigFemResultAddress& resAddr,
int frameIndex,
std::vector<double>* values )
{
CVF_ASSERT( values );
CVF_ASSERT( resAddr.fieldName == RiaResultNames::wbsFGResult().toStdString() ||
resAddr.fieldName == RiaResultNames::wbsSFGResult().toStdString() );
// The result addresses needed
RigFemResultAddress stressResAddr( RIG_ELEMENT_NODAL, "ST", "" );
RigFemResultAddress porBarResAddr( RIG_ELEMENT_NODAL, "POR-Bar", "" );
RigFemPartResultsCollection* resultCollection = m_caseData->femPartResults();
// Load results
std::vector<caf::Ten3f> vertexStressesFloat = resultCollection->tensors( stressResAddr, 0, frameIndex );
if ( !vertexStressesFloat.size() ) return;
std::vector<caf::Ten3d> vertexStresses;
vertexStresses.reserve( vertexStressesFloat.size() );
for ( const caf::Ten3f& floatTensor : vertexStressesFloat )
{
vertexStresses.push_back( caf::Ten3d( floatTensor ) );
}
std::vector<caf::Ten3d> interpolatedInterfaceStressBar =
interpolateInterfaceValues( stressResAddr, frameIndex, vertexStresses );
values->resize( m_intersections.size(), std::numeric_limits<float>::infinity() );
std::vector<double> ppSandAllSegments( m_intersections.size(), std::numeric_limits<double>::infinity() );
std::vector<WbsParameterSource> ppSources = calculateWbsParameterForAllSegments( RigWbsParameter::PP_Reservoir(),
RigWbsParameter::GRID,
frameIndex,
&ppSandAllSegments,
false );
std::vector<double> poissonAllSegments( m_intersections.size(), std::numeric_limits<double>::infinity() );
calculateWbsParameterForAllSegments( RigWbsParameter::poissonRatio(), frameIndex, &poissonAllSegments, false );
std::vector<double> ucsAllSegments( m_intersections.size(), std::numeric_limits<double>::infinity() );
calculateWbsParameterForAllSegments( RigWbsParameter::UCS(), frameIndex, &ucsAllSegments, false );
#pragma omp parallel for
for ( int64_t intersectionIdx = 0; intersectionIdx < (int64_t)m_intersections.size(); ++intersectionIdx )
{
// FG is for sands, SFG for shale. Sands has valid PP, shale does not.
bool isFGregion = ppSources[intersectionIdx] == RigWbsParameter::GRID;
double hydroStaticPorePressureBar = hydroStaticPorePressureForSegment( intersectionIdx );
double porePressureBar = ppSandAllSegments[intersectionIdx];
if ( porePressureBar == std::numeric_limits<double>::infinity() )
{
porePressureBar = hydroStaticPorePressureBar;
}
double poissonRatio = poissonAllSegments[intersectionIdx];
double ucsBar = ucsAllSegments[intersectionIdx];
caf::Ten3d segmentStress;
bool validSegmentStress = averageIntersectionValuesToSegmentValue( intersectionIdx,
interpolatedInterfaceStressBar,
caf::Ten3d::invalid(),
&segmentStress );
cvf::Vec3d wellPathTangent = calculateWellPathTangent( intersectionIdx, TangentConstantWithinCell );
caf::Ten3d wellPathStressFloat = transformTensorToWellPathOrientation( wellPathTangent, segmentStress );
caf::Ten3d wellPathStressDouble( wellPathStressFloat );
RigGeoMechBoreHoleStressCalculator sigmaCalculator( wellPathStressDouble, porePressureBar, poissonRatio, ucsBar, 32 );
double resultValue = std::numeric_limits<double>::infinity();
if ( resAddr.fieldName == RiaResultNames::wbsFGResult().toStdString() )
{
if ( isFGregion && validSegmentStress )
{
resultValue = sigmaCalculator.solveFractureGradient();
}
}
else
{
CVF_ASSERT( resAddr.fieldName == RiaResultNames::wbsSFGResult().toStdString() );
if ( !isFGregion && validSegmentStress )
{
resultValue = sigmaCalculator.solveStassiDalia();
}
}
if ( resultValue != std::numeric_limits<double>::infinity() )
{
if ( hydroStaticPorePressureBar > 1.0e-8 )
{
resultValue /= hydroStaticPorePressureBar;
}
}
( *values )[intersectionIdx] = resultValue;
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RigGeoMechWellLogExtractor::wellBoreFGShale( int frameIndex, std::vector<double>* values )
{
if ( values->empty() ) values->resize( m_intersections.size(), std::numeric_limits<double>::infinity() );
WbsParameterSource source = m_parameterSources.at( RigWbsParameter::FG_Shale() );
if ( source == RigWbsParameter::DERIVED_FROM_K0FG )
{
std::vector<double> PP0; // results
std::vector<double> K0_FG, OBG0; // parameters
RigFemResultAddress ppAddr( RIG_WELLPATH_DERIVED, RiaResultNames::wbsPPResult().toStdString(), "" );
wellPathScaledCurveData( ppAddr, 0, &PP0, true );
calculateWbsParameterForAllSegments( RigWbsParameter::K0_FG(), frameIndex, &K0_FG, true );
calculateWbsParameterForAllSegments( RigWbsParameter::OBG0(), 0, &OBG0, true );
#pragma omp parallel for
for ( int64_t intersectionIdx = 0; intersectionIdx < (int64_t)m_intersections.size(); ++intersectionIdx )
{
if ( !isValid( ( *values )[intersectionIdx] ) )
{
if ( isValid( PP0[intersectionIdx] ) && isValid( OBG0[intersectionIdx] ) &&
isValid( K0_FG[intersectionIdx] ) )
{
( *values )[intersectionIdx] =
( K0_FG[intersectionIdx] * ( OBG0[intersectionIdx] - PP0[intersectionIdx] ) + PP0[intersectionIdx] );
}
}
}
}
else
{
std::vector<double> SH;
calculateWbsParameterForAllSegments( RigWbsParameter::SH(), frameIndex, &SH, true );
CVF_ASSERT( SH.size() == m_intersections.size() );
double multiplier = m_userDefinedValues.at( RigWbsParameter::FG_Shale() );
CVF_ASSERT( multiplier != std::numeric_limits<double>::infinity() );
#pragma omp parallel for
for ( int64_t intersectionIdx = 0; intersectionIdx < (int64_t)m_intersections.size(); ++intersectionIdx )
{
if ( !isValid( ( *values )[intersectionIdx] ) )
{
if ( isValid( SH[intersectionIdx] ) )
{
( *values )[intersectionIdx] = SH[intersectionIdx] * multiplier;
}
}
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RigGeoMechWellLogExtractor::wellBoreSH_MatthewsKelly( int frameIndex, std::vector<double>* values )
{
std::vector<double> PP, PP0; // results
std::vector<double> K0_SH, OBG0, DF; // parameters
RigFemResultAddress ppAddr( RIG_WELLPATH_DERIVED, RiaResultNames::wbsPPResult().toStdString(), "" );
curveData( ppAddr, frameIndex, &PP );
curveData( ppAddr, 0, &PP0 );
calculateWbsParameterForAllSegments( RigWbsParameter::K0_SH(), frameIndex, &K0_SH, true );
calculateWbsParameterForAllSegments( RigWbsParameter::OBG0(), 0, &OBG0, true );
calculateWbsParameterForAllSegments( RigWbsParameter::DF(), frameIndex, &DF, true );
values->resize( m_intersections.size(), std::numeric_limits<double>::infinity() );
#pragma omp parallel for
for ( int64_t intersectionIdx = 0; intersectionIdx < (int64_t)m_intersections.size(); ++intersectionIdx )
{
if ( isValid( PP[intersectionIdx] ) && isValid( PP0[intersectionIdx] ) && isValid( OBG0[intersectionIdx] ) &&
isValid( K0_SH[intersectionIdx] ) && isValid( DF[intersectionIdx] ) )
{
( *values )[intersectionIdx] =
( K0_SH[intersectionIdx] * ( OBG0[intersectionIdx] - PP0[intersectionIdx] ) + PP0[intersectionIdx] +
DF[intersectionIdx] * ( PP[intersectionIdx] - PP0[intersectionIdx] ) );
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
const RigGeoMechCaseData* RigGeoMechWellLogExtractor::caseData()
{
return m_caseData.p();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RigGeoMechWellLogExtractor::setWbsLasValues( const RigWbsParameter& parameter,
const std::vector<std::pair<double, double>>& values )
{
m_lasFileValues[parameter] = values;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RigGeoMechWellLogExtractor::setWbsParametersSource( RigWbsParameter parameter, WbsParameterSource source )
{
m_parameterSources[parameter] = source;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RigGeoMechWellLogExtractor::setWbsUserDefinedValue( RigWbsParameter parameter, double userDefinedValue )
{
m_userDefinedValues[parameter] = userDefinedValue;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RigGeoMechWellLogExtractor::parameterInputUnits( const RigWbsParameter& parameter )
{
if ( parameter == RigWbsParameter::PP_NonReservoir() || parameter == RigWbsParameter::PP_Reservoir() ||
parameter == RigWbsParameter::UCS() )
{
return RiaWellLogUnitTools<double>::barUnitString();
}
else if ( parameter == RigWbsParameter::poissonRatio() || parameter == RigWbsParameter::DF() )
{
return RiaWellLogUnitTools<double>::noUnitString();
}
else if ( parameter == RigWbsParameter::waterDensity() )
{
return RiaWellLogUnitTools<double>::gPerCm3UnitString();
}
return RiaWellLogUnitTools<double>::sg_emwUnitString();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<double> RigGeoMechWellLogExtractor::porePressureSourceRegions( int frameIndex )
{
RigFemResultAddress ppResAddr( RIG_ELEMENT_NODAL, RiaResultNames::wbsPPResult().toStdString(), "" );
std::vector<double> values;
std::vector<WbsParameterSource> sources = wellPathScaledCurveData( ppResAddr, frameIndex, &values );
std::vector<double> doubleSources( sources.size(), 0.0 );
#pragma omp parallel for
for ( int64_t intersectionIdx = 0; intersectionIdx < (int64_t)m_intersections.size(); ++intersectionIdx )
{
doubleSources[intersectionIdx] = static_cast<double>( sources[intersectionIdx] );
}
return doubleSources;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<double> RigGeoMechWellLogExtractor::poissonSourceRegions( int frameIndex )
{
std::vector<double> outputValues;
std::vector<WbsParameterSource> sources =
calculateWbsParameterForAllSegments( RigWbsParameter::poissonRatio(), frameIndex, &outputValues, false );
std::vector<double> doubleSources( sources.size(), 0.0 );
#pragma omp parallel for
for ( int64_t intersectionIdx = 0; intersectionIdx < (int64_t)m_intersections.size(); ++intersectionIdx )
{
doubleSources[intersectionIdx] = static_cast<double>( sources[intersectionIdx] );
}
return doubleSources;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<double> RigGeoMechWellLogExtractor::ucsSourceRegions( int frameIndex )
{
std::vector<double> outputValues;
std::vector<WbsParameterSource> sources =
calculateWbsParameterForAllSegments( RigWbsParameter::UCS(), frameIndex, &outputValues, true );
std::vector<double> doubleSources( sources.size(), 0.0 );
#pragma omp parallel for
for ( int64_t intersectionIdx = 0; intersectionIdx < (int64_t)m_intersections.size(); ++intersectionIdx )
{
doubleSources[intersectionIdx] = static_cast<double>( sources[intersectionIdx] );
}
return doubleSources;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template <typename T>
T RigGeoMechWellLogExtractor::interpolateGridResultValue( RigFemResultPosEnum resultPosType,
const std::vector<T>& gridResultValues,
int64_t intersectionIdx ) const
{
const RigFemPart* femPart = m_caseData->femParts()->part( 0 );
const std::vector<cvf::Vec3f>& nodeCoords = femPart->nodes().coordinates;
size_t elmIdx = m_intersectedCellsGlobIdx[intersectionIdx];
RigElementType elmType = femPart->elementType( elmIdx );
if ( !( elmType == HEX8 || elmType == HEX8P ) ) return T();
if ( resultPosType == RIG_FORMATION_NAMES )
{
resultPosType = RIG_ELEMENT_NODAL; // formation indices are stored per element node result.
}
if ( resultPosType == RIG_ELEMENT )
{
return gridResultValues[elmIdx];
}
cvf::StructGridInterface::FaceType cellFace = m_intersectedCellFaces[intersectionIdx];
if ( cellFace == cvf::StructGridInterface::NO_FACE )
{
if ( resultPosType == RIG_ELEMENT_NODAL_FACE )
{
return std::numeric_limits<T>::infinity(); // undefined value. ELEMENT_NODAL_FACE values are only defined on
// a face.
}
// TODO: Should interpolate within the whole hexahedron. This requires converting to locals coordinates.
// For now just pick the average value for the cell.
size_t gridResultValueIdx =
femPart->resultValueIdxFromResultPosType( resultPosType, static_cast<int>( elmIdx ), 0 );
T sumOfVertexValues = gridResultValues[gridResultValueIdx];
for ( int i = 1; i < 8; ++i )
{
gridResultValueIdx = femPart->resultValueIdxFromResultPosType( resultPosType, static_cast<int>( elmIdx ), i );
sumOfVertexValues = sumOfVertexValues + gridResultValues[gridResultValueIdx];
}
return sumOfVertexValues * ( 1.0 / 8.0 );
}
int faceNodeCount = 0;
const int* elementLocalIndicesForFace = RigFemTypes::localElmNodeIndicesForFace( elmType, cellFace, &faceNodeCount );
const int* elmNodeIndices = femPart->connectivities( elmIdx );
cvf::Vec3d v0( nodeCoords[elmNodeIndices[elementLocalIndicesForFace[0]]] );
cvf::Vec3d v1( nodeCoords[elmNodeIndices[elementLocalIndicesForFace[1]]] );
cvf::Vec3d v2( nodeCoords[elmNodeIndices[elementLocalIndicesForFace[2]]] );
cvf::Vec3d v3( nodeCoords[elmNodeIndices[elementLocalIndicesForFace[3]]] );
std::vector<size_t> nodeResIdx( 4, cvf::UNDEFINED_SIZE_T );
for ( size_t i = 0; i < nodeResIdx.size(); ++i )
{
if ( resultPosType == RIG_ELEMENT_NODAL_FACE )
{
nodeResIdx[i] = gridResultIndexFace( elmIdx, cellFace, static_cast<int>( i ) );
}
else
{
nodeResIdx[i] = femPart->resultValueIdxFromResultPosType( resultPosType,
static_cast<int>( elmIdx ),
elementLocalIndicesForFace[i] );
}
}
std::vector<T> nodeResultValues;
nodeResultValues.reserve( 4 );
for ( size_t i = 0; i < nodeResIdx.size(); ++i )
{
nodeResultValues.push_back( gridResultValues[nodeResIdx[i]] );
}
T interpolatedValue = cvf::GeometryTools::interpolateQuad<T>( v0,
nodeResultValues[0],
v1,
nodeResultValues[1],
v2,
nodeResultValues[2],
v3,
nodeResultValues[3],
m_intersections[intersectionIdx] );
return interpolatedValue;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
size_t RigGeoMechWellLogExtractor::gridResultIndexFace( size_t elementIdx,
cvf::StructGridInterface::FaceType cellFace,
int faceLocalNodeIdx ) const
{
CVF_ASSERT( cellFace != cvf::StructGridInterface::NO_FACE && faceLocalNodeIdx < 4 );
return elementIdx * 24 + static_cast<int>( cellFace ) * 4 + faceLocalNodeIdx;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RigGeoMechWellLogExtractor::calculateIntersection()
{
CVF_ASSERT( m_caseData->femParts()->partCount() == 1 );
std::map<RigMDCellIdxEnterLeaveKey, HexIntersectionInfo> uniqueIntersections;
const RigFemPart* femPart = m_caseData->femParts()->part( 0 );
const std::vector<cvf::Vec3f>& nodeCoords = femPart->nodes().coordinates;
for ( size_t wpp = 0; wpp < m_wellPathGeometry->wellPathPoints().size() - 1; ++wpp )
{
std::vector<HexIntersectionInfo> intersections;
cvf::Vec3d p1 = m_wellPathGeometry->wellPathPoints()[wpp];
cvf::Vec3d p2 = m_wellPathGeometry->wellPathPoints()[wpp + 1];
cvf::BoundingBox bb;
bb.add( p1 );
bb.add( p2 );
std::vector<size_t> closeCells = findCloseCells( bb );
cvf::Vec3d hexCorners[8];
for ( size_t ccIdx = 0; ccIdx < closeCells.size(); ++ccIdx )
{
RigElementType elmType = femPart->elementType( closeCells[ccIdx] );
if ( !( elmType == HEX8 || elmType == HEX8P ) ) continue;
const int* cornerIndices = femPart->connectivities( closeCells[ccIdx] );
hexCorners[0] = cvf::Vec3d( nodeCoords[cornerIndices[0]] );
hexCorners[1] = cvf::Vec3d( nodeCoords[cornerIndices[1]] );
hexCorners[2] = cvf::Vec3d( nodeCoords[cornerIndices[2]] );
hexCorners[3] = cvf::Vec3d( nodeCoords[cornerIndices[3]] );
hexCorners[4] = cvf::Vec3d( nodeCoords[cornerIndices[4]] );
hexCorners[5] = cvf::Vec3d( nodeCoords[cornerIndices[5]] );
hexCorners[6] = cvf::Vec3d( nodeCoords[cornerIndices[6]] );
hexCorners[7] = cvf::Vec3d( nodeCoords[cornerIndices[7]] );
// int intersectionCount = RigHexIntersector::lineHexCellIntersection(p1, p2, hexCorners,
// closeCells[ccIdx], &intersections);
RigHexIntersectionTools::lineHexCellIntersection( p1, p2, hexCorners, closeCells[ccIdx], &intersections );
}
// Now, with all the intersections of this piece of line, we need to
// sort them in order, and set the measured depth and corresponding cell index
// Inserting the intersections in this map will remove identical intersections
// and sort them according to MD, CellIdx, Leave/enter
double md1 = m_wellPathGeometry->measuredDepths()[wpp];
double md2 = m_wellPathGeometry->measuredDepths()[wpp + 1];
insertIntersectionsInMap( intersections, p1, md1, p2, md2, &uniqueIntersections );
}
this->populateReturnArrays( uniqueIntersections );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<size_t> RigGeoMechWellLogExtractor::findCloseCells( const cvf::BoundingBox& bb )
{
std::vector<size_t> closeCells;
if ( m_caseData->femParts()->partCount() )
{
m_caseData->femParts()->part( 0 )->findIntersectingCells( bb, &closeCells );
}
return closeCells;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Vec3d RigGeoMechWellLogExtractor::calculateLengthInCell( size_t cellIndex,
const cvf::Vec3d& startPoint,
const cvf::Vec3d& endPoint ) const
{
std::array<cvf::Vec3d, 8> hexCorners;
const RigFemPart* femPart = m_caseData->femParts()->part( 0 );
const std::vector<cvf::Vec3f>& nodeCoords = femPart->nodes().coordinates;
const int* cornerIndices = femPart->connectivities( cellIndex );
hexCorners[0] = cvf::Vec3d( nodeCoords[cornerIndices[0]] );
hexCorners[1] = cvf::Vec3d( nodeCoords[cornerIndices[1]] );
hexCorners[2] = cvf::Vec3d( nodeCoords[cornerIndices[2]] );
hexCorners[3] = cvf::Vec3d( nodeCoords[cornerIndices[3]] );
hexCorners[4] = cvf::Vec3d( nodeCoords[cornerIndices[4]] );
hexCorners[5] = cvf::Vec3d( nodeCoords[cornerIndices[5]] );
hexCorners[6] = cvf::Vec3d( nodeCoords[cornerIndices[6]] );
hexCorners[7] = cvf::Vec3d( nodeCoords[cornerIndices[7]] );
return RigWellPathIntersectionTools::calculateLengthInCell( hexCorners, startPoint, endPoint );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Vec3d RigGeoMechWellLogExtractor::calculateWellPathTangent( int64_t intersectionIdx,
WellPathTangentCalculation calculationType ) const
{
if ( calculationType == TangentFollowWellPathSegments )
{
cvf::Vec3d segmentStart, segmentEnd;
m_wellPathGeometry->twoClosestPoints( m_intersections[intersectionIdx], &segmentStart, &segmentEnd );
return ( segmentEnd - segmentStart ).getNormalized();
}
else
{
cvf::Vec3d wellPathTangent;
if ( intersectionIdx % 2 == 0 )
{
wellPathTangent = m_intersections[intersectionIdx + 1] - m_intersections[intersectionIdx];
}
else
{
wellPathTangent = m_intersections[intersectionIdx] - m_intersections[intersectionIdx - 1];
}
CVF_ASSERT( wellPathTangent.length() > 1.0e-7 );
return wellPathTangent.getNormalized();
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
caf::Ten3d RigGeoMechWellLogExtractor::transformTensorToWellPathOrientation( const cvf::Vec3d& wellPathTangent,
const caf::Ten3d& tensor )
{
// Create local coordinate system for well path segment
cvf::Vec3d local_z = wellPathTangent;
cvf::Vec3d local_x = local_z.perpendicularVector().getNormalized();
cvf::Vec3d local_y = ( local_z ^ local_x ).getNormalized();
// Calculate the rotation matrix from global i, j, k to local x, y, z.
cvf::Mat4d rotationMatrix = cvf::Mat4d::fromCoordSystemAxes( &local_x, &local_y, &local_z );
return tensor.rotated( rotationMatrix.toMatrix3() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Vec3f RigGeoMechWellLogExtractor::cellCentroid( size_t intersectionIdx ) const
{
const RigFemPart* femPart = m_caseData->femParts()->part( 0 );
const std::vector<cvf::Vec3f>& nodeCoords = femPart->nodes().coordinates;
size_t elmIdx = m_intersectedCellsGlobIdx[intersectionIdx];
RigElementType elmType = femPart->elementType( elmIdx );
int elementNodeCount = RigFemTypes::elementNodeCount( elmType );
const int* elmNodeIndices = femPart->connectivities( elmIdx );
cvf::Vec3f centroid( 0.0, 0.0, 0.0 );
for ( int i = 0; i < elementNodeCount; ++i )
{
centroid += nodeCoords[elmNodeIndices[i]];
}
return centroid / elementNodeCount;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double RigGeoMechWellLogExtractor::getWellLogIntersectionValue( size_t intersectionIdx,
const std::vector<std::pair<double, double>>& wellLogValues ) const
{
const double eps = 1.0e-4;
double intersection_md = m_intersectionMeasuredDepths[intersectionIdx];
for ( size_t i = 0; i < wellLogValues.size() - 1; ++i )
{
double las_md_i = wellLogValues[i].first;
double las_md_ip1 = wellLogValues[i + 1].first;
if ( cvf::Math::valueInRange( intersection_md, las_md_i, las_md_ip1 ) )
{
double dist_i = std::abs( intersection_md - las_md_i );
double dist_ip1 = std::abs( intersection_md - las_md_ip1 );
if ( dist_i < eps )
{
return wellLogValues[i].second;
}
else if ( dist_ip1 < eps )
{
return wellLogValues[i + 1].second;
}
else
{
RiaWeightedMeanCalculator<double> averageCalc;
averageCalc.addValueAndWeight( wellLogValues[i].second, 1.0 / dist_i );
averageCalc.addValueAndWeight( wellLogValues[i + 1].second, 1.0 / dist_ip1 );
return averageCalc.weightedMean();
}
}
}
// If we found no match, check first and last value within a threshold.
if ( !wellLogValues.empty() )
{
const double relativeEps = 1.0e-3 * std::max( 1.0, intersection_md );
if ( std::abs( wellLogValues.front().first - intersection_md ) < relativeEps )
{
return wellLogValues.front().second;
}
else if ( std::abs( wellLogValues.back().first - intersection_md ) < relativeEps )
{
return wellLogValues.back().second;
}
}
return std::numeric_limits<double>::infinity();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double RigGeoMechWellLogExtractor::pascalToBar( double pascalValue )
{
return pascalValue * 1.0e-5;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template <typename T>
bool RigGeoMechWellLogExtractor::averageIntersectionValuesToSegmentValue( size_t intersectionIdx,
const std::vector<T>& values,
const T& invalidValue,
T* averagedCellValue ) const
{
CVF_ASSERT( values.size() >= 2 );
*averagedCellValue = invalidValue;
T value1, value2;
cvf::Vec3d centroid( cellCentroid( intersectionIdx ) );
double dist1 = 0.0, dist2 = 0.0;
if ( intersectionIdx % 2 == 0 )
{
value1 = values[intersectionIdx];
value2 = values[intersectionIdx + 1];
dist1 = ( centroid - m_intersections[intersectionIdx] ).length();
dist2 = ( centroid - m_intersections[intersectionIdx + 1] ).length();
}
else
{
value1 = values[intersectionIdx - 1];
value2 = values[intersectionIdx];
dist1 = ( centroid - m_intersections[intersectionIdx - 1] ).length();
dist2 = ( centroid - m_intersections[intersectionIdx] ).length();
}
if ( invalidValue == value1 || invalidValue == value2 )
{
return false;
}
RiaWeightedMeanCalculator<T> averageCalc;
averageCalc.addValueAndWeight( value1, dist2 );
averageCalc.addValueAndWeight( value2, dist1 );
if ( averageCalc.validAggregatedWeight() )
{
*averagedCellValue = averageCalc.weightedMean();
}
return true;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template <typename T>
std::vector<T> RigGeoMechWellLogExtractor::interpolateInterfaceValues( RigFemResultAddress nativeAddr,
int frameIndex,
const std::vector<T>& unscaledResultValues )
{
std::vector<T> interpolatedInterfaceValues;
initializeResultValues( interpolatedInterfaceValues, m_intersections.size() );
const RigFemPart* femPart = m_caseData->femParts()->part( 0 );
#pragma omp parallel for
for ( int64_t intersectionIdx = 0; intersectionIdx < (int64_t)m_intersections.size(); ++intersectionIdx )
{
size_t elmIdx = m_intersectedCellsGlobIdx[intersectionIdx];
RigElementType elmType = femPart->elementType( elmIdx );
if ( !( elmType == HEX8 || elmType == HEX8P ) ) continue;
interpolatedInterfaceValues[intersectionIdx] =
interpolateGridResultValue<T>( nativeAddr.resultPosType, unscaledResultValues, intersectionIdx );
}
return interpolatedInterfaceValues;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RigGeoMechWellLogExtractor::initializeResultValues( std::vector<float>& resultValues, size_t resultCount )
{
resultValues.resize( resultCount, std::numeric_limits<float>::infinity() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RigGeoMechWellLogExtractor::initializeResultValues( std::vector<caf::Ten3d>& resultValues, size_t resultCount )
{
resultValues.resize( resultCount );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RigGeoMechWellLogExtractor::smoothSegments( std::vector<double>* mds,
std::vector<double>* tvds,
std::vector<double>* values,
const std::vector<double>& interfaceShValues,
const std::vector<unsigned char>& smoothSegments,
const double smoothingThreshold )
{
const double eps = 1.0e-6;
double maxOriginalMd = ( *mds )[0];
double maxOriginalTvd = ( !tvds->empty() ) ? ( *tvds )[0] : 0.0;
for ( int64_t i = 1; i < int64_t( mds->size() - 1 ); ++i )
{
double originalMD = ( *mds )[i];
double originalTVD = ( !tvds->empty() ) ? ( *tvds )[i] : 0.0;
bool smoothSegment = smoothSegments[i] != 0u;
double diffMd = std::fabs( ( *mds )[i + 1] - ( *mds )[i] ) / std::max( eps, ( *mds )[i] );
double diffSh =
std::fabs( interfaceShValues[i + 1] - interfaceShValues[i] ) / std::max( eps, interfaceShValues[i] );
bool leapSh = diffSh > smoothingThreshold && diffMd < eps;
if ( smoothSegment )
{
if ( leapSh )
{
// Update depth of current
if ( i == 1 )
{
( *mds )[i] = maxOriginalMd;
if ( !tvds->empty() )
{
( *tvds )[i] = maxOriginalTvd;
}
}
else
{
( *mds )[i] = 0.5 * ( ( *mds )[i] + maxOriginalMd );
if ( !tvds->empty() )
{
( *tvds )[i] = 0.5 * ( ( *tvds )[i] + maxOriginalTvd );
}
}
}
else
{
// Update depth of current
( *mds )[i] = ( *mds )[i - 1];
if ( !tvds->empty() )
{
( *tvds )[i] = ( *tvds )[i - 1];
}
}
double diffMd_m1 = std::fabs( ( *mds )[i] - ( *mds )[i - 1] );
if ( diffMd_m1 < ( *mds )[i] * eps && ( *values )[i - 1] != std::numeric_limits<double>::infinity() )
{
( *values )[i] = ( *values )[i - 1];
}
}
if ( leapSh )
{
maxOriginalMd = std::max( maxOriginalMd, originalMD );
maxOriginalTvd = std::max( maxOriginalTvd, originalTVD );
}
}
}
//--------------------------------------------------------------------------------------------------
/// Note that this is unsigned char because std::vector<bool> is not thread safe
//--------------------------------------------------------------------------------------------------
std::vector<unsigned char>
RigGeoMechWellLogExtractor::determineFilteringOrSmoothing( const std::vector<double>& porePressures )
{
std::vector<unsigned char> smoothOrFilterSegments( porePressures.size(), false );
#pragma omp parallel for
for ( int64_t i = 1; i < int64_t( porePressures.size() - 1 ); ++i )
{
bool validPP_im1 = porePressures[i - 1] >= 0.0 && porePressures[i - 1] != std::numeric_limits<double>::infinity();
bool validPP_i = porePressures[i] >= 0.0 && porePressures[i] != std::numeric_limits<double>::infinity();
bool validPP_ip1 = porePressures[i + 1] >= 0.0 && porePressures[i + 1] != std::numeric_limits<double>::infinity();
bool anyValidPP = validPP_im1 || validPP_i || validPP_ip1;
smoothOrFilterSegments[i] = !anyValidPP;
}
return smoothOrFilterSegments;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double RigGeoMechWellLogExtractor::hydroStaticPorePressureForIntersection( size_t intersectionIdx,
double waterDensityGCM3 ) const
{
double trueVerticalDepth = m_intersectionTVDs[intersectionIdx];
double effectiveDepthMeters = trueVerticalDepth + m_wellPathGeometry->rkbDiff();
return hydroStaticPorePressureAtDepth( effectiveDepthMeters, waterDensityGCM3 );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double RigGeoMechWellLogExtractor::hydroStaticPorePressureForSegment( size_t intersectionIdx, double waterDensityGCM3 ) const
{
cvf::Vec3f centroid = cellCentroid( intersectionIdx );
double trueVerticalDepth = -centroid.z();
double effectiveDepthMeters = trueVerticalDepth + m_wellPathGeometry->rkbDiff();
return hydroStaticPorePressureAtDepth( effectiveDepthMeters, waterDensityGCM3 );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double RigGeoMechWellLogExtractor::hydroStaticPorePressureAtDepth( double effectiveDepthMeters, double waterDensityGCM3 )
{
double hydroStaticPorePressurePascal = effectiveDepthMeters * GRAVITY_ACCEL * waterDensityGCM3 * 1000;
double hydroStaticPorePressureBar = pascalToBar( hydroStaticPorePressurePascal );
return hydroStaticPorePressureBar;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double RigGeoMechWellLogExtractor::wbsCurveValuesAtMsl() const
{
double waterDensityGCM3 = m_userDefinedValues.at( RigWbsParameter::waterDensity() );
double rkbDiff = m_wellPathGeometry->rkbDiff();
if ( rkbDiff == std::numeric_limits<double>::infinity() )
{
rkbDiff = 0.0;
}
if ( m_waterDepth + rkbDiff < 1.0e-8 )
{
return waterDensityGCM3;
}
return waterDensityGCM3 * m_waterDepth / ( m_waterDepth + rkbDiff );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RigGeoMechWellLogExtractor::isValid( double value )
{
return value != std::numeric_limits<double>::infinity();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RigGeoMechWellLogExtractor::isValid( float value )
{
return value != std::numeric_limits<float>::infinity();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double RigGeoMechWellLogExtractor::calculateWaterDepth() const
{
// Need a well path with intersections to generate a precise water depth
if ( m_intersectionTVDs.empty() || m_wellPathGeometry->wellPathPoints().empty() )
{
return std::numeric_limits<double>::infinity();
}
// Only calculate water depth if the well path starts outside the model.
cvf::BoundingBox boundingBox = m_caseData->femParts()->boundingBox();
if ( boundingBox.contains( m_wellPathGeometry->wellPathPoints().front() ) )
{
return std::numeric_limits<double>::infinity();
}
// Water depth is always the first intersection with model for geo mech models.
double waterDepth = m_intersectionTVDs.front();
return waterDepth;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double RigGeoMechWellLogExtractor::estimateWaterDepth() const
{
// Estimate water depth using bounding box. This will be imprecise
// for models with a slanting top layer.
cvf::BoundingBox boundingBox = m_caseData->femParts()->boundingBox();
return std::abs( boundingBox.max().z() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double RigGeoMechWellLogExtractor::waterDepth() const
{
return m_waterDepth;
}
| OPM/ResInsight | ApplicationLibCode/ReservoirDataModel/RigGeoMechWellLogExtractor.cpp | C++ | gpl-3.0 | 69,527 |
/*
* Decompiled with CFR 0_115.
*/
package com.crashlytics.android.answers;
import com.crashlytics.android.answers.AnswersAttributes;
import com.crashlytics.android.answers.AnswersEvent;
import com.crashlytics.android.answers.AnswersEventValidator;
public class CustomEvent
extends AnswersEvent<CustomEvent> {
private final String eventName;
public CustomEvent(String string2) {
if (string2 == null) {
throw new NullPointerException("eventName must not be null");
}
this.eventName = this.validator.limitStringLength(string2);
}
String getCustomType() {
return this.eventName;
}
public String toString() {
return "{eventName:\"" + this.eventName + '\"' + ", customAttributes:" + this.customAttributes + "}";
}
}
| SPACEDAC7/TrabajoFinalGrado | uploads/34f7f021ecaf167f6e9669e45c4483ec/java_source/com/crashlytics/android/answers/CustomEvent.java | Java | gpl-3.0 | 799 |
/**
* The main application class. An instance of this class is created by app.js when it
* calls Ext.application(). This is the ideal place to handle application launch and
* initialization details.
*/
Ext.define('Demo.Application', {
extend: 'Ext.app.Application',
name: 'Demo',
stores: [
// TODO: add global / shared stores here
],
launch: function () {
// TODO - Launch the application
},
onAppUpdate: function () {
Ext.Msg.confirm('Application Update', 'This application has an update, reload?',
function (choice) {
if (choice === 'yes') {
window.location.reload();
}
}
);
}
});
| chihchungyu/Demo | public/app/Application.js | JavaScript | gpl-3.0 | 739 |
using System;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace NvnTest.Employer.Rtf {
/// <summary>
/// Summary description for RtfFootnote
/// </summary>
public class RtfFootnote : RtfBlockList {
private int _position;
internal RtfFootnote(int position, int textLength)
: base(true, false, false, true, false) {
if (position < 0 || position >= textLength) {
throw new Exception("Invalid footnote position: " + position
+ " (text length=" + textLength + ")");
}
_position = position;
}
internal int Position {
get {
return _position;
}
}
internal new string render() {
StringBuilder result = new StringBuilder();
result.AppendLine(@"{\super\chftn}");
result.AppendLine(@"{\footnote\plain\chftn");
((RtfBlock)base._blocks[base._blocks.Count - 1]).BlockTail = "}";
result.Append(base.render());
result.AppendLine("}");
return result.ToString();
}
}
} | nvngithub/nvntest | NvnTest.Employer/schedules/report/rtf/RtfFootnote.cs | C# | gpl-3.0 | 1,205 |
using System;
using ServiceModel = Eleflex;
namespace Eleflex.Security.Services.WCF.Message
{
/// <summary>
/// Represents a LogMessage service client.
/// </summary>
public partial class SecurityUserPermissionServiceRepository : ISecurityUserPermissionServiceRepository
{
/// <summary>
/// Insert an item.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public virtual IResponseItem<ServiceModel.SecurityUserPermission> Insert(IRequestItem<ServiceModel.SecurityUserPermission> request)
{
using (ISecurityRequestDispatcher dispatcher = ObjectLocator.Current.GetInstance<ISecurityRequestDispatcher>())
{
SecurityUserPermissionInsertRequest req = new SecurityUserPermissionInsertRequest();
req.Item = request.Item;
return dispatcher.ExecuteServiceCommand<SecurityUserPermissionInsertResponse>(req);
}
}
/// <summary>
/// Get an item.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public virtual IResponseItem<ServiceModel.SecurityUserPermission> Get(IRequestItem<long> request)
{
using (ISecurityRequestDispatcher dispatcher = ObjectLocator.Current.GetInstance<ISecurityRequestDispatcher>())
{
SecurityUserPermissionGetRequest req = new SecurityUserPermissionGetRequest();
req.Item = request.Item;
return dispatcher.ExecuteServiceCommand<SecurityUserPermissionGetResponse>(req);
}
}
/// <summary>
/// Update an item.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public virtual IResponseItem<ServiceModel.SecurityUserPermission> Update(IRequestItem<ServiceModel.SecurityUserPermission> request)
{
using (ISecurityRequestDispatcher dispatcher = ObjectLocator.Current.GetInstance<ISecurityRequestDispatcher>())
{
SecurityUserPermissionUpdateRequest req = new SecurityUserPermissionUpdateRequest();
req.Item = request.Item;
return dispatcher.ExecuteServiceCommand<SecurityUserPermissionUpdateResponse>(req);
}
}
/// <summary>
/// Delete an item.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public virtual IResponse Delete(IRequestItem<long> request)
{
using (ISecurityRequestDispatcher dispatcher = ObjectLocator.Current.GetInstance<ISecurityRequestDispatcher>())
{
SecurityUserPermissionDeleteRequest req = new SecurityUserPermissionDeleteRequest();
req.Item = request.Item;
return dispatcher.ExecuteServiceCommand<SecurityUserPermissionDeleteResponse>(req);
}
}
/// <summary>
/// Query items.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public virtual IStorageQueryResponseItems<ServiceModel.SecurityUserPermission> Query(IRequestItem<IStorageQuery> request)
{
using (ISecurityRequestDispatcher dispatcher = ObjectLocator.Current.GetInstance<ISecurityRequestDispatcher>())
{
SecurityUserPermissionQueryRequest req = new SecurityUserPermissionQueryRequest();
req.Item = request.Item;
return dispatcher.ExecuteServiceCommand<SecurityUserPermissionQueryResponse>(req);
}
}
/// <summary>
/// Query aggregate.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public virtual IResponseItem<double> QueryAggregate(IRequestItem<IStorageQuery> request)
{
using (ISecurityRequestDispatcher dispatcher = ObjectLocator.Current.GetInstance<ISecurityRequestDispatcher>())
{
SecurityUserPermissionQueryAggregateRequest req = new SecurityUserPermissionQueryAggregateRequest();
req.Item = request.Item;
return dispatcher.ExecuteServiceCommand<SecurityUserPermissionQueryAggregateResponse>(req);
}
}
}
}
| ProductionReady/Eleflex | V3.0/Modules/Security/Eleflex.Security.Services.WCF.Message/SecurityUserPermissionServiceRepository.cs | C# | gpl-3.0 | 4,369 |
""" DIRAC FileCatalog Security Manager mix-in class
"""
__RCSID__ = "$Id$"
import os
from DIRAC import S_OK, S_ERROR
from DIRAC.Core.Security.Properties import FC_MANAGEMENT
_readMethods = ['exists', 'isFile', 'getFileSize', 'getFileMetadata',
'getReplicas','getReplicaStatus','getFileAncestors',
'getFileDescendents','listDirectory','isDirectory',
'getDirectoryReplicas', 'getDirectorySize', 'getDirectoryMetadata']
_writeMethods = ['changePathOwner', 'changePathGroup', 'changePathMode',
'addFile','setFileStatus','removeFile','addReplica',
'removeReplica','setReplicaStatus','setReplicaHost',
'setFileOwner','setFileGroup','setFileMode',
'addFileAncestors','createDirectory','removeDirectory',
'setMetadata','__removeMetadata']
class SecurityManagerBase( object ):
def __init__( self, database = None ):
self.db = database
def setDatabase( self, database ):
self.db = database
def getPathPermissions( self, paths, credDict ):
""" Get path permissions according to the policy
"""
return S_ERROR( 'The getPathPermissions method must be implemented in the inheriting class' )
def hasAccess(self,opType,paths,credDict):
# Map the method name to Read/Write
if opType in _readMethods:
opType = 'Read'
elif opType in _writeMethods:
opType = 'Write'
# Check if admin access is granted first
result = self.hasAdminAccess( credDict )
if not result['OK']:
return result
if result['Value']:
# We are admins, allow everything
permissions = {}
for path in paths:
permissions[path] = True
return S_OK( {'Successful':permissions, 'Failed':{}} )
successful = {}
failed = {}
if not opType.lower() in ['read', 'write', 'execute']:
return S_ERROR( "Operation type not known" )
if self.db.globalReadAccess and ( opType.lower() == 'read' ):
for path in paths:
successful[path] = True
resDict = {'Successful':successful, 'Failed':{}}
return S_OK( resDict )
result = self.getPathPermissions( paths, credDict )
if not result['OK']:
return result
permissions = result['Value']['Successful']
for path, permDict in permissions.items():
if permDict[opType]:
successful[path] = True
else:
successful[path] = False
failed.update( result['Value']['Failed'] )
resDict = {'Successful':successful, 'Failed':failed}
return S_OK( resDict )
def hasAdminAccess( self, credDict ):
if FC_MANAGEMENT in credDict['properties']:
return S_OK( True )
return S_OK( False )
class NoSecurityManager( SecurityManagerBase ):
def getPathPermissions( self, paths, credDict ):
""" Get path permissions according to the policy
"""
permissions = {}
for path in paths:
permissions[path] = {'Read':True, 'Write':True, 'Execute':True}
return S_OK( {'Successful':permissions, 'Failed':{}} )
def hasAccess( self, opType, paths, credDict ):
successful = {}
for path in paths:
successful[path] = True
resDict = {'Successful':successful, 'Failed':{}}
return S_OK( resDict )
def hasAdminAccess( self, credDict ):
return S_OK( True )
class DirectorySecurityManager( SecurityManagerBase ):
def getPathPermissions( self, paths, credDict ):
""" Get path permissions according to the policy
"""
toGet = dict( zip( paths, [ [path] for path in paths ] ) )
permissions = {}
failed = {}
while toGet:
res = self.db.dtree.getPathPermissions( toGet.keys(), credDict )
if not res['OK']:
return res
for path, mode in res['Value']['Successful'].items():
for resolvedPath in toGet[path]:
permissions[resolvedPath] = mode
toGet.pop( path )
for path, error in res['Value']['Failed'].items():
if error != 'No such file or directory':
for resolvedPath in toGet[path]:
failed[resolvedPath] = error
toGet.pop( path )
for path, resolvedPaths in toGet.items():
if path == '/':
for resolvedPath in resolvedPaths:
permissions[path] = {'Read':True, 'Write':True, 'Execute':True}
if not toGet.has_key( os.path.dirname( path ) ):
toGet[os.path.dirname( path )] = []
toGet[os.path.dirname( path )] += resolvedPaths
toGet.pop( path )
if self.db.globalReadAccess:
for path in permissions:
permissions[path]['Read'] = True
return S_OK( {'Successful':permissions, 'Failed':failed} )
class FullSecurityManager( SecurityManagerBase ):
def getPathPermissions( self, paths, credDict ):
""" Get path permissions according to the policy
"""
toGet = dict( zip( paths, [ [path] for path in paths ] ) )
permissions = {}
failed = {}
res = self.db.fileManager.getPathPermissions( paths, credDict )
if not res['OK']:
return res
for path, mode in res['Value']['Successful'].items():
for resolvedPath in toGet[path]:
permissions[resolvedPath] = mode
toGet.pop( path )
for path, resolvedPaths in toGet.items():
if path == '/':
for resolvedPath in resolvedPaths:
permissions[path] = {'Read':True, 'Write':True, 'Execute':True}
if not toGet.has_key( os.path.dirname( path ) ):
toGet[os.path.dirname( path )] = []
toGet[os.path.dirname( path )] += resolvedPaths
toGet.pop( path )
while toGet:
paths = toGet.keys()
res = self.db.dtree.getPathPermissions( paths, credDict )
if not res['OK']:
return res
for path, mode in res['Value']['Successful'].items():
for resolvedPath in toGet[path]:
permissions[resolvedPath] = mode
toGet.pop( path )
for path, error in res['Value']['Failed'].items():
if error != 'No such file or directory':
for resolvedPath in toGet[path]:
failed[resolvedPath] = error
toGet.pop( path )
for path, resolvedPaths in toGet.items():
if path == '/':
for resolvedPath in resolvedPaths:
permissions[path] = {'Read':True, 'Write':True, 'Execute':True}
if not toGet.has_key( os.path.dirname( path ) ):
toGet[os.path.dirname( path )] = []
toGet[os.path.dirname( path )] += resolvedPaths
toGet.pop( path )
if self.db.globalReadAccess:
for path in permissions:
permissions[path]['Read'] = True
return S_OK( {'Successful':permissions, 'Failed':failed} )
class DirectorySecurityManagerWithDelete( DirectorySecurityManager ):
""" This security manager implements a Delete operation.
For Read, Write, Execute, it's behavior is the one of DirectorySecurityManager.
For Delete, if the directory does not exist, we return True.
If the directory exists, then we test the Write permission
"""
def hasAccess( self, opType, paths, credDict ):
# The other SecurityManager do not support the Delete operation,
# and it is transformed in Write
# so we keep the original one
if opType in ['removeFile', 'removeReplica', 'removeDirectory']:
self.opType = 'Delete'
elif opType in _readMethods:
self.opType = 'Read'
elif opType in _writeMethods:
self.opType = 'Write'
res = super( DirectorySecurityManagerWithDelete, self ).hasAccess( opType, paths, credDict )
# We reinitialize self.opType in case someone would call getPathPermissions directly
self.opType = ''
return res
def getPathPermissions( self, paths, credDict ):
""" Get path permissions according to the policy
"""
# If we are testing in anything else than a Delete, just return the parent methods
if hasattr( self, 'opType' ) and self.opType.lower() != 'delete':
return super( DirectorySecurityManagerWithDelete, self ).getPathPermissions( paths, credDict )
# If the object (file or dir) does not exist, we grant the permission
res = self.db.dtree.exists( paths )
if not res['OK']:
return res
nonExistingDirectories = set( path for path in res['Value']['Successful'] if not res['Value']['Successful'][path] )
res = self.db.fileManager.exists( paths )
if not res['OK']:
return res
nonExistingFiles = set( path for path in res['Value']['Successful'] if not res['Value']['Successful'][path] )
nonExistingObjects = nonExistingDirectories & nonExistingFiles
permissions = {}
failed = {}
for path in nonExistingObjects:
permissions[path] = {'Read':True, 'Write':True, 'Execute':True}
# The try catch is just to protect in case there are duplicate in the paths
try:
paths.remove( path )
except Exception, _e:
pass
# For all the paths that exist, check the write permission
if paths:
res = super( DirectorySecurityManagerWithDelete, self ).getPathPermissions( paths, credDict )
if not res['OK']:
return res
failed = res['Value']['Failed']
permissions.update( res['Value']['Successful'] )
return S_OK( {'Successful':permissions, 'Failed':failed} )
class PolicyBasedSecurityManager( SecurityManagerBase ):
""" This security manager loads a python plugin and forwards the
calls to it. The python plugin has to be defined in the CS under
/Systems/DataManagement/YourSetup/FileCatalog/SecurityPolicy
"""
def __init__( self, database = False ):
super( PolicyBasedSecurityManager, self ).__init__( database )
from DIRAC.ConfigurationSystem.Client.PathFinder import getServiceSection
from DIRAC import gConfig
from DIRAC.ConfigurationSystem.Client.Helpers.Path import cfgPath
serviceSection = getServiceSection( 'DataManagement/FileCatalog' )
pluginPath = gConfig.getValue( cfgPath( serviceSection, 'SecurityPolicy' ) )
if not pluginPath:
raise Exception( "SecurityPolicy not defined in service options" )
pluginCls = self.__loadPlugin( pluginPath )
self.policyObj = pluginCls( database = database )
@staticmethod
def __loadPlugin( pluginPath ):
""" Create an instance of requested plugin class, loading and importing it when needed.
This function could raise ImportError when plugin cannot be found or TypeError when
loaded class object isn't inherited from SecurityManagerBase class.
:param str pluginName: dotted path to plugin, specified as in import statement, i.e.
"DIRAC.CheesShopSystem.private.Cheddar" or alternatively in 'normal' path format
"DIRAC/CheesShopSystem/private/Cheddar"
:return: object instance
This function try to load and instantiate an object from given path. It is assumed that:
- :pluginPath: is pointing to module directory "importable" by python interpreter, i.e.: it's
package's top level directory is in $PYTHONPATH env variable,
- the module should consist a class definition following module name,
- the class itself is inherited from SecurityManagerBase
If above conditions aren't meet, function is throwing exceptions:
- ImportError when class cannot be imported
- TypeError when class isn't inherited from SecurityManagerBase
"""
if "/" in pluginPath:
pluginPath = ".".join( [ chunk for chunk in pluginPath.split( "/" ) if chunk ] )
pluginName = pluginPath.split( "." )[-1]
if pluginName not in globals():
mod = __import__( pluginPath, globals(), fromlist = [ pluginName ] )
pluginClassObj = getattr( mod, pluginName )
else:
pluginClassObj = globals()[pluginName]
if not issubclass( pluginClassObj, SecurityManagerBase ):
raise TypeError( "Security policy '%s' isn't inherited from SecurityManagerBase class" % pluginName )
return pluginClassObj
def hasAccess( self, opType, paths, credDict ):
return self.policyObj.hasAccess( opType, paths, credDict )
def getPathPermissions( self, paths, credDict ):
return self.policyObj.getPathPermissions( paths, credDict )
| marcelovilaca/DIRAC | DataManagementSystem/DB/FileCatalogComponents/SecurityManager.py | Python | gpl-3.0 | 12,106 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package neembuu.uploader.accounts;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import neembuu.uploader.translation.Translation;
import neembuu.uploader.exceptions.NUException;
import neembuu.uploader.exceptions.accounts.NUInvalidLoginException;
import neembuu.uploader.httpclient.NUHttpClient;
import neembuu.uploader.httpclient.httprequest.NUHttpPost;
import neembuu.uploader.interfaces.abstractimpl.AbstractAccount;
import neembuu.uploader.utils.CookieUtils;
import neembuu.uploader.utils.NULogger;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
/**
*
* @author davidepastore
* @author Paralytic - plugin re-written
*/
public class BillionUploadsAccount extends AbstractAccount{
private final HttpClient httpclient = NUHttpClient.getHttpClient();
private HttpResponse httpResponse;
private NUHttpPost httpPost;
private CookieStore cookieStore;
private String responseString;
public BillionUploadsAccount() {
KEY_USERNAME = "bllnuusername";
KEY_PASSWORD = "bllnupassword";
HOSTNAME = "BillionUploads.com";
}
@Override
public void disableLogin() {
resetLogin();
NULogger.getLogger().log(Level.INFO, "{0} account disabled", getHOSTNAME());
}
@Override
public void login() {
loginsuccessful = false;
try {
initialize();
NULogger.getLogger().info("Trying to log in to BillionUploads.com");
httpPost = new NUHttpPost("http://billionuploads.com");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("op", "login"));
formparams.add(new BasicNameValuePair("login", getUsername()));
formparams.add(new BasicNameValuePair("password", getPassword()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
httpPost.setEntity(entity);
httpResponse = httpclient.execute(httpPost, httpContext);
NULogger.getLogger().info(httpResponse.getStatusLine().toString());
if (!CookieUtils.getCookieValue(httpContext, "xfss").isEmpty() && !CookieUtils.getCookieValue(httpContext, "login").isEmpty()) {
EntityUtils.consume(httpResponse.getEntity());
loginsuccessful = true;
username = getUsername();
password = getPassword();
NULogger.getLogger().info("BillionUploads.com login successful!");
} else {
//Get error message
responseString = EntityUtils.toString(httpResponse.getEntity());
//FileUtils.saveInFile("BillionUploadsAccount.html", responseString);
Document doc = Jsoup.parse(responseString);
String error = doc.getElementById("malert").text();
if(error.contains("Incorrect Login or Password")){
throw new NUInvalidLoginException(getUsername(), HOSTNAME);
}
//Generic exception
throw new Exception("Login error: " + error);
}
} catch(NUException ex){
resetLogin();
ex.printError();
accountUIShow().setVisible(true);
} catch (Exception e) {
resetLogin();
NULogger.getLogger().log(Level.SEVERE, "{0}: {1}", new Object[]{getClass().getName(), e});
showWarningMessage( Translation.T().loginerror(), HOSTNAME);
accountUIShow().setVisible(true);
}
}
private void initialize() throws Exception {
httpContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//NULogger.getLogger().info("Getting startup cookies & link from BillionUploads.com");
//responseString = NUHttpClientUtils.getData("http://billionuploads.com", httpContext);
}
private void resetLogin(){
loginsuccessful = false;
username = "";
password = "";
}
}
| Neembuu-Uploader/neembuu-uploader | modules/neembuu-uploader-uploaders/src/neembuu/uploader/accounts/BillionUploadsAccount.java | Java | gpl-3.0 | 4,737 |
import asyncio
class MyProtocol(asyncio.Protocol):
def __init__(self, loop):
self.loop = loop
def connection_made(self, transport):
self.transport = transport
self.transport.write(b"Ciao!")
def data_received(self, data):
print(data.decode())
self.transport.close()
def connection_lost(self, exc):
self.loop.stop()
def main():
loop = asyncio.get_event_loop()
coro = loop.create_connection(lambda: MyProtocol(loop), "localhost", 8000)
loop.run_until_complete(coro)
loop.run_forever()
loop.close()
if __name__ == "__main__":
main()
| DavideCanton/Python3 | prove_aio/prova_client.py | Python | gpl-3.0 | 626 |
<?php
session_start();
if ($_SESSION["autenticado"] != "SI")
{
header("Location: acceso.php");
exit();
}
$vida_session = time() - $_SESSION['tiempo'];
if($vida_session > $_SESSION['inactivo'])
{
session_destroy();
header("Location: acceso.php");
}
$_SESSION['tiempo'] = time();
?>
<html>
<head>
<link rel="stylesheet" href="style.css">
<title> Cambio de contraseña </title>
<head>
<div align=center>
<body>
<form method="POST" action="" class="basic-grey">
<h1 align=center> Cambio de contraseña </h1>
<div align=right>
<a href="index.php">Inicio</a>
<div align=center>
<br>
<label>
<?php echo $_SESSION["cc"]?>
</label>
<br>
<label>
<span>Contraseña actual:</span>
<input type="password" name="passv" />
</label>
<label>
<span>Contraseña nueva:</span>
<input type="password" name="passn1" />
</label>
<label>
<span>Repetir contraseña nueva:</span>
<input type="password" name="passn2" />
</label>
<br>
<input type="submit" name="submit" value="Continuar" class="button"/>
<br>
<br>
<?php
if (isset($_POST['submit']))
{
$campos = strlen($_POST['passv']) * strlen($_POST['passn1']) * strlen($_POST['passn2']);
if ($campos > 0)
{
if ($_POST['passn1'] == $_POST['passn2'])
{
if($_SESSION['pass']==$_POST['passv'])
{
$conexion = mysqli_connect("localhost",$_SESSION['cc'],$_SESSION['pass'],"1") or die ("No se puede conectar con el servidor");
mysqli_set_charset($conexion, "utf8");
$instruccion = "SET PASSWORD = PASSWORD('$_POST[passn1]')";
mysqli_query($conexion,$instruccion) or die ("Fallo en la consulta");
mysqli_close ($conexion);
$_SESSION['pass'] = $_POST['passn1'];
echo 'Cambio de contraseña satisfactorio';
}
else
echo "Comprueba tu contraseña";
}
else
echo 'Los campos de contraseña nueva no son iguales';
}
else
echo 'Rellena todos los campos';
}
?>
<br>
<br>
<a href="index.php">Volver</a>
</form>
</body>
</html>
| alSeveR/teso | archivos/contrasena.php | PHP | gpl-3.0 | 2,093 |
/* $Id: MessagesCh.cpp 3755 2013-07-14 23:11:47Z IMPOMEZIA $
* IMPOMEZIA Simple Chat
* Copyright © 2008-2013 IMPOMEZIA <schat@impomezia.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Ch.h"
#include "MessagesCh.h"
#include "sglobal.h"
MessagesCh::MessagesCh(QObject *parent)
: ChHook(parent)
{
}
void MessagesCh::newChannel(ChatChannel channel, ChatChannel user)
{
Ch::addNewFeedIfNotExist(channel, FEED_NAME_MESSAGES, user);
}
void MessagesCh::server(ChatChannel channel, bool created)
{
Q_UNUSED(created)
channel->feed(FEED_NAME_MESSAGES);
}
void MessagesCh::sync(ChatChannel channel, ChatChannel user)
{
Q_UNUSED(user)
Ch::addNewFeedIfNotExist(channel, FEED_NAME_MESSAGES);
}
void MessagesCh::userChannel(ChatChannel channel)
{
Ch::addNewUserFeedIfNotExist(channel, FEED_NAME_MESSAGES);
}
| impomezia/schat | src/common/plugins/Messages/MessagesCh.cpp | C++ | gpl-3.0 | 1,458 |
/*
YUI 3.4.1pr1 (build 4097)
Copyright 2011 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('io-queue', function(Y) {
/**
Extends IO to implement Queue for synchronous
transaction processing.
@module io-base
@submodule io-queue
@for IO
**/
var io = Y.io._map['io:0'] || new Y.IO();
Y.mix(Y.IO.prototype, {
/**
* Array of transactions queued for processing
*
* @property _q
* @private
* @static
* @type {Object}
*/
_q: new Y.Queue(),
_qActiveId: null,
_qInit: false,
/**
* Property to determine whether the queue is set to
* 1 (active) or 0 (inactive). When inactive, transactions
* will be stored in the queue until the queue is set to active.
*
* @property _qState
* @private
* @static
* @type {Number}
*/
_qState: 1,
/**
* Method Process the first transaction from the
* queue in FIFO order.
*
* @method _qShift
* @private
* @static
*/
_qShift: function() {
var io = this,
o = io._q.next();
io._qActiveId = o.id;
io._qState = 0;
io.send(o.uri, o.cfg, o.id);
},
/**
* Method for queueing a transaction before the request is sent to the
* resource, to ensure sequential processing.
*
* @method queue
* @static
* @return {Object}
*/
queue: function(uri, c) {
var io = this,
o = { uri: uri, cfg:c, id: this._id++ };
if(!io._qInit) {
Y.on('io:complete', function(id, o) { io._qNext(id); }, io);
io._qInit = true;
}
io._q.add(o);
if (io._qState === 1) {
io._qShift();
}
Y.log('Object queued. Transaction id is' + o.id, 'info', 'io');
return o;
},
_qNext: function(id) {
var io = this;
io._qState = 1;
if (io._qActiveId === id && io._q.size() > 0) {
io._qShift();
}
},
/**
* Method for promoting a transaction to the top of the queue.
*
* @method promote
* @static
*/
qPromote: function(o) {
this._q.promote(o);
},
/**
* Method for removing a specific, pending transaction from
* the queue.
*
* @method remove
* @private
* @static
*/
qRemove: function(o) {
this._q.remove(o);
},
qStart: function() {
var io = this;
io._qState = 1;
if (io._q.size() > 0) {
io._qShift();
}
Y.log('Queue started.', 'info', 'io');
},
/**
* Method for setting queue processing to inactive.
* Transaction requests to YUI.io.queue() will be stored in the queue, but
* not processed until the queue is reset to "active".
*
* @method _stop
* @private
* @static
*/
qStop: function() {
this._qState = 0;
Y.log('Queue stopped.', 'info', 'io');
},
/**
* Method to query the current size of the queue.
*
* @method _size
* @private
* @static
* @return {Number}
*/
qSize: function() {
return this._q.size();
}
}, true);
function _queue(u, c) {
return io.queue.apply(io, [u, c]);
}
_queue.start = function () { io.qStart(); };
_queue.stop = function () { io.qStop(); };
_queue.promote = function (o) { io.qPromote(o); };
_queue.remove = function (o) { io.qRemove(o); };
_queue.size = function () { io.qSize(); };
Y.io.queue = _queue;
}, '3.4.1pr1' ,{requires:['io-base','queue-promote']});
| uhoreg/moodle | lib/yui/3.4.1pr1/build/io-queue/io-queue-debug.js | JavaScript | gpl-3.0 | 3,560 |
package taojava.lists;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
/**
* Simple explorations of iterators and list iterators, using Java's
* friendly ArrayList class.
*
* @author Samuel A. Rebelsky
* @author Your Name Here
*/
public class ArrayListExperiment
{
// +---------+---------------------------------------------------------
// | Helpers |
// +---------+
/**
* Add a bunch of strings to the end of an arraylist.
*/
public static void addStrings(ArrayList<String> list, String[] values)
{
for (String str : values)
list.add(str);
} // addStrings(ArrayList<String>, String[])
// +------+------------------------------------------------------------
// | Main |
// +------+
public static void main(String[] args)
{
// Prepare for output
PrintWriter pen = new PrintWriter(System.out, true);
// Create an ArrayList to use in these experiments.
ArrayList<String> strings = new ArrayList<String>();
// Add some initial strings to our list and print it out.
addStrings(strings, new String[] { "a", "b", "c" });
pen.println("Initial array: " + strings);
// Create some iterators for the list
Iterator<String> it = strings.iterator();
ListIterator<String> lit = strings.listIterator();
ListIterator<String> lit1 = strings.listIterator();
ListIterator<String> lit2 = strings.listIterator();
// And we're done
pen.close();
} // main(String[])
} // class ArrayListExperiment
| Grinnell-CSC207/lab-array-based-lists | src/taojava/lists/ArrayListExperiment.java | Java | gpl-3.0 | 1,555 |
/*
* Copyright (C) 2015 Simon Schaeffner <simon.schaeffner@googlemail.com>
*
* This file is part of jArtnet.
*
* jArtnet is free software: you can redistribute it and/or modify
* it under the terms of the Lesser General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* jArtnet is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with jArtnet. If not, see <http://www.gnu.org/licenses/>.
*/
package me.sschaeffner.jArtnet;
import me.sschaeffner.jArtnet.packets.*;
import java.util.Arrays;
/**
* A collection of all OpCodes defined by the Art-Net 3 specification.
*
* These codes are used in all ArtnetPackets.
*
* Art-Net specification pages 15/16.
*/
public final class ArtnetOpCodes {
//each opcode is 2 bytes long
public static final int OP_POLL = 0x2000;
public static final int OP_POLL_REPLY = 0x2100;
public static final int OP_DIAG_DATA = 0x2300;
public static final int OP_COMMAND = 0x2400;
public static final int OP_OUTPUT = 0x5000;
public static final int OP_NZS = 0x5100;
public static final int OP_SYNC = 0x5200;
public static final int OP_ADDRESS = 0x6000;
public static final int OP_INPUT = 0x7000;
public static final int OP_TOD_REQUEST = 0x8000;
public static final int OP_TOD_DATA = 0x8100;
public static final int OP_TOD_CONTROL = 0x8200;
public static final int OP_RDM = 0x8300;
public static final int OP_RDM_SUB = 0x8400;
public static final int OP_VIDEO_SETUP = 0xa010;
public static final int OP_VIDEO_PALETTE = 0xa020;
public static final int OP_VIDEO_DATA = 0xa040;
public static final int OP_MAC_MASTER = 0xf000;
public static final int OP_MAC_SLAVE = 0xf100;
public static final int OP_FIRMWARE_REPLY = 0xf300;
public static final int OP_FILE_TN_MASTER = 0xf400;
public static final int OP_FILE_FN_MASTER = 0xf500;
public static final int OP_FILE_FN_REPLY = 0xf600;
public static final int OP_IP_PROG = 0xf800;
public static final int OP_IP_PROG_REPLY = 0xf900;
public static final int OP_MEDIA = 0x9000;
public static final int OP_MEDIA_PATCH = 0x9100;
public static final int OP_MEDIA_CONTROL = 0x9200;
public static final int OP_MEDIA_CONTRL_REPLY = 0x9300;
public static final int OP_TIME_CODE = 0x9700;
public static final int OP_TIME_SYNC = 0x9800;
public static final int OP_TRIGGER = 0x9900;
public static final int OP_DIRECTORY = 0x9a00;
public static final int OP_DIRECTORY_REPLY = 0x9b00;
/**
* Converts an OpCode integer into a byte array.
*
* Low byte is at position 0 and high byte at position 1 as to specification.
*
* @param opCode OpCode to convert
* @return converted OpCode as byte array
*/
public static byte[] toByteArray(int opCode) {
byte lowByte = (byte) (opCode & 0xFF);
byte highByte = (byte)((opCode >>> 8) & 0xFF);
return new byte[]{lowByte, highByte};
}
/**
* Converts the data of an Art-Net packet in an ArtnetPacket.
*
* @param bytes data of an Art-Net packet
* @return instance of ArtnetPacket
*/
public static ArtnetPacket fromBytes(byte[] bytes) throws MalformedArtnetPacketException {
//minimum data length
//packet id -> 8
//opcode -> 2
//some data -> 1+
if (bytes.length > 10) {
//check packet id
byte[] packetId = new byte[8];
System.arraycopy(bytes, 0, packetId, 0, 8);
if(Arrays.equals(packetId, ArtnetPacket.ID)) {
//check opcode
int opCodeLo = Byte.toUnsignedInt(bytes[8]);
int opCodeHi = Byte.toUnsignedInt(bytes[9]);
int opCode = (opCodeHi << 8) + opCodeLo;
switch (opCode) {
case ArtnetOpCodes.OP_OUTPUT:
return ArtDmxPacket.fromBytes(bytes);
case ArtnetOpCodes.OP_POLL:
return ArtPollPacket.fromBytes(bytes);
case ArtnetOpCodes.OP_POLL_REPLY:
return ArtPollReplyPacket.fromBytes(bytes);
case ArtnetOpCodes.OP_DIAG_DATA:
return ArtDiagDataPacket.fromBytes(bytes);
case ArtnetOpCodes.OP_IP_PROG:
return ArtIpProgPacket.fromBytes(bytes);
case ArtnetOpCodes.OP_IP_PROG_REPLY:
return ArtIpProgReplyPacket.fromBytes(bytes);
case ArtnetOpCodes.OP_SYNC:
return ArtSyncPacket.fromBytes(bytes);
case ArtnetOpCodes.OP_TIME_CODE:
return ArtTimeCodePacket.fromBytes(bytes);
case ArtnetOpCodes.OP_COMMAND:
return ArtCommandPacket.fromBytes(bytes);
case ArtnetOpCodes.OP_TRIGGER:
return ArtTriggerPacket.fromBytes(bytes);
case ArtnetOpCodes.OP_NZS:
return ArtNzsPacket.fromBytes(bytes);
case ArtnetOpCodes.OP_INPUT:
return ArtInputPacket.fromBytes(bytes);
case ArtnetOpCodes.OP_ADDRESS:
return ArtAddressPacket.fromBytes(bytes);
default:
throw new MalformedArtnetPacketException("unimplemented artnet packet (opcode " + opCode + ")");
}
} else {
System.out.println("not artnet packet: wrong packet ID");
}
} else {//else cannot be Art-Net packet
System.out.println("not artnet packet: too short");
}
return null;
}
}
| sschaeffner/jArtnet | src/me/sschaeffner/jArtnet/ArtnetOpCodes.java | Java | gpl-3.0 | 6,065 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* XSEC
*
* XSCryptCryptoBase64 := Internal implementation of a base64 encoder/decoder
*
* Author(s): Berin Lautenbach
*
* $Id: XSCryptCryptoBase64.hpp 1125514 2011-05-20 19:08:33Z scantor $
*
*/
#ifndef XSCRYPTCRYPTOBASE64_INCLUDE
#define XSCRYPTCRYPTOBASE64_INCLUDE
#include <xsec/framework/XSECDefs.hpp>
#include <xsec/enc/XSECCryptoBase64.hpp>
#include <xsec/utils/XSECSafeBuffer.hpp>
/**
* @defgroup xscryptcrypto Internal Crypto API Interface
* @ingroup crypto
* The XSCrypt Interface provides cryptographic functions that are missing
* from other libraries.
*
* Currently this only provides Base64 functionality which is not
* available in the Windows Crypto API.
*
*/
class DSIG_EXPORT XSCryptCryptoBase64 : public XSECCryptoBase64 {
public :
// Constructors/Destructors
XSCryptCryptoBase64() : m_state(B64_UNINITIALISED) {};
virtual ~XSCryptCryptoBase64() {};
/** @name Decoding Functions */
//@{
/**
* \brief Initialise the base64 object.
*
* Initialises the OpenSSL decode context and gets ready for data
* to be decoded.
*
*/
virtual void decodeInit(void); // Setup
/**
* \brief Decode some passed in data.
*
* Decode the passed in data and place the data in the outData buffer
*
* @param inData Pointer to the buffer holding encoded data.
* @param inLength Length of the encoded data in the buffer
* @param outData Buffer to place decoded data into
* @param outLength Maximum amount of data that can be placed in
* the buffer.
* @returns The number of bytes placed in the outData buffer.
*/
virtual unsigned int decode(const unsigned char * inData,
unsigned int inLength,
unsigned char * outData,
unsigned int outLength);
/**
* \brief Finish off a decode.
*
* Clean out any extra data from previous decode operations and place
* into the outData buffer.
*
* @param outData Buffer to place any remaining decoded data
* @param outLength Max amount of data to be placed in the buffer.
* @returns Amount of data placed in the outData buffer
*/
virtual unsigned int decodeFinish(unsigned char * outData,
unsigned int outLength);
//@}
/** @name Encoding Functions */
//@{
/**
* \brief Initialise the base64 object for encoding
*
* Get the context variable ready for a base64 decode
*
*/
virtual void encodeInit(void);
/**
* \brief Encode some passed in data.
*
* @param inData Pointer to the buffer holding data to be encoded.
* @param inLength Length of the data in the buffer
* @param outData Buffer to place encoded data into
* @param outLength Maximum amount of data that can be placed in
* the buffer.
* @returns The number of bytes placed in the outData buffer.
*/
virtual unsigned int encode(const unsigned char * inData,
unsigned int inLength,
unsigned char * outData,
unsigned int outLength);
/**
* \brief Finish off an encode.
*
* Take any data from previous encode operations and create the
* tail of the base64 encoding.
*
* @param outData Buffer to place any remaining encoded data
* @param outLength Max amount of data to be placed in the buffer.
* @returns Amount of data placed in the outData buffer
*/
virtual unsigned int encodeFinish(unsigned char * outData,
unsigned int outLength);
//@}
private :
enum b64state {
B64_UNINITIALISED,
B64_ENCODE,
B64_DECODE
};
safeBuffer m_inputBuffer; // Carry over buffer
safeBuffer m_outputBuffer; // Carry over output
unsigned int m_remainingInput; // Number of bytes in carry input buffer
unsigned int m_remainingOutput; // Number of bytes in carry output buffer
bool m_allDone; // End found (=)
b64state m_state; // What are we currently doing?
unsigned int m_charCount; // How many characters in current line?
// Private functions
void canonicaliseInput(const unsigned char *inData, unsigned int inLength);
};
#endif /* XSCRYPTCRYPTOBASE64_INCLUDE */
| 12019/svn.gov.pt | _src/eidmw/xml-security-c-1.7.2/xsec/enc/XSCrypt/XSCryptCryptoBase64.hpp | C++ | gpl-3.0 | 4,852 |
package com.github.jwtintegration.domain;
import lombok.Data;
/**
* @author Claudia López
* @author Diego Sepúlveda
*/
public @Data
class AuthenticationResponse {
private String token;
public AuthenticationResponse() {
}
public AuthenticationResponse(String token) {
this.token = token;
}
}
| colopezfuentes/spring-security-jwt-integration | src/main/java/com/github/jwtintegration/domain/AuthenticationResponse.java | Java | gpl-3.0 | 331 |
<?php
/**
* Storgman - Student Organizations Management
* Copyright (C) 2014-2015, Dejan Angelov <angelovdejan92@gmail.com>
*
* This file is part of Storgman.
*
* Storgman is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Storgman is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Storgman. If not, see <http://www.gnu.org/licenses/>.
*
* @package Storgman
* @copyright Copyright (C) 2014-2015, Dejan Angelov <angelovdejan92@gmail.com>
* @license https://github.com/angelov/storgman/blob/master/LICENSE
* @author Dejan Angelov <angelovdejan92@gmail.com>
*/
namespace Angelov\Storgman\Members\Listeners;
use Angelov\Storgman\Members\Events\MemberWasApprovedEvent;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Mail\Message;
class EmailApprovalConfirmation
{
protected $mailer;
public function __construct(Mailer $mailer)
{
$this->mailer = $mailer;
}
public function handle(MemberWasApprovedEvent $event)
{
$member = $event->getMember();
$this->mailer->send('emails.members.approved', compact('member'), function (Message $message) use ($member) {
$message->to($member->getEmail())->subject('Your account was approved!');
});
}
}
| angelov/eestec-platform | app/Members/Listeners/EmailApprovalConfirmation.php | PHP | gpl-3.0 | 1,685 |
#!/usr/bin/python
"""Run a Machination update cycle
"""
import sys
import itertools
from machination import utils, xmltools, fetcher, hierarchy, context
import topsort
from lxml import etree
workers = {}
class OLWorker:
def __init__(self, wid):
self.wid = wid
self.progdir = context.config.xpath("/config/workers")[0].get("progdir")
for f in os.listdir(self.progdir):
if f == wid or f.startswith(wid + "."):
self.progfile = f
self.progpath = os.path.join(self.progdir, self.progfile)
break
if self.progfile == None:
raise Exception("No worker named " + wid)
def generate_status(self):
pass
def do_work(self, wus):
pass
def main(args):
# initialise from config
logger = context.logger
# get config assertions and compile into desired_status.xml
ca_list = hierarchy.fetch_calist()
dst_elt = hierarchy.compile_calist(ca_list)
cst_elt = generate_base_status()
# workers: generate_status
for welt in dst_elt.xpath("/status/worker"):
w = get_worker(welt)
wcst_elt = w.generate_status()
# workers might not implement generate_status() - better be
# prepared for no status
if wcst_elt == None:
wcst_elt = get_previous_status(welt.get("id"))
# stitch them together into a big status document for later
# comparison
cst_elt.append(wcst_elt)
# find work
xmlcmp = xmltools.XMLCompare(dst_elt, cst_elt, workerdesc)
xmlcmp.compare()
xmlcmp.find_work()
stdeps = dst_elt.xpath("/status/deps/dep")
wudeps = xmlcmp.dependencies_state_to_wu(stdeps, xmlcmp.worklist, xmlcmp.byxpath)
first = True
previous_failures = set()
for i_workset in iter(topsort.topsort_levels(wudeps)):
# wuwus within an 'i_workset' are independent of each other
# wuwus that aren't mentioned in wudeps should be in the
# first i_workset
if first:
first = False
i_workset = i_workset.union(find_nodeps(xmlcmp.worklist, wudeps))
# fetcher: downloads and workers: do_work
# parallelisation perhaps?
results = spawn_work(parcel_work(i_workset, previous_failures))
# mark any failures
previous_failures = previous_failures.union(results.failures())
# gather resultant_status
def spawn_work(parcels):
"""Take a work parcels dictionary and do the work"""
for workername in parcels:
workerdesc = xmltools.WorkerDescription(os.path.join(context.status_dir(), "workers", workername, "description.xml"))
# if the worker is ordered:
# get copy of worker's current status (working_status)
# apply removes and mods to working status
# copy final desired_status to cur_des_status
# loop over siblings at wu level in cur_des_status:
# if sibling not in cur_des_st and is not to be added:
# drop from cur_des_st
# if sibling not in cur_des_st but is to be added:
# find position arg for add
# if sibling in both but wrong position:
# find correct move/reorder instruction
def get_worker(welt):
wid = welt.get("id")
if wid in workers:
return workers[wid]
try:
w = __import__("workers." + wid)
except ImportError as e:
if e.message.startswith('No module named '):
# TODO: assume no python module for this worker,
# try to find and execute an OL worker
try:
w = OLWorker(wid)
except Exception:
logger.emsg("No worker %s, giving up!" % wid)
raise
def generate_base_status():
elt = etree.Element("status")
return elt
if __name__ == '__main__':
main(sys.argv[1:])
| machination/machination | bin/update.py | Python | gpl-3.0 | 3,871 |
let weightDependency = new Tracker.Dependency;
Template.productSettings.helpers({
hasSelectedProducts() {
return this.products.length > 0;
},
itemWeightActive: function (weight) {
weightDependency.depend();
for (let product of this.products) {
let position = product.position || {};
let currentWeight = position.weight || 0;
if (currentWeight === weight) {
return "active";
}
}
return "";
}
});
Template.productSettingsGridItem.helpers({
displayPrice: function () {
if (this._id) {
return ReactionProduct.getProductPriceRange(this._id).range;
}
},
media: function () {
const media = ReactionCore.Collections.Media.findOne({
"metadata.productId": this._id,
"metadata.priority": 0,
"metadata.toGrid": 1
}, { sort: { uploadedAt: 1 } });
return media instanceof FS.File ? media : false;
},
additionalMedia: function () {
const mediaArray = ReactionCore.Collections.Media.find({
"metadata.productId": this._id,
"metadata.priority": {
$gt: 0
},
"metadata.toGrid": 1
}, { limit: 3 });
if (mediaArray.count() > 1) {
return mediaArray;
}
return false;
},
weightClass: function () {
weightDependency.depend();
let position = this.position || {};
let weight = position.weight || 0;
switch (weight) {
case 1:
return "product-medium";
case 2:
return "product-large";
default:
return "product-small";
}
},
isMediumWeight: function () {
weightDependency.depend();
let position = this.position || {};
let weight = position.weight || 0;
return weight === 1;
},
isLargeWeight: function () {
weightDependency.depend();
let position = this.position || {};
let weight = position.weight || 0;
return weight === 3;
},
shouldShowAdditionalImages: function () {
weightDependency.depend();
if (this.isMediumWeight && this.mediaArray) {
return true;
}
return false;
}
});
Template.productSettingsListItem.inheritsHelpersFrom("productSettingsGridItem");
/**
* productExtendedControls events
*/
Template.productSettings.events({
"click [data-event-action=publishProduct]": function () {
ReactionProduct.publishProduct(this.products);
},
"click [data-event-action=cloneProduct]": function () {
ReactionProduct.cloneProduct(this.products);
},
"click [data-event-action=deleteProduct]": function () {
ReactionProduct.maybeDeleteProduct(this.products);
},
"click [data-event-action=changeProductWeight]": function (event) {
event.preventDefault();
for (product of this.products) {
let weight = $(event.currentTarget).data("event-data") || 0;
let position = {
tag: ReactionCore.getCurrentTag(),
weight: weight,
updatedAt: new Date()
};
product.position = position;
Meteor.call("products/updateProductPosition", product._id, position,
function () {
weightDependency.changed();
});
}
}
});
| ScyDev/reaction | packages/reaction-product-variant/client/templates/products/productSettings/productSettings.js | JavaScript | gpl-3.0 | 3,087 |
<?php
/*
* Copyright (c) delight.im <info@delight.im>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see {http://www.gnu.org/licenses/}.
*/
require_once(__DIR__ . '/../../base.php');
// initialize the database connection
try {
Database::init(CONFIG_DB_CONNECT_STRING, CONFIG_DB_USERNAME, CONFIG_DB_PASSWORD);
}
catch (Exception $e) {
throw new Exception('Could not connect to database');
}
function getTwilioEndpoint() {
return (isHTTPS() ? 'https://' : 'http://').$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
}
function getTwilioSignature($url, $authToken, $data = array()) {
// sort the array by keys
ksort($data);
// append the data array to the URL without any delimiters
foreach ($data as $key => $value) {
$url = $url.$key.$value;
}
// calculate HMAC SHA-1
$hmac = hash_hmac('sha1', $url, $authToken, true);
// return hash as Base64
return base64_encode($hmac);
}
function clientHash($input) {
$output = '';
for ($i = 0; $i < CONFIG_CLIENT_HASH_ITERATIONS; $i++) {
$output = clientHashInternal($input.$output.CONFIG_CLIENT_HASH_SEED);
}
return $output;
}
function clientHashInternal($input) {
return base64_encode(hash(CONFIG_CLIENT_HASH_ALGORITHM, $input, true));
}
function extractHexHash($text) {
// if a hexadecimal hash (32+ chars) is found
if (preg_match('/[abcdef0-9]{32,}/is', $text, $subpattern)) {
// return the extracted hash
return $subpattern[0];
}
else {
// return an empty string because we didn't find the hash
return '';
}
}
$incomingSignature = isset($_SERVER['HTTP_X_TWILIO_SIGNATURE']) ? $_SERVER['HTTP_X_TWILIO_SIGNATURE'] : '';
$requiredSignature = getTwilioSignature(getTwilioEndpoint(), CONFIG_TWILIO_AUTH_CODE, $_POST);
if (hash_equals($incomingSignature, $requiredSignature)) {
if (isset($_POST['From']) && isset($_POST['Body'])) {
$incomingCode = extractHexHash($_POST['Body']);
// try to find an open request with the given verification code
$openRequest = Database::selectFirst("SELECT user_id, new_password FROM verifications WHERE verification_code = ".Database::escape($incomingCode)." AND time_until > ".time());
// if an open request with the given code has been found
if (isset($openRequest['user_id']) && isset($openRequest['new_password'])) {
$usernameByPhoneNumber = makeHash(clientHash(trim($_POST['From'])));
// set the new password for the user if the actual phone number matches the pretended phone number (contained in the username)
Database::update("UPDATE users SET password = ".Database::escape($openRequest['new_password'])." WHERE id = ".intval($openRequest['user_id'])." AND username = ".Database::escape($usernameByPhoneNumber));
// invalidate all open verification requests
Database::update("UPDATE verifications SET time_until = 0 WHERE user_id = ".intval($openRequest['user_id']));
}
}
}
// overwrite the response type header
header('Content-type: application/xml; charset=utf-8');
// send an empty response for the Twilio API (do nothing) and exit
echo '<?xml version="1.0" encoding="utf-8"?>';
echo '<Response></Response>';
exit;
?> | delight-im/Faceless | Server/public_html/internal/sms_verify.php | PHP | gpl-3.0 | 3,833 |
// Decompiled with JetBrains decompiler
// Type: Wb.Lpw.Game.Common.GameRoomObject.Building.ConsumableCraftingBuildingProtocol
// Assembly: Wb.Lpw.Game.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 3C4BDCBA-73F8-4BAA-AC19-A98EC2D71189
// Assembly location: C:\Users\CGA Computer\Desktop\LEGO Universe Stuff\LOCO Server\Unity Web Player Extractor\Saved Files\LOCO Server.unity3d_unpacked\Wb.Lpw.Game.Common.dll
using System.Collections;
using Wb.Lpw.Game.Common;
namespace Wb.Lpw.Game.Common.GameRoomObject.Building
{
public class ConsumableCraftingBuildingProtocol
{
public enum Opcode
{
svrStartCrafting = 39,
svrCollectItem = 40,
svrSpawnConsumableItem = 41,
Custom = 42,
}
public enum SyncCode
{
CustomColor1 = 17,
CustomColor2 = 18,
Custom = 19,
}
public class StartCraftingCmd : GameRoomProtocol.Command
{
public long BlueprintItemId;
public float TimeLeftInSeconds;
public string Metadata;
public override int Opcode
{
get
{
return 39;
}
}
public override GameRoomProtocol.Command FromHashtable(Hashtable ht)
{
this.BlueprintItemId = SafeHashTable.ReadLong(ht, 0, 0L);
this.TimeLeftInSeconds = SafeHashTable.ReadFloat(ht, 3, 0.0f);
this.Metadata = SafeHashTable.ReadString(ht, 4, "Failed to read string from hashtable");
return (GameRoomProtocol.Command) this;
}
public override Hashtable ToHashtable()
{
Hashtable wrappedTable = new Hashtable();
SafeHashTable.WriteLong(wrappedTable, 0, this.BlueprintItemId);
SafeHashTable.WriteFloat(wrappedTable, 3, this.TimeLeftInSeconds);
SafeHashTable.WriteString(wrappedTable, 4, this.Metadata);
return wrappedTable;
}
}
public class CollectItemCmd : GameRoomProtocol.Command
{
public long ItemId;
public int LootHandle;
public string MetadataString;
public override int Opcode
{
get
{
return 40;
}
}
public override GameRoomProtocol.Command FromHashtable(Hashtable ht)
{
this.ItemId = SafeHashTable.ReadLong(ht, 0, 0L);
this.LootHandle = SafeHashTable.ReadInt(ht, 3, 0);
this.MetadataString = SafeHashTable.ReadString(ht, 4, "");
return (GameRoomProtocol.Command) this;
}
public override Hashtable ToHashtable()
{
Hashtable wrappedTable = new Hashtable();
SafeHashTable.WriteLong(wrappedTable, 0, this.ItemId);
SafeHashTable.WriteInt(wrappedTable, 3, this.LootHandle);
if (!string.IsNullOrEmpty(this.MetadataString))
SafeHashTable.WriteString(wrappedTable, 4, this.MetadataString);
return wrappedTable;
}
}
public class SpawnConsumableItemCmd : GameRoomProtocol.Command
{
public long ItemId;
public override int Opcode
{
get
{
return 41;
}
}
public override GameRoomProtocol.Command FromHashtable(Hashtable ht)
{
this.ItemId = SafeHashTable.ReadLong(ht, 0, 0L);
return (GameRoomProtocol.Command) this;
}
public override Hashtable ToHashtable()
{
Hashtable wrappedTable = new Hashtable();
SafeHashTable.WriteLong(wrappedTable, 0, this.ItemId);
return wrappedTable;
}
}
}
}
| mater06/LEGOChimaOnlineReloaded | LoCO Client Files/Decompressed Client/Extracted DLL/Wb.Lpw.Game.Common/Wb/Lpw/Game/Common/GameRoomObject/Building/ConsumableCraftingBuildingProtocol.cs | C# | gpl-3.0 | 3,471 |
package delegate;
import locator.ServiceLocator;
import services.interfaces.CompetitionServicesRemote;
public class CompetitionServicesDelegate{
public final String jndiName = "/tft-project-ear/tft-project-ejb/CompetitionServices!services.interfaces.CompetitionServicesRemote";
public CompetitionServicesRemote getProxy() {
return (CompetitionServicesRemote) ServiceLocator.getInstance().getProxy(jndiName);
}
} | ZanzanaTeam/PDEV-TFT | tft-project/tft-project-client/src/main/java/delegate/CompetitionServicesDelegate.java | Java | gpl-3.0 | 422 |
<?php
class Acceso_PerfilTable extends Doctrine_Table
{
public static function getInstance()
{
return Doctrine_Core::getTable('Acceso_Perfil');
}
public function perfilesActivos()
{
$q = Doctrine_Query::create()
->select('p.*')
->from('Acceso_Perfil p')
->where('p.status = ?','A')
->orderBy('p.nombre');
return $q->execute();
}
} | mwveliz/siglas-mppp | lib/model/doctrine/project/Acceso/Acceso_PerfilTable.class.php | PHP | gpl-3.0 | 443 |
# -*- coding: utf-8 -*-
from __future__ import division
from otree.common import Currency as c, currency_range, safe_json
from . import models
from ._builtin import Page, WaitPage
from .models import Constants
class FinalPage(Page):
def is_displayed(self):
return self.round_number == Constants.num_rounds
def vars_for_template(self):
return {
'cumulated_score': int(self.participant.vars['app_cumulated_score']),
'rank': self.participant.vars['app_rank'],
'session': self.session.code,
'paid': self.participant.vars['app_paid'],
'ID': self.participant.label
}
pass
class SurveyPage(Page):
form_model = models.Player
form_fields = ['sex', #'sisters_brothers',
#'religion', 'religion_practice',
'student', 'field_of_studies',
#'couple',
#'boring_task',
#'risk_aversion'
'check_partners','check_matching',
'comments']
class MerciPage(Page):
pass
page_sequence = [
SurveyPage,
FinalPage
# MerciPage
]
| anthropo-lab/XP | UIMM_project/atl_Survey/views.py | Python | gpl-3.0 | 1,142 |
/****************************************************************************
** Meta object code from reading C++ file 'Call.h'
**
** Created: Tue Apr 20 17:18:33 2010
** by: The Qt Meta Object Compiler version 62 (Qt 4.6.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../src/Call.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'Call.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.6.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_Call[] = {
// content:
4, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
2, // signalCount
// signals: signature, parameters, type, tag, flags
6, 5, 5, 5, 0x05,
16, 5, 5, 5, 0x05,
0 // eod
};
static const char qt_meta_stringdata_Call[] = {
"Call\0\0changed()\0isOver(Call*)\0"
};
const QMetaObject Call::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_Call,
qt_meta_data_Call, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &Call::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *Call::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *Call::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_Call))
return static_cast<void*>(const_cast< Call*>(this));
return QObject::qt_metacast(_clname);
}
int Call::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: changed(); break;
case 1: isOver((*reinterpret_cast< Call*(*)>(_a[1]))); break;
default: ;
}
_id -= 2;
}
return _id;
}
// SIGNAL 0
void Call::changed()
{
QMetaObject::activate(this, &staticMetaObject, 0, 0);
}
// SIGNAL 1
void Call::isOver(Call * _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 1, _a);
}
QT_END_MOC_NAMESPACE
| max3903/SFLphone | kde/cmake-build/src/moc_Call.cpp | C++ | gpl-3.0 | 2,632 |
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2022 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
*
* EspoCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EspoCRM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Query;
use Espo\ORM\Query\Part\Order;
use InvalidArgumentException;
class UnionBuilder implements Builder
{
use BaseBuilderTrait;
/**
* Create an instance.
*/
public static function create(): self
{
return new self();
}
/**
* Build a UNION select query.
*/
public function build(): Union
{
return Union::fromRaw($this->params);
}
/**
* Clone an existing query for a subsequent modifying and building.
*/
public function clone(Union $query): self
{
$this->cloneInternal($query);
return $this;
}
/**
* Use UNION ALL.
*/
public function all(): self
{
$this->params['all'] = true;
return $this;
}
public function query(Select $query): self
{
$this->params['queries'] = $this->params['queries'] ?? [];
$this->params['queries'][] = $query;
return $this;
}
/**
* Apply OFFSET and LIMIT.
*/
public function limit(?int $offset = null, ?int $limit = null): self
{
$this->params['offset'] = $offset;
$this->params['limit'] = $limit;
return $this;
}
/**
* Apply ORDER.
*
* @param string|array<array{string,bool|string}> $orderBy A select alias.
* @param string|bool $direction OrderExpression::ASC|OrderExpression::DESC. TRUE for DESC order.
*/
public function order($orderBy, $direction = Order::ASC): self
{
if (is_bool($direction)) {
$direction = $direction ? Order::DESC : Order::ASC;
}
if (!$orderBy) {
throw new InvalidArgumentException();
}
if (is_array($orderBy)) {
foreach ($orderBy as $item) {
if (count($item) == 2) {
$this->order($item[0], $item[1]);
continue;
}
if (count($item) == 1) {
$this->order($item[0]);
continue;
}
throw new InvalidArgumentException("Bad order.");
}
return $this;
}
/** @var object|scalar $orderBy */
if (!is_string($orderBy) && !is_int($orderBy)) {
throw new InvalidArgumentException("Bad order.");
}
$this->params['orderBy'] = $this->params['orderBy'] ?? [];
$this->params['orderBy'][] = [$orderBy, $direction];
return $this;
}
}
| espocrm/espocrm | application/Espo/ORM/Query/UnionBuilder.php | PHP | gpl-3.0 | 3,878 |
package com.baeldung.pojo.test;
import com.baeldung.initializer.SimpleXstreamInitializer;
import com.baeldung.pojo.Customer;
import com.thoughtworks.xstream.XStream;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class XmlToObjectAliasIntegrationTest {
private XStream xstream = null;
@Before
public void dataSetup() {
SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer();
xstream = simpleXstreamInitializer.getXstreamInstance();
xstream.alias("customer", Customer.class);
}
@Test
public void convertXmlToObjectFromFile() throws FileNotFoundException {
ClassLoader classLoader = getClass().getClassLoader();
FileReader reader = new FileReader(classLoader
.getResource("data-file-alias.xml")
.getFile());
Customer customer = (Customer) xstream.fromXML(reader);
Assert.assertNotNull(customer);
}
}
| Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasIntegrationTest.java | Java | gpl-3.0 | 1,035 |
namespace SQL_Comment_Generator
{
partial class HistoryLogAdd
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.datUpdatedDate = new System.Windows.Forms.DateTimePicker();
this.txtAuthor = new System.Windows.Forms.TextBox();
this.txtDescription = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.btnAccept = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// datUpdatedDate
//
this.datUpdatedDate.Format = System.Windows.Forms.DateTimePickerFormat.Short;
this.datUpdatedDate.Location = new System.Drawing.Point(88, 13);
this.datUpdatedDate.Name = "datUpdatedDate";
this.datUpdatedDate.Size = new System.Drawing.Size(102, 20);
this.datUpdatedDate.TabIndex = 0;
//
// txtAuthor
//
this.txtAuthor.Location = new System.Drawing.Point(88, 39);
this.txtAuthor.Name = "txtAuthor";
this.txtAuthor.Size = new System.Drawing.Size(290, 20);
this.txtAuthor.TabIndex = 1;
//
// txtDescription
//
this.txtDescription.Location = new System.Drawing.Point(88, 65);
this.txtDescription.Name = "txtDescription";
this.txtDescription.Size = new System.Drawing.Size(290, 20);
this.txtDescription.TabIndex = 2;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(44, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(38, 13);
this.label1.TabIndex = 3;
this.label1.Text = "Date:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(34, 42);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(48, 13);
this.label2.TabIndex = 4;
this.label2.Text = "Author:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(7, 68);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(75, 13);
this.label3.TabIndex = 5;
this.label3.Text = "Description:";
//
// btnAccept
//
this.btnAccept.Location = new System.Drawing.Point(115, 104);
this.btnAccept.Name = "btnAccept";
this.btnAccept.Size = new System.Drawing.Size(75, 23);
this.btnAccept.TabIndex = 6;
this.btnAccept.Text = "Accept";
this.btnAccept.UseVisualStyleBackColor = true;
this.btnAccept.Click += new System.EventHandler(this.btnAccept_Click);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(196, 104);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 7;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// HistoryLogAdd
//
this.AcceptButton = this.btnAccept;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(387, 142);
this.ControlBox = false;
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnAccept);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.txtDescription);
this.Controls.Add(this.txtAuthor);
this.Controls.Add(this.datUpdatedDate);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "HistoryLogAdd";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Add History Record";
this.TopMost = true;
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.DateTimePicker datUpdatedDate;
private System.Windows.Forms.TextBox txtAuthor;
private System.Windows.Forms.TextBox txtDescription;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button btnAccept;
private System.Windows.Forms.Button btnCancel;
}
} | myoung1988/SQL-Comment-Generator | SQL Comment Generator/HistoryLogAdd.Designer.cs | C# | gpl-3.0 | 6,934 |
require 'java'
require 'inference/inference_service'
class UploadController < ApplicationController
def upload
if request.method == 'GET'
return
end
csv = params[:csv]
if csv
CsvUpload.read(csv)
render :text=>"File uploaded"
else
return redirect_to(:action=>:upload)
end
end
end
| novalis/cebu-rails | app/controllers/upload_controller.rb | Ruby | gpl-3.0 | 342 |
import {
curry,
split,
indexBy,
path,
prop,
} from 'ramda';
import fetchUserInstallations from './fetchUserInstallations';
import fetchInstallationRepositories from './fetchInstallationRepositories';
export default curry((accessToken, repository) => {
const [installationName] = split('/', repository);
return fetchUserInstallations(accessToken)
.then((installations) => {
const byName = indexBy(path(['account', 'login']), installations);
if (!byName[installationName]) {
throw new Error('Not Found');
}
return fetchInstallationRepositories(accessToken, byName[installationName].id);
})
.then(repositories => {
const byName = indexBy(prop(['full_name']), repositories);
if (!byName[repository]) {
throw new Error('Not Found');
}
return byName[repository];
});
});
| branch-bookkeeper/pina | src/lib/fetchRepository.js | JavaScript | gpl-3.0 | 959 |
// Decompiled with JetBrains decompiler
// Type: System.Reflection.Emit.AssemblyBuilderAccess
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// MVID: 255ABCDF-D9D6-4E3D-BAD4-F74D4CE3D7A8
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll
using System;
using System.Runtime.InteropServices;
namespace System.Reflection.Emit
{
/// <summary>
/// Defines the access modes for a dynamic assembly.
/// </summary>
[Flags]
[ComVisible(true)]
[Serializable]
public enum AssemblyBuilderAccess
{
Run = 1,
Save = 2,
RunAndSave = Save | Run,
ReflectionOnly = 6,
RunAndCollect = 9,
}
}
| mater06/LEGOChimaOnlineReloaded | LoCO Client Files/Decompressed Client/Extracted DLL/mscorlib/System/Reflection/Emit/AssemblyBuilderAccess.cs | C# | gpl-3.0 | 687 |
--TEST--
constant() tests
--FILE--
<?php
var_dump(constant());
var_dump(constant("", ""));
var_dump(constant(""));
var_dump(constant(array()));
define("TEST_CONST", 1);
var_dump(constant("TEST_CONST"));
define("TEST_CONST2", "test");
var_dump(constant("TEST_CONST2"));
echo "Done\n";
?>
--EXPECTF--
Warning: Wrong parameter count for constant() in %s on line %d
NULL
Warning: Wrong parameter count for constant() in %s on line %d
NULL
Warning: constant(): Couldn't find constant in %s on line %d
NULL
Notice: Array to string conversion in %s on line %d
Warning: constant(): Couldn't find constant Array in %s on line %d
NULL
int(1)
string(4) "test"
Done
| tukusejssirs/eSpievatko | spievatko/espievatko/prtbl/srv/new/php-5.2.5/Zend/tests/018.phpt | PHP | gpl-3.0 | 665 |
//--------------------------------------------------------
// Zelda Classic
//
// alleg_compat.cpp
//
// Compatibility between allegro versions.
//
//--------------------------------------------------------
#include "allegro_wrapper.h"
PACKFILE *pack_fopen_password(const char *filename, const char *mode, const char *password)
{
packfile_password(password);
PACKFILE *new_pf = pack_fopen(filename, mode);
packfile_password("");
return new_pf;
}
uint64_t file_size_ex_password(const char *filename, const char *password)
{
packfile_password(password);
uint64_t new_pf = file_size_ex(filename);
packfile_password("");
return new_pf;
}
| ArmageddonGames/ZeldaClassic | src/alleg_compat.cpp | C++ | gpl-3.0 | 649 |
from django.contrib import admin
from sentences.models import Sentence
from .models import Tweet
admin.site.register(Tweet)
# class SentenceInline(admin.TabularInline):
# model = Sentence
# readonly_fields = ('content', 'question',)
# max_num = 0
# can_delete = False
#
#
# class TweetAdmin(admin.ModelAdmin):
# inlines = [
# SentenceInline,
# ]
#
# admin.site.register(Tweet, TweetAdmin)
| efe/lesib | twitter/admin.py | Python | gpl-3.0 | 425 |
# -*- coding: utf-8 -*-
from models.user import User
class Authenticator(object):
def __init__(self, username, password):
self.username = username
self.password = password
def authenticate(self):
return True
class StudentAuthenticator(Authenticator):
def __init__(self,
student_grade=0,
student_class=0,
student_number=0,
# student_name='',
password='',
**kwargs):
# 年級
self.student_grade = student_grade
# 班級
self.student_class = student_class
# 座號
self.student_number = student_number
# 學生姓名
''' omit the name field
self.username = student_name
'''
self.username = "%02s_%02s_%02s" % (student_grade, student_class, student_number)
# 密碼
self.password = password
super(StudentAuthenticator, self).__init__(
self.username, self.password, **kwargs)
def authenticate(self):
try:
# unique key
user = User.query.filter_by(
student_grade=self.student_grade,
student_class=self.student_class,
student_number=self.student_number
).first()
# user not found
if user is None:
return False
else:
''' omit the name field
# password are 'student_name' and 'default_password'
if (user.student_name == self.username) and (user.default_password == self.password):
'''
if user.default_password == self.password:
return True
else:
return False
except:
return False
| lyshie/afc-github | app/authenticator.py | Python | gpl-3.0 | 1,848 |
#include "includepath/header.h"
#ifdef _CPPP_TEST // won't build in msvc?
#include "../msvc-8.0/include/crtdefs.h" // escape from '.'
#endif
#include <../include/stdarg.h> // escape from msvc stdcpp include-path
#include <../../cpparch/cppparse/test/includepath/header4.h> // escape from external/boost include-path
| willjoseph/cpparch | cpparch/cppparse/test/test_includepath.cpp | C++ | gpl-3.0 | 324 |
"""Collection of function that may be used by JCM template files (*.jcmt) to
create the project or that may be useful/necessary to process the results.
Contains a default processing function (`processing_default`).
Authors : Carlo Barth
Credit: Partly based on MATLAB-versions written by Sven Burger and Martin
Hammerschmidt.
"""
import numpy as np
from scipy import constants
c0 = constants.speed_of_light
mu0 = constants.mu_0
eps0 = constants.epsilon_0
Z0 = np.sqrt(mu0/eps0)
# =============================================================================
def processing_default(pps, keys):
"""Calculates the scattering efficiency `qsca` and the absorption efficieny
`qabs` by normalizing the `ElectromagneticFieldEnergyFlux` calculated in
the JCMsuite post process to the incident flux. It also returns the
extinction efficiency `qext`, which is the sum of `qsca` and `qabs`.
"""
results = {}
# Check if the correct number of post processes was passed
if not len(pps) == 2:
raise ValueError('This processing function is designed for a list of 2'+
' post processes, but these are {}'.format(len(pps)))
return
# Hard coded values
uol = 1e-6
vacuum_wavelength = 5.5e-7
# Set default keys
default_keys = {'info_level' : 10,
'storage_format' : 'Binary',
'initial_p_adaption' : True,
'n_refinement_steps' : 0,
'refinement_strategy' : 'HAdaptive'}
for dkey in default_keys:
if not dkey in keys:
keys[dkey] = default_keys[dkey]
# Calculate the energy flux normalization factor
geo_cross_section = np.pi*np.square(keys['radius']*uol)
p_in = 0.5/Z0*geo_cross_section
# Read the field energy and calculate the absorption in the sphere
# (should be 0)
omega = 2.*np.pi*c0/vacuum_wavelength
field_energy = pps[0]['ElectricFieldEnergy'][0]
results['qabs'] = -2.*omega*field_energy[1].imag/p_in
# Calculate the scattering cross section from the
# ElectromagneticFieldEnergyFlux-post process
results['qsca'] = pps[1]['ElectromagneticFieldEnergyFlux'][0][0].real/p_in
# Calculate the extinction efficiency
results['qext'] = results['qsca'] + results['qabs']
return results
def mie_analytical(radii, vacuum_wavelength, out_param='qsca',
cross_section=False, **mie_params):
"""Returns the analytical values for the efficiencies using the
`pymiecoated`-package. Pass additional parameters to the `Mie`-class
using the `mie_params`, e.g. by writing `m=1.52` to pass the refractive
index of the sphere. `out_param` can be each method of the `Mie`-class,
e.g. 'qext', 'qsca' or 'qabs'. Use `cross_section=True` to return the
related cross section instead of the efficiency."""
from pymiecoated import Mie
import collections
_is_iter = True
if not isinstance(radii, collections.Iterable):
_is_iter = False
radii = np.array([radii])
out_vals = []
for radius in radii:
x = 2 * np.pi * radius / vacuum_wavelength
mie = Mie(x=x, **mie_params)
out_func = getattr(mie, out_param)
out_val = out_func()
if cross_section:
out_val = np.pi * np.square(radius) * out_val
out_vals.append(out_val)
if not _is_iter:
return out_vals[0]
return np.array(out_vals)
if __name__ == '__main__':
pass
| cbpygit/pypmj | projects/scattering/mie/mie3D/project_utils.py | Python | gpl-3.0 | 3,547 |
/***************************************************************************
* Copyright S. V. Paulauskas 2014-2016 *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, version 3.0 License. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
**************************************************************************
*/
/** \file test.cpp
* \brief A test code to test the filtering
* \author S. V. Paulauskas
* \date 23 April 2014
*
* This code is based off of the IGOR macro energy.ipf
* written by H. Tan of XIA LLC and parts of the nscope
* program written at the NSCL written by C.Prokop.
*
*/
#include <algorithm>
#include <chrono>
#include <fstream>
#include <iostream>
#include <random>
#include <SignalGenerator.hpp>
#include "TraceFilter.hpp"
using namespace std;
int main(int argc, char* argv[]) {
vector<double> trc, trcMb, trcP;
unsigned int seed =
chrono::system_clock::now().time_since_epoch().count();
mt19937_64 twist (seed);
uniform_real_distribution<double> mult(0.0,1.0);
normal_distribution<double> amps(2048, 2);
ifstream infile("data/piledupTrc.dat");
if(!infile) {
cerr << "Cannot open input file. Try again, son." << endl;
exit(1);
} else {
while(infile) {
if (isdigit(infile.peek())) {
int junk1;
infile >> junk1;
trc.push_back(junk1);
} else
infile.ignore(1000,'\n');
}
}
infile.close();
//times in ns, sampling in ns/S, and thresh in ADC units
unsigned int adc = 10; // in ns/S
double tl = 100, tg = 30;
unsigned int thresh = 20;
double el = 600, eg = 240, tau = 90;
TrapFilterParameters trigger(tl,tg, thresh);
TrapFilterParameters energy(el,eg,tau);
double eLen = energy.GetSize() / adc;
TraceFilter filter(adc , trigger, energy);
filter.SetVerbose(true);
if(filter.CalcFilters(&trc) != 0)
exit(0);
vector<double> trig = filter.GetTriggerFilter();
vector<double> esums = filter.GetEnergySums();
ofstream output("trig.dat");
if(output)
for(const auto &i : trig)
output << i << endl;
output.close();
//The energy sum information
double sumL = 20489;
double sumG = 10040;
double sumT = 16508;
//double pE = 1179;
double pb = 3780.7283;
double pbPerSamp = pb / eLen;
vector<double> coeffs = filter.GetEnergyFilterCoefficients();
double trcEn = filter.GetEnergy();
cout << endl << "Calculations using my coefficients" << endl
<< "----------------------------" << endl;
cout << "Trc Energy Sums : ";
for(const auto &i : esums)
cout << i << " ";
cout << endl;
cout << "Trace Energy: " << trcEn << endl;
cout << "Esums Energy Calc 1 : "
<< sumL*coeffs[0]+sumG*coeffs[1]+sumT*coeffs[2]-pbPerSamp
<< endl;
cout << "Esums Energy Calc 2 : "
<< (sumL-pbPerSamp)*coeffs[0]+(sumG-pbPerSamp)*coeffs[1]+(sumT-pbPerSamp)*coeffs[2]
<< endl;
cout << "Esums Energy Calc 3 : "
<< sumL*coeffs[0]+sumG*coeffs[1]+sumT*coeffs[2]
<< endl;
cout << "Esums Energy Calc 4 : "
<< (sumL-pb)*coeffs[0]+(sumG-pb)*coeffs[1]+(sumT-pb)*coeffs[2]
<< endl;
cout << "Esums Energy Calc 5 : "
<< (sumL/(el*adc))*coeffs[0]+(sumG/(el*adc))*coeffs[1]+(sumT/(el*adc))*coeffs[2]
<< endl;
cout << "Esums Energy Calc 6 : "
<< (sumL/(el*adc))+(sumG/(el*adc))+(sumT/(el*adc))
<< endl;
double b1 = exp(-1/(tau*adc));
double a0 = pow(b1,el*adc)/(pow(b1,el*adc)-1.0);
double ag = 1.0;
double a1 = -1.0/(pow(b1,el*adc)-1.0);
cout << endl << "Calculations using C. Prokop's coefficients" << endl
<< "----------------------------" << endl;
cout << "Coeffs: " << endl << " a0 = " << a0 << endl << " ag = " << ag << endl
<< " a1 = " << a1 << endl;
cout << "Esums Energy Calc 1 : "
<< (sumL)*a0+(sumG)*ag+(sumT)*a1 - pb
<< endl;
cout << "Esums Energy Calc 2 : "
<< (sumL-pb)*a0+(sumG-pb)*ag+(sumT-pb)*a1
<< endl;
}
| spaulaus/TraceFiltering | src/test.cpp | C++ | gpl-3.0 | 5,050 |
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class Admin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::check() && Auth::user()->isAdmin()) {
return $next($request);
}
return redirect('unauthorized-access');
}
}
| ttucomc/utilities | app/Http/Middleware/Admin.php | PHP | gpl-3.0 | 454 |
package ch.cyberduck.core;
/*
* Copyright (c) 2002-2017 iterate GmbH. All rights reserved.
* https://cyberduck.io/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
import ch.cyberduck.core.cryptomator.CryptoAuthenticationException;
import ch.cyberduck.core.exception.BackgroundException;
import org.cryptomator.cryptolib.api.AuthenticationFailedException;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class DefaultIOExceptionMappingServiceTest {
@Test
public void testRootCause() {
final BackgroundException failure = new DefaultIOExceptionMappingService().map(new IOException("e", new CryptoAuthenticationException("d", new AuthenticationFailedException("f"))));
assertEquals(CryptoAuthenticationException.class, failure.getClass());
assertEquals("d.", failure.getDetail());
}
} | iterate-ch/cyberduck | cryptomator/src/test/java/ch/cyberduck/core/DefaultIOExceptionMappingServiceTest.java | Java | gpl-3.0 | 1,342 |
// Regression test for a leak in tsd:
// https://code.google.com/p/address-sanitizer/issues/detail?id=233
// RUN: %clangxx_asan -O1 %s -pthread -o %t
// RUN: ASAN_OPTIONS=quarantine_size=1 %run %t
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <sanitizer/allocator_interface.h>
static pthread_key_t tsd_key;
void *Thread(void *) {
pthread_setspecific(tsd_key, malloc(10));
return 0;
}
static volatile void *v;
void Dtor(void *tsd) {
v = malloc(10000);
free(tsd);
free((void*)v); // The bug was that this was leaking.
}
int main() {
assert(0 == pthread_key_create(&tsd_key, Dtor));
size_t old_heap_size = 0;
for (int i = 0; i < 10; i++) {
pthread_t t;
pthread_create(&t, 0, Thread, 0);
pthread_join(t, 0);
size_t new_heap_size = __sanitizer_get_heap_size();
fprintf(stderr, "heap size: new: %zd old: %zd\n", new_heap_size, old_heap_size);
if (old_heap_size)
assert(old_heap_size == new_heap_size);
old_heap_size = new_heap_size;
}
}
| s20121035/rk3288_android5.1_repo | external/compiler-rt/test/asan/TestCases/Linux/tsd_dtor_leak.cc | C++ | gpl-3.0 | 1,032 |
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2010 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
/*********************************************************************************
* Description: Defines the English language pack for the base application.
* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
* All Rights Reserved.
* Contributor(s): ______________________________________..
********************************************************************************/
$mod_strings = array (
'LBL_SEND_DATE_TIME' => 'Send Date',
'LBL_IN_QUEUE' => 'In Process',
'LBL_IN_QUEUE_DATE' => 'Queued Date',
'ERR_INT_ONLY_EMAIL_PER_RUN' => 'Use only integer values to specify the number of emails sent per batch',
'LBL_ATTACHMENT_AUDIT' => ' was sent. It was not duplicated locally to conserve disk usage.',
'LBL_CONFIGURE_SETTINGS' => 'Configure',
'LBL_CUSTOM_LOCATION' => 'User Defined',
'LBL_DEFAULT_LOCATION' => 'Default',
'LBL_DISCLOSURE_TITLE' => 'Append Disclosure Message to Every Email',
'LBL_DISCLOSURE_TEXT_TITLE' => 'Disclosure Contents',
'LBL_DISCLOSURE_TEXT_SAMPLE' => 'NOTICE: This email message is for the sole use of the intended recipient(s) and may contain confidential and privileged information. Any unauthorized review, use, disclosure, or distribution is prohibited. If you are not the intended recipient, please destroy all copies of the original message and notify the sender so that our address record can be corrected. Thank you.',
'LBL_EMAIL_DEFAULT_CHARSET' => 'Compose email messages in this character set',
'LBL_EMAIL_DEFAULT_EDITOR' => 'Compose email using this client',
'LBL_EMAIL_DEFAULT_DELETE_ATTACHMENTS' => 'Delete related notes & attachments with deleted Emails',
'LBL_EMAIL_GMAIL_DEFAULTS' => 'Prefill Gmail™ Defaults',
'LBL_EMAIL_PER_RUN_REQ' => 'Number of emails sent per batch:',
'LBL_EMAIL_SMTP_SSL' => 'Enable SMTP over SSL?',
'LBL_EMAIL_USER_TITLE' => 'User Email Defaults',
'LBL_EMAIL_OUTBOUND_CONFIGURATION' => 'Outgoing Mail Configuration',
'LBL_EMAILS_PER_RUN' => 'Number of emails sent per batch:',
'LBL_ID' => 'Id',
'LBL_LIST_CAMPAIGN' => 'Campaign',
'LBL_LIST_FORM_PROCESSED_TITLE' => 'Processed',
'LBL_LIST_FORM_TITLE' => 'Queue',
'LBL_LIST_FROM_EMAIL' => 'From Email',
'LBL_LIST_FROM_NAME' => 'From Name',
'LBL_LIST_IN_QUEUE' => 'In Process',
'LBL_LIST_MESSAGE_NAME' => 'Marketing Message',
'LBL_LIST_RECIPIENT_EMAIL' => 'Recipient Email',
'LBL_LIST_RECIPIENT_NAME' => 'Recipient Name',
'LBL_LIST_SEND_ATTEMPTS' => 'Send Attempts',
'LBL_LIST_SEND_DATE_TIME' => 'Send On',
'LBL_LIST_USER_NAME' => 'User Name',
'LBL_LOCATION_ONLY' => 'Location',
'LBL_LOCATION_TRACK' => 'Location of campaign tracking files (like campaign_tracker.php)',
'LBL_CAMP_MESSAGE_COPY' => 'Keep copies of campaign messages:',
'LBL_CAMP_MESSAGE_COPY_DESC' => 'Would you like to store complete copies of <bold>EACH</bold> email message sent during all campaigns? <bold>We recommend and default to no</bold>. Choosing no will store only the template that is sent and the needed variables to recreate the individual message.',
'LBL_MAIL_SENDTYPE' => 'Mail Transfer Agent:',
'LBL_MAIL_SMTPAUTH_REQ' => 'Use SMTP Authentication:',
'LBL_MAIL_SMTPPASS' => 'Password:',
'LBL_MAIL_SMTPPORT' => 'SMTP Port:',
'LBL_MAIL_SMTPSERVER' => 'SMTP Mail Server:',
'LBL_MAIL_SMTPUSER' => 'Username:',
'LBL_MARKETING_ID' => 'Marketing Id',
'LBL_MODULE_ID' => 'EmailMan',
'LBL_MODULE_NAME' => 'Email Settings',
'LBL_CAMP_MODULE_NAME' => 'Campaign Email Settings',
'LBL_MODULE_TITLE' => 'Outbound Email Queue Management',
'LBL_NOTIFICATION_ON_DESC' => 'When enabled, emails are sent to users when records are assigned to them.',
'LBL_NOTIFY_FROMADDRESS' => '"From" Address:',
'LBL_NOTIFY_FROMNAME' => '"From" Name:',
'LBL_NOTIFY_ON' => 'Assignment Notifications',
'LBL_NOTIFY_SEND_BY_DEFAULT' => 'Send notifications to new users',
'LBL_NOTIFY_TITLE' => 'Email Options',
'LBL_OLD_ID' => 'Old Id',
'LBL_OUTBOUND_EMAIL_TITLE' => 'Outbound Email Options',
'LBL_RELATED_ID' => 'Related Id',
'LBL_RELATED_TYPE' => 'Related Type',
'LBL_SAVE_OUTBOUND_RAW' => 'Save Outbound Raw Emails',
'LBL_SEARCH_FORM_PROCESSED_TITLE' => 'Processed Search',
'LBL_SEARCH_FORM_TITLE' => 'Queue Search',
'LBL_VIEW_PROCESSED_EMAILS' => 'View Processed Emails',
'LBL_VIEW_QUEUED_EMAILS' => 'View Queued Emails',
'TRACKING_ENTRIES_LOCATION_DEFAULT_VALUE' => 'Value of Config.php setting site_url',
'TXT_REMOVE_ME_ALT' => 'To remove yourself from this email list go to',
'TXT_REMOVE_ME_CLICK' => 'click here',
'TXT_REMOVE_ME' => 'To remove yourself from this email list ',
'LBL_NOTIFY_SEND_FROM_ASSIGNING_USER' => 'Send notification from assigning user\'s e-mail address',
'LBL_SECURITY_TITLE' => 'Email Security Settings',
'LBL_SECURITY_DESC' => 'Check the following that should NOT be allowed in via InboundEmail or displayed in the Emails module.',
'LBL_SECURITY_APPLET' => 'Applet tag',
'LBL_SECURITY_BASE' => 'Base tag',
'LBL_SECURITY_EMBED' => 'Embed tag',
'LBL_SECURITY_FORM' => 'Form tag',
'LBL_SECURITY_FRAME' => 'Frame tag',
'LBL_SECURITY_FRAMESET' => 'Frameset tag',
'LBL_SECURITY_IFRAME' => 'iFrame tag',
'LBL_SECURITY_IMPORT' => 'Import tag',
'LBL_SECURITY_LAYER' => 'Layer tag',
'LBL_SECURITY_LINK' => 'Link tag',
'LBL_SECURITY_OBJECT' => 'Object tag',
'LBL_SECURITY_OUTLOOK_DEFAULTS' => 'Select Outlook default minimum security settings (errs on the side of correct display).',
'LBL_SECURITY_SCRIPT' => 'Script tag',
'LBL_SECURITY_STYLE' => 'Style tag',
'LBL_SECURITY_TOGGLE_ALL' => 'Toggle All Options',
'LBL_SECURITY_XMP' => 'Xmp tag',
'LBL_YES' => 'Yes',
'LBL_NO' => 'No',
'LBL_PREPEND_TEST' => '[Test]: ',
'LBL_SEND_ATTEMPTS' => 'Send Attempts',
'LBL_OUTGOING_SECTION_HELP' => 'Configure the default outgoing mail server for sending email notifications, including workflow alerts.',
'LBL_ALLOW_DEFAULT_SELECTION' => 'Allow users to use this account for outgoing email:',
'LBL_ALLOW_DEFAULT_SELECTION_HELP' => 'When this option selected, all users will be able to send emails using the same outgoing<br> mail account used to send system notifications and alerts. If the option is not selected,<br> users can still use the outgoing mail server after providing their own account information.',
);
?> | Yuutakasan/SugarCRM-5.5.1-CE-JA-Dev | modules/EmailMan/language/en_us.lang.php | PHP | gpl-3.0 | 8,894 |
###
# Copyright 2016 - 2022 Green River Data Analysis, LLC
#
# License detail: https://github.com/greenriver/hmis-warehouse/blob/production/LICENSE.md
###
require 'rails_helper'
require_relative 'dq_context'
RSpec.describe HudDataQualityReport::Generators::Fy2022::QuestionOne, type: :model do
include_context 'dq context FY2022'
describe 'with default filters' do
before(:all) do
default_setup
run(default_filter, HudDataQualityReport::Generators::Fy2022::QuestionOne::QUESTION_NUMBER)
end
after(:all) do
cleanup
end
it 'counts people served' do
expect(report_result.answer(question: 'Q1', cell: 'B1').summary).to eq(9)
end
it 'counts adults' do
expect(report_result.answer(question: 'Q1', cell: 'B2').summary).to eq(6)
end
it 'counts children' do
expect(report_result.answer(question: 'Q1', cell: 'B3').summary).to eq(2)
end
it 'counts missing age' do
expect(report_result.answer(question: 'Q1', cell: 'B4').summary).to eq(1)
end
it 'counts leavers' do
expect(report_result.answer(question: 'Q1', cell: 'B5').summary).to eq(4)
end
it 'counts adult leavers' do
expect(report_result.answer(question: 'Q1', cell: 'B6').summary).to eq(3)
end
it 'counts adult and head of household leavers' do
expect(report_result.answer(question: 'Q1', cell: 'B7').summary).to eq(3)
end
it 'counts stayers' do
expect(report_result.answer(question: 'Q1', cell: 'B8').summary).to eq(5)
end
it 'counts adult stayers' do
expect(report_result.answer(question: 'Q1', cell: 'B9').summary).to eq(3)
end
it 'counts veterans' do
expect(report_result.answer(question: 'Q1', cell: 'B10').summary).to eq(2)
end
it 'counts chronically homeless persons' do
expect(report_result.answer(question: 'Q1', cell: 'B11').summary).to eq(1)
end
it 'counts under 25' do
expect(report_result.answer(question: 'Q1', cell: 'B12').summary).to eq(8)
end
it 'counts under 25 with children' do
expect(report_result.answer(question: 'Q1', cell: 'B13').summary).to eq(1)
end
it 'counts adult heads of household' do
expect(report_result.answer(question: 'Q1', cell: 'B14').summary).to eq(6)
end
it 'counts child and unknown age heads of household' do
expect(report_result.answer(question: 'Q1', cell: 'B15').summary).to eq(2)
end
it 'counts heads of household and stayers over 365 days' do
expect(report_result.answer(question: 'Q1', cell: 'B16').summary).to eq(4)
end
end
describe 'When filtering with a specific race' do
before(:all) do
default_setup
run(race_filter, HudDataQualityReport::Generators::Fy2022::QuestionOne::QUESTION_NUMBER)
end
it 'counts people served' do
expect(report_result.answer(question: 'Q1', cell: 'B1').summary).to eq(1)
end
end
describe 'When filtering with a specific age' do
before(:all) do
default_setup
run(age_filter, HudDataQualityReport::Generators::Fy2022::QuestionOne::QUESTION_NUMBER)
end
it 'counts people served' do
expect(report_result.answer(question: 'Q1', cell: 'B1').summary).to eq(2)
end
end
end
| greenriver/hmis-warehouse | drivers/hud_data_quality_report/spec/models/fy2022/question_one_spec.rb | Ruby | gpl-3.0 | 3,252 |
/*-
* #%L
* Genome Damage and Stability Centre SMLM ImageJ Plugins
*
* Software for single molecule localisation microscopy (SMLM)
* %%
* Copyright (C) 2011 - 2020 Alex Herbert
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package uk.ac.sussex.gdsc.smlm.function.gaussian.erf;
import java.util.logging.Level;
import org.apache.commons.math3.util.Precision;
import org.ejml.data.DenseMatrix64F;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import uk.ac.sussex.gdsc.core.utils.BitFlagUtils;
import uk.ac.sussex.gdsc.core.utils.DoubleEquality;
import uk.ac.sussex.gdsc.core.utils.LocalList;
import uk.ac.sussex.gdsc.core.utils.MathUtils;
import uk.ac.sussex.gdsc.core.utils.Statistics;
import uk.ac.sussex.gdsc.smlm.function.ExtendedGradient2Procedure;
import uk.ac.sussex.gdsc.smlm.function.Gradient1Procedure;
import uk.ac.sussex.gdsc.smlm.function.Gradient2Procedure;
import uk.ac.sussex.gdsc.smlm.function.IntegralValueProcedure;
import uk.ac.sussex.gdsc.smlm.function.ValueProcedure;
import uk.ac.sussex.gdsc.smlm.function.gaussian.Gaussian2DFunction;
import uk.ac.sussex.gdsc.smlm.function.gaussian.Gaussian2DFunctionTest;
import uk.ac.sussex.gdsc.smlm.function.gaussian.GaussianFunctionFactory;
import uk.ac.sussex.gdsc.test.api.TestAssertions;
import uk.ac.sussex.gdsc.test.api.TestHelper;
import uk.ac.sussex.gdsc.test.api.function.DoubleDoubleBiPredicate;
import uk.ac.sussex.gdsc.test.junit5.SpeedTag;
import uk.ac.sussex.gdsc.test.utils.BaseTimingTask;
import uk.ac.sussex.gdsc.test.utils.TestComplexity;
import uk.ac.sussex.gdsc.test.utils.TestLogUtils;
import uk.ac.sussex.gdsc.test.utils.TestSettings;
import uk.ac.sussex.gdsc.test.utils.TimingResult;
import uk.ac.sussex.gdsc.test.utils.TimingService;
@SuppressWarnings({"javadoc"})
public abstract class ErfGaussian2DFunctionTest extends Gaussian2DFunctionTest {
/**
* Instantiates a new erf gaussian 2 D function test.
*/
public ErfGaussian2DFunctionTest() {
super();
// The derivative check can be tighter with the ERF since it is a true integration
stepH = 0.0001;
eq3 = new DoubleEquality(5e-3, 1e-3); // For the Gaussian integral
}
@Test
void factoryDefaultsToErfGaussian2DFunction() {
Gaussian2DFunction f1;
Gaussian2DFunction f2;
final int flags2 = BitFlagUtils.unset(flags, GaussianFunctionFactory.FIT_ERF);
if (this.f2 != null) {
f1 = GaussianFunctionFactory.create2D(2, maxx, maxy, flags, zModel);
f2 = GaussianFunctionFactory.create2D(2, maxx, maxy, flags2, zModel);
Assertions.assertTrue(f1.getClass() == f2.getClass(), "Incorrect function2");
} else {
f1 = GaussianFunctionFactory.create2D(1, maxx, maxy, flags, zModel);
f2 = GaussianFunctionFactory.create2D(1, maxx, maxy, flags2, zModel);
Assertions.assertTrue(f1.getClass() == f2.getClass(), "Incorrect function1");
}
}
@Test
void functionComputesSecondBackgroundGradient() {
if (f1.evaluatesBackground()) {
functionComputesSecondTargetGradient(Gaussian2DFunction.BACKGROUND);
}
}
@Test
void functionComputesSecondSignalGradient() {
if (f1.evaluatesSignal()) {
functionComputesSecondTargetGradient(Gaussian2DFunction.SIGNAL);
}
}
@Test
void functionComputesSecondXGradient() {
functionComputesSecondTargetGradient(Gaussian2DFunction.X_POSITION);
}
@Test
void functionComputesSecondYGradient() {
functionComputesSecondTargetGradient(Gaussian2DFunction.Y_POSITION);
}
@Test
void functionComputesSecondZGradient() {
if (f1.evaluatesZ()) {
functionComputesSecondTargetGradient(Gaussian2DFunction.Z_POSITION);
}
}
@Test
void functionComputesSecondXWidthGradient() {
if (f1.evaluatesSD0()) {
functionComputesSecondTargetGradient(Gaussian2DFunction.X_SD);
}
}
@Test
void functionComputesSecondYWidthGradient() {
if (f1.evaluatesSD1()) {
functionComputesSecondTargetGradient(Gaussian2DFunction.Y_SD);
}
}
@Test
void functionComputesSecondAngleGradient() {
if (f1.evaluatesAngle()) {
functionComputesSecondTargetGradient(Gaussian2DFunction.ANGLE);
}
}
private void functionComputesSecondTargetGradient(int targetParameter) {
final ErfGaussian2DFunction f1 = (ErfGaussian2DFunction) this.f1;
final int gradientIndex = findGradientIndex(f1, targetParameter);
final double[] dyda = new double[f1.getNumberOfGradients()];
final double[] dyda2 = new double[dyda.length];
double[] params;
// Test fitting of second derivatives
final ErfGaussian2DFunction f1a =
(ErfGaussian2DFunction) GaussianFunctionFactory.create2D(1, maxx, maxy, flags, zModel);
final ErfGaussian2DFunction f1b =
(ErfGaussian2DFunction) GaussianFunctionFactory.create2D(1, maxx, maxy, flags, zModel);
final Statistics s = new Statistics();
for (final double background : testbackground) {
// Peak 1
for (final double signal1 : testsignal1) {
for (final double cx1 : testcx1) {
for (final double cy1 : testcy1) {
for (final double cz1 : testcz1) {
for (final double[] w1 : testw1) {
for (final double angle1 : testangle1) {
params =
createParameters(background, signal1, cx1, cy1, cz1, w1[0], w1[1], angle1);
f1.initialise2(params);
// Numerically solve gradient.
// Calculate the step size h to be an exact numerical representation
final double xx = params[targetParameter];
// Get h to minimise roundoff error
final double h = Precision.representableDelta(xx, stepH);
// Evaluate at (x+h) and (x-h)
params[targetParameter] = xx + h;
f1a.initialise1(params.clone());
params[targetParameter] = xx - h;
f1b.initialise1(params.clone());
for (final int x : testx) {
for (final int y : testy) {
final int i = y * maxx + x;
f1a.eval(i, dyda);
final double value2 = dyda[gradientIndex];
f1b.eval(i, dyda);
final double value3 = dyda[gradientIndex];
f1.eval2(i, dyda, dyda2);
final double gradient = (value2 - value3) / (2 * h);
final double error =
DoubleEquality.relativeError(gradient, dyda2[gradientIndex]);
s.add(error);
Assertions.assertTrue((gradient * dyda2[gradientIndex]) >= 0,
() -> gradient + " sign != " + dyda2[gradientIndex]);
// TestLog.fine(logger,"[%d,%d] %f == [%d] %f? (%g)", x, y, gradient,
// gradientIndex, dyda2[gradientIndex], error);
Assertions.assertTrue(
eq.almostEqualRelativeOrAbsolute(gradient, dyda2[gradientIndex]),
() -> gradient + " != " + dyda2[gradientIndex]);
}
}
}
}
}
}
}
}
}
logger.info(() -> {
return String.format("functionComputesSecondTargetGradient %s %s (error %s +/- %s)",
f1.getClass().getSimpleName(), Gaussian2DFunction.getName(targetParameter),
MathUtils.rounded(s.getMean()), MathUtils.rounded(s.getStandardDeviation()));
});
}
@Test
void functionComputesSecondBackgroundGradientWith2Peaks() {
Assumptions.assumeTrue(null != f2);
if (f2.evaluatesBackground()) {
functionComputesSecondTargetGradientWith2Peaks(Gaussian2DFunction.BACKGROUND);
}
}
@Test
void functionComputesSecondSignalGradientWith2Peaks() {
Assumptions.assumeTrue(null != f2);
if (f2.evaluatesSignal()) {
functionComputesSecondTargetGradientWith2Peaks(Gaussian2DFunction.SIGNAL);
functionComputesSecondTargetGradientWith2Peaks(
Gaussian2DFunction.SIGNAL + Gaussian2DFunction.PARAMETERS_PER_PEAK);
}
}
@Test
void functionComputesSecondXGradientWith2Peaks() {
Assumptions.assumeTrue(null != f2);
functionComputesSecondTargetGradientWith2Peaks(Gaussian2DFunction.X_POSITION);
functionComputesSecondTargetGradientWith2Peaks(
Gaussian2DFunction.Y_POSITION + Gaussian2DFunction.PARAMETERS_PER_PEAK);
}
@Test
void functionComputesSecondYGradientWith2Peaks() {
Assumptions.assumeTrue(null != f2);
functionComputesSecondTargetGradientWith2Peaks(Gaussian2DFunction.Y_POSITION);
functionComputesSecondTargetGradientWith2Peaks(
Gaussian2DFunction.Y_POSITION + Gaussian2DFunction.PARAMETERS_PER_PEAK);
}
@Test
void functionComputesSecondZGradientWith2Peaks() {
Assumptions.assumeTrue(null != f2);
if (f2.evaluatesZ()) {
functionComputesSecondTargetGradientWith2Peaks(Gaussian2DFunction.Z_POSITION);
functionComputesSecondTargetGradientWith2Peaks(
Gaussian2DFunction.Z_POSITION + Gaussian2DFunction.PARAMETERS_PER_PEAK);
}
}
@Test
void functionComputesSecondXWidthGradientWith2Peaks() {
Assumptions.assumeTrue(null != f2);
if (f2.evaluatesSD0()) {
functionComputesSecondTargetGradientWith2Peaks(Gaussian2DFunction.X_SD);
functionComputesSecondTargetGradientWith2Peaks(
Gaussian2DFunction.X_SD + Gaussian2DFunction.PARAMETERS_PER_PEAK);
}
}
@Test
void functionComputesSecondYWidthGradientWith2Peaks() {
Assumptions.assumeTrue(null != f2);
if (f2.evaluatesSD1()) {
functionComputesSecondTargetGradientWith2Peaks(Gaussian2DFunction.Y_SD);
functionComputesSecondTargetGradientWith2Peaks(
Gaussian2DFunction.Y_SD + Gaussian2DFunction.PARAMETERS_PER_PEAK);
}
}
@Test
void functionComputesSecondAngleGradientWith2Peaks() {
Assumptions.assumeTrue(null != f2);
if (f2.evaluatesAngle()) {
functionComputesSecondTargetGradientWith2Peaks(Gaussian2DFunction.ANGLE);
functionComputesSecondTargetGradientWith2Peaks(
Gaussian2DFunction.ANGLE + Gaussian2DFunction.PARAMETERS_PER_PEAK);
}
}
private void functionComputesSecondTargetGradientWith2Peaks(int targetParameter) {
final ErfGaussian2DFunction f2 = (ErfGaussian2DFunction) this.f2;
final int gradientIndex = findGradientIndex(f2, targetParameter);
final double[] dyda = new double[f2.getNumberOfGradients()];
final double[] dyda2 = new double[dyda.length];
double[] params;
// Test fitting of second derivatives
final ErfGaussian2DFunction f2a =
(ErfGaussian2DFunction) GaussianFunctionFactory.create2D(2, maxx, maxy, flags, zModel);
final ErfGaussian2DFunction f2b =
(ErfGaussian2DFunction) GaussianFunctionFactory.create2D(2, maxx, maxy, flags, zModel);
final Statistics s = new Statistics();
for (final double background : testbackground) {
// Peak 1
for (final double signal1 : testsignal1) {
for (final double cx1 : testcx1) {
for (final double cy1 : testcy1) {
for (final double cz1 : testcz1) {
for (final double[] w1 : testw1) {
for (final double angle1 : testangle1) {
// Peak 2
for (final double signal2 : testsignal2) {
for (final double cx2 : testcx2) {
for (final double cy2 : testcy2) {
for (final double cz2 : testcz2) {
for (final double[] w2 : testw2) {
for (final double angle2 : testangle2) {
params = createParameters(background, signal1, cx1, cy1, cz1, w1[0],
w1[1], angle1, signal2, cx2, cy2, cz2, w2[0], w2[1], angle2);
f2.initialise2(params);
// Numerically solve gradient.
// Calculate the step size h to be an exact numerical representation
final double xx = params[targetParameter];
// Get h to minimise roundoff error
final double h = Precision.representableDelta(xx, stepH);
// Evaluate at (x+h) and (x-h)
params[targetParameter] = xx + h;
f2a.initialise1(params.clone());
params[targetParameter] = xx - h;
f2b.initialise1(params.clone());
for (final int x : testx) {
for (final int y : testy) {
final int i = y * maxx + x;
f2a.eval(i, dyda);
final double value2 = dyda[gradientIndex];
f2b.eval(i, dyda);
final double value3 = dyda[gradientIndex];
f2.eval2(i, dyda, dyda2);
final double gradient = (value2 - value3) / (2 * h);
final double error =
DoubleEquality.relativeError(gradient, dyda2[gradientIndex]);
s.add(error);
Assertions.assertTrue(
(gradient * dyda2[gradientIndex]) >= 0,
() -> gradient + " sign != " + dyda2[gradientIndex]);
// TestLog.fine(logger,"[%d,%d] %f == [%d] %f? (%g)", x, y,
// gradient,
// gradientIndex, dyda2[gradientIndex], error);
Assertions.assertTrue(
eq.almostEqualRelativeOrAbsolute(gradient,
dyda2[gradientIndex]),
() -> gradient + " != " + dyda2[gradientIndex]);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
logger.info(() -> {
return String.format("functionComputesSecondTargetGradient %s [%d] %s (error %s +/- %s)",
f2.getClass().getSimpleName(), Gaussian2DFunction.getPeak(targetParameter),
Gaussian2DFunction.getName(targetParameter), MathUtils.rounded(s.getMean()),
MathUtils.rounded(s.getStandardDeviation()));
});
}
private class FunctionTimingTask extends BaseTimingTask {
Gaussian2DFunction f1;
ErfGaussian2DFunction f2;
double[][] x;
int order;
final double[] dyda;
final double[] d2yda2;
final int size = f1.size();
public FunctionTimingTask(Gaussian2DFunction f1, double[][] x, int order) {
super(f1.getClass().getSimpleName() + " " + order + " eval");
this.f1 = f1;
if (order == 2) {
f2 = (ErfGaussian2DFunction) f1;
}
this.x = x;
this.order = order;
dyda = new double[f1.getNumberOfGradients()];
d2yda2 = new double[f1.getNumberOfGradients()];
}
@Override
public int getSize() {
return 1;
}
@Override
public Object getData(int index) {
return null;
}
@Override
public Object run(Object data) {
double sum = 0;
f1 = f1.copy();
if (order == 0) {
for (int i = 0; i < x.length; i++) {
f1.initialise0(x[i]);
for (int j = 0; j < size; j++) {
sum += f1.eval(j);
}
}
} else if (order == 1) {
for (int i = 0; i < x.length; i++) {
f1.initialise1(x[i]);
for (int j = 0; j < size; j++) {
sum += f1.eval(j, dyda);
}
}
} else {
for (int i = 0; i < x.length; i++) {
f2.initialise2(x[i]);
for (int j = 0; j < size; j++) {
sum += f2.eval2(j, dyda, d2yda2);
}
}
}
return sum;
}
}
// Speed test verses equivalent Gaussian2DFunction
@SpeedTag
@Test
void functionIsFasterThanEquivalentGaussian2DFunction() {
Assumptions.assumeTrue(TestSettings.allow(TestComplexity.MEDIUM));
final int flags = this.flags & ~GaussianFunctionFactory.FIT_ERF;
final Gaussian2DFunction gf = GaussianFunctionFactory.create2D(1, maxx, maxy, flags, zModel);
final boolean zDepth = (flags & GaussianFunctionFactory.FIT_Z) != 0;
final LocalList<double[]> params1 = new LocalList<>();
final LocalList<double[]> params2 = new LocalList<>();
for (final double background : testbackground) {
// Peak 1
for (final double signal1 : testsignal1) {
for (final double cx1 : testcx1) {
for (final double cy1 : testcy1) {
for (final double cz1 : testcz1) {
for (final double[] w1 : testw1) {
for (final double angle1 : testangle1) {
double[] params =
createParameters(background, signal1, cx1, cy1, cz1, w1[0], w1[1], angle1);
params1.add(params);
if (zDepth) {
// Change to a standard free circular function
params = params.clone();
params[Gaussian2DFunction.X_SD] *=
zModel.getSx(params[Gaussian2DFunction.Z_POSITION]);
params[Gaussian2DFunction.Y_SD] *=
zModel.getSy(params[Gaussian2DFunction.Z_POSITION]);
params[Gaussian2DFunction.Z_POSITION] = 0;
params2.add(params);
}
}
}
}
}
}
}
}
final double[][] x = params1.toArray(new double[0][]);
final double[][] x2 = (zDepth) ? params2.toArray(new double[0][]) : x;
final int runs = 10000 / x.length;
final TimingService ts = new TimingService(runs);
ts.execute(new FunctionTimingTask(gf, x2, 1));
ts.execute(new FunctionTimingTask(gf, x2, 0));
ts.execute(new FunctionTimingTask(f1, x, 2));
ts.execute(new FunctionTimingTask(f1, x, 1));
ts.execute(new FunctionTimingTask(f1, x, 0));
final int size = ts.getSize();
ts.repeat(size);
if (logger.isLoggable(Level.INFO)) {
logger.info(ts.getReport());
}
for (int i = 1; i <= 2; i++) {
final TimingResult slow = ts.get(-i - 3);
final TimingResult fast = ts.get(-i);
logger.log(TestLogUtils.getTimingRecord(slow, fast));
}
}
@Test
void functionComputesGradientForEach() {
final ErfGaussian2DFunction f1 = (ErfGaussian2DFunction) this.f1;
final int n = f1.size();
final double[] du_da = new double[f1.getNumberOfGradients()];
final double[] du_db = new double[f1.getNumberOfGradients()];
final double[] d2u_da2 = new double[f1.getNumberOfGradients()];
final double[] values = new double[n];
final double[][] jacobian = new double[n][];
final double[][] jacobian2 = new double[n][];
for (final double background : testbackground) {
// Peak 1
for (final double signal1 : testsignal1) {
for (final double cx1 : testcx1) {
for (final double cy1 : testcy1) {
for (final double cz1 : testcz1) {
for (final double[] w1 : testw1) {
for (final double angle1 : testangle1) {
final double[] a =
createParameters(background, signal1, cx1, cy1, cz1, w1[0], w1[1], angle1);
f1.initialiseExtended2(a);
// Compute single
for (int i = 0; i < n; i++) {
final double o1 = f1.eval(i, du_da);
final double o2 = f1.eval2(i, du_db, d2u_da2);
Assertions.assertEquals(o1, o2, 1e-10, "Value");
Assertions.assertArrayEquals(du_da, du_db, 1e-10, "Jacobian!=Jacobian");
values[i] = o1;
jacobian[i] = du_da.clone();
jacobian2[i] = d2u_da2.clone();
}
// Use procedures
f1.forEach(new ValueProcedure() {
int index = 0;
@Override
public void execute(double value) {
Assertions.assertEquals(values[index], value, 1e-10, "Value ValueProcedure");
index++;
}
});
f1.forEach(new Gradient1Procedure() {
int index = 0;
@Override
public void execute(double value, double[] dyDa) {
Assertions.assertEquals(values[index], value, 1e-10,
"Value Gradient1Procedure");
Assertions.assertArrayEquals(jacobian[index], dyDa, 1e-10,
"du_da Gradient1Procedure");
index++;
}
});
f1.forEach(new Gradient2Procedure() {
int index = 0;
@Override
public void execute(double value, double[] dyDa, double[] d2yDa2) {
Assertions.assertEquals(values[index], value, 1e-10,
"Value Gradient2Procedure");
Assertions.assertArrayEquals(jacobian[index], dyDa, 1e-10,
"du_da Gradient2Procedure");
Assertions.assertArrayEquals(jacobian2[index], d2yDa2, 1e-10,
"d2u_da2 Gradient2Procedure");
index++;
}
});
f1.forEach(new ExtendedGradient2Procedure() {
int index = 0;
@Override
public void executeExtended(double value, double[] dyDa, double[] d2yDaDb) {
Assertions.assertEquals(values[index], value, 1e-10,
"Value ExtendedGradient2Procedure");
Assertions.assertArrayEquals(jacobian[index], dyDa, 1e-10,
"du_da ExtendedGradient2Procedure");
for (int j = 0, k = 0; j < d2u_da2.length; j++, k += d2u_da2.length + 1) {
d2u_da2[j] = d2yDaDb[k];
}
Assertions.assertArrayEquals(jacobian2[index], d2u_da2, 1e-10,
"d2u_da2 Gradient2Procedure");
index++;
}
});
}
}
}
}
}
}
}
}
@Test
void functionComputesExtendedGradientForEach() {
final ErfGaussian2DFunction f1 = (ErfGaussian2DFunction) this.f1;
final int nparams = f1.getNumberOfGradients();
final int[] gradientIndices = f1.gradientIndices();
final ErfGaussian2DFunction[] fHigh = new ErfGaussian2DFunction[nparams];
final ErfGaussian2DFunction[] fLow = new ErfGaussian2DFunction[nparams];
final double[] delta = new double[nparams];
for (int j = 0; j < nparams; j++) {
fHigh[j] = f1.copy();
fLow[j] = f1.copy();
}
for (final double background : testbackground) {
// Peak 1
for (final double signal1 : testsignal1) {
for (final double cx1 : testcx1) {
for (final double cy1 : testcy1) {
for (final double cz1 : testcz1) {
for (final double[] w1 : testw1) {
for (final double angle1 : testangle1) {
final double[] a =
createParameters(background, signal1, cx1, cy1, cz1, w1[0], w1[1], angle1);
f1.initialiseExtended2(a);
// Create a set of functions initialised +/- delta in each parameter
for (int j = 0; j < nparams; j++) {
final int targetParameter = gradientIndices[j];
// Numerically solve gradient.
// Calculate the step size h to be an exact numerical representation
final double xx = a[targetParameter];
// Get h to minimise roundoff error
final double h = Precision.representableDelta(xx, stepH);
// Evaluate at (x+h) and (x-h)
a[targetParameter] = xx + h;
fHigh[j].initialise1(a.clone());
a[targetParameter] = xx - h;
fLow[j].initialise1(a.clone());
a[targetParameter] = xx;
delta[j] = 2 * h;
}
f1.forEach(new ExtendedGradient2Procedure() {
int index = -1;
final double[] duDa = new double[f1.getNumberOfGradients()];
final double[] duDb = new double[f1.getNumberOfGradients()];
@Override
public void executeExtended(double value, double[] dyDa, double[] d2yDaDb) {
index++;
final DenseMatrix64F m = DenseMatrix64F.wrap(nparams, nparams, d2yDaDb);
for (int j = 0; j < nparams; j++) {
// Evaluate the function +/- delta for parameter j
fHigh[j].eval(index, duDa);
fLow[j].eval(index, duDb);
// Check the gradient with respect to parameter k
for (int k = 0; k < nparams; k++) {
final double gradient = (duDa[k] - duDb[k]) / delta[j];
final boolean ok =
eq.almostEqualRelativeOrAbsolute(gradient, m.get(j, k));
if (!ok) {
logger.log(TestLogUtils.getRecord(Level.INFO, "%d [%d,%d] %f ?= %f",
index, j, k, gradient, m.get(j, k)));
Assertions.fail(String.format("%d [%d,%d] %f != %f", index, j, k,
gradient, m.get(j, k)));
}
}
}
}
});
}
}
}
}
}
}
}
}
@Test
void functionComputesGradientForEachWith2Peaks() {
Assumptions.assumeTrue(null != f2);
final ErfGaussian2DFunction f2 = (ErfGaussian2DFunction) this.f2;
final int n = f2.size();
final double[] du_da = new double[f2.getNumberOfGradients()];
final double[] du_db = new double[f2.getNumberOfGradients()];
final double[] d2u_da2 = new double[f2.getNumberOfGradients()];
final double[] values = new double[n];
final double[][] jacobian = new double[n][];
final double[][] jacobian2 = new double[n][];
for (final double background : testbackground) {
// Peak 1
for (final double signal1 : testsignal1) {
for (final double cx1 : testcx1) {
for (final double cy1 : testcy1) {
for (final double cz1 : testcz1) {
for (final double[] w1 : testw1) {
for (final double angle1 : testangle1) {
// Peak 2
for (final double signal2 : testsignal2) {
for (final double cx2 : testcx2) {
for (final double cy2 : testcy2) {
for (final double cz2 : testcz2) {
for (final double[] w2 : testw2) {
for (final double angle2 : testangle2) {
final double[] a =
createParameters(background, signal1, cx1, cy1, cz1, w1[0], w1[1],
angle1, signal2, cx2, cy2, cz2, w2[0], w2[1], angle2);
f2.initialiseExtended2(a);
// Compute single
for (int i = 0; i < n; i++) {
final double o1 = f2.eval(i, du_da);
final double o2 = f2.eval2(i, du_db, d2u_da2);
Assertions.assertEquals(o1, o2, 1e-10, "Value");
Assertions.assertArrayEquals(du_da, du_db, 1e-10,
"Jacobian!=Jacobian");
values[i] = o1;
jacobian[i] = du_da.clone();
jacobian2[i] = d2u_da2.clone();
}
// Use procedures
f2.forEach(new ValueProcedure() {
int index = 0;
@Override
public void execute(double value) {
Assertions.assertEquals(values[index], value, 1e-10,
"Value ValueProcedure");
index++;
}
});
f2.forEach(new Gradient1Procedure() {
int index = 0;
@Override
public void execute(double value, double[] dyDa) {
Assertions.assertEquals(values[index], value, 1e-10,
"Value Gradient1Procedure");
Assertions.assertArrayEquals(jacobian[index], dyDa, 1e-10,
"du_da Gradient1Procedure");
index++;
}
});
f2.forEach(new Gradient2Procedure() {
int index = 0;
@Override
public void execute(double value, double[] dyDa, double[] d2yDa2) {
Assertions.assertEquals(values[index], value, 1e-10,
"Value Gradient2Procedure");
Assertions.assertArrayEquals(jacobian[index], dyDa, 1e-10,
"du_da Gradient2Procedure");
Assertions.assertArrayEquals(jacobian2[index], d2yDa2, 1e-10,
"d2u_da2 Gradient2Procedure");
index++;
}
});
f2.forEach(new ExtendedGradient2Procedure() {
int index = 0;
@Override
public void executeExtended(double value, double[] dyDa,
double[] d2yDaDb) {
Assertions.assertEquals(
values[index], value, 1e-10,
"Value ExtendedGradient2Procedure");
Assertions.assertArrayEquals(
jacobian[index], dyDa, 1e-10,
"du_da ExtendedGradient2Procedure");
for (int j = 0, k = 0; j < d2u_da2.length;
j++, k += d2u_da2.length + 1) {
d2u_da2[j] = d2yDaDb[k];
}
Assertions.assertArrayEquals(jacobian2[index], d2u_da2, 1e-10,
"d2u_da2 Gradient2Procedure");
index++;
}
});
}
}
}
}
}
}
}
}
}
}
}
}
}
}
@Test
void functionComputesExtendedGradientForEachWith2Peaks() {
Assumptions.assumeTrue(null != f2);
final ErfGaussian2DFunction f2 = (ErfGaussian2DFunction) this.f2;
final int nparams = f2.getNumberOfGradients();
final int[] gradientIndices = f2.gradientIndices();
final ErfGaussian2DFunction[] fHigh = new ErfGaussian2DFunction[nparams];
final ErfGaussian2DFunction[] fLow = new ErfGaussian2DFunction[nparams];
final double[] delta = new double[nparams];
for (int j = 0; j < nparams; j++) {
fHigh[j] = f2.copy();
fLow[j] = f2.copy();
}
for (final double background : testbackground) {
// Peak 1
for (final double signal1 : testsignal1) {
for (final double cx1 : testcx1) {
for (final double cy1 : testcy1) {
for (final double cz1 : testcz1) {
for (final double[] w1 : testw1) {
for (final double angle1 : testangle1) {
// Peak 2
for (final double signal2 : testsignal2) {
for (final double cx2 : testcx2) {
for (final double cy2 : testcy2) {
for (final double cz2 : testcz2) {
for (final double[] w2 : testw2) {
for (final double angle2 : testangle2) {
final double[] a =
createParameters(background, signal1, cx1, cy1, cz1, w1[0], w1[1],
angle1, signal2, cx2, cy2, cz2, w2[0], w2[1], angle2);
f2.initialiseExtended2(a);
// Create a set of functions initialised +/- delta in each parameter
for (int j = 0; j < nparams; j++) {
final int targetParameter = gradientIndices[j];
// Numerically solve gradient.
// Calculate the step size h to be an exact numerical representation
final double xx = a[targetParameter];
// Get h to minimise roundoff error
final double h = Precision.representableDelta(xx, stepH);
// Evaluate at (x+h) and (x-h)
a[targetParameter] = xx + h;
fHigh[j].initialise1(a.clone());
a[targetParameter] = xx - h;
fLow[j].initialise1(a.clone());
a[targetParameter] = xx;
delta[j] = 2 * h;
}
f2.forEach(new ExtendedGradient2Procedure() {
int index = -1;
final double[] duDa = new double[f2.getNumberOfGradients()];
final double[] duDb = new double[f2.getNumberOfGradients()];
@Override
public void executeExtended(double value, double[] dyDa,
double[] d2yDaDb) {
index++;
// if (i!=f2.size()/2) return;
final DenseMatrix64F m =
DenseMatrix64F.wrap(nparams, nparams, d2yDaDb);
for (int j = 0; j < nparams; j++) {
// Evaluate the function +/- delta for parameter j
fHigh[j].eval(index, duDa);
fLow[j].eval(index, duDb);
// Check the gradient with respect to parameter k
for (int k = 0; k < nparams; k++) {
final double gradient = (duDa[k] - duDb[k]) / delta[j];
final boolean ok =
eq.almostEqualRelativeOrAbsolute(gradient, m.get(j, k));
// logger.log(TestLog.getRecord(Level.FINE,
// "%d [%d,%d] %f ?= %f", i, j, k,
// gradient, m.get(j, k)));
if (!ok) {
Assertions.fail(String.format("%d [%d,%d] %f != %f", index,
j, k, gradient, m.get(j, k)));
}
}
}
}
});
// return;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
abstract static class SimpleProcedure {
ErfGaussian2DFunction func;
double sum = 0;
SimpleProcedure(ErfGaussian2DFunction func) {
this.func = func;
}
void reset() {
sum = 0;
}
void run(double[] a) {
func = func.copy();
initialise(a);
forEach();
}
abstract void initialise(double[] a);
abstract void forEach();
}
static class Procedure0 extends SimpleProcedure implements ValueProcedure {
Procedure0(ErfGaussian2DFunction func) {
super(func);
}
@Override
void initialise(double[] a) {
func.initialise0(a);
}
@Override
void forEach() {
func.forEach(this);
}
@Override
public void execute(double value) {
sum += value;
}
}
static class Procedure1 extends SimpleProcedure implements Gradient1Procedure {
Procedure1(ErfGaussian2DFunction func) {
super(func);
}
@Override
void initialise(double[] a) {
func.initialise1(a);
}
@Override
void forEach() {
func.forEach(this);
}
@Override
public void execute(double value, double[] dyDa) {
sum += value;
}
}
static class Procedure2 extends SimpleProcedure implements Gradient2Procedure {
Procedure2(ErfGaussian2DFunction func) {
super(func);
}
@Override
void initialise(double[] a) {
func.initialise2(a);
}
@Override
void forEach() {
func.forEach(this);
}
@Override
public void execute(double value, double[] dyDa, double[] d2yDa2) {
sum += value;
}
}
private static class ForEachTimingTask extends BaseTimingTask {
double[][] x;
SimpleProcedure procedure;
public ForEachTimingTask(ErfGaussian2DFunction func, double[][] x, int order) {
super(func.getClass().getSimpleName() + " " + order + " forEach");
this.x = x;
if (order == 0) {
procedure = new Procedure0(func);
} else if (order == 1) {
procedure = new Procedure1(func);
} else {
procedure = new Procedure2(func);
}
}
@Override
public int getSize() {
return 1;
}
@Override
public Object getData(int index) {
return null;
}
@Override
public Object run(Object data) {
procedure.reset();
for (int i = 0; i < x.length; i++) {
procedure.run(x[i]);
}
return procedure.sum;
}
}
// Speed test forEach verses equivalent eval() function calls
@SpeedTag
@Test
void functionIsFasterUsingForEach() {
Assumptions.assumeTrue(TestSettings.allow(TestComplexity.MEDIUM));
final ErfGaussian2DFunction f1 = (ErfGaussian2DFunction) this.f1;
final LocalList<double[]> params = new LocalList<>();
for (final double background : testbackground) {
// Peak 1
for (final double signal1 : testsignal1) {
for (final double cx1 : testcx1) {
for (final double cy1 : testcy1) {
for (final double cz1 : testcz1) {
for (final double[] w1 : testw1) {
for (final double angle1 : testangle1) {
final double[] a =
createParameters(background, signal1, cx1, cy1, cz1, w1[0], w1[1], angle1);
params.add(a);
}
}
}
}
}
}
}
final double[][] x = params.toArray(new double[0][]);
final int runs = 10000 / x.length;
final TimingService ts = new TimingService(runs);
ts.execute(new FunctionTimingTask(f1, x, 2));
ts.execute(new FunctionTimingTask(f1, x, 1));
ts.execute(new FunctionTimingTask(f1, x, 0));
ts.execute(new ForEachTimingTask(f1, x, 2));
ts.execute(new ForEachTimingTask(f1, x, 1));
ts.execute(new ForEachTimingTask(f1, x, 0));
final int size = ts.getSize();
ts.repeat(size);
if (logger.isLoggable(Level.INFO)) {
logger.info(ts.getReport());
}
for (int i = 1; i <= 3; i++) {
final TimingResult slow = ts.get(-i - 3);
final TimingResult fast = ts.get(-i);
logger.log(TestLogUtils.getTimingRecord(slow, fast));
}
}
@Test
void functionCanComputeIntegral() {
final DoubleDoubleBiPredicate predicate = TestHelper.doublesAreClose(1e-8, 0);
double[] params;
for (final double background : testbackground) {
// Peak 1
for (final double signal1 : testsignal1) {
for (final double cx1 : testcx1) {
for (final double cy1 : testcy1) {
for (final double cz1 : testcz1) {
for (final double[] w1 : testw1) {
for (final double angle1 : testangle1) {
params =
createParameters(background, signal1, cx1, cy1, cz1, w1[0], w1[1], angle1);
final double e = new IntegralValueProcedure().getIntegral(f1, params);
final double o = f1.integral(params);
TestAssertions.assertTest(e, o, predicate);
}
}
}
}
}
}
}
}
@Test
void computeIntegralIsFaster() {
Assumptions.assumeTrue(TestSettings.allow(TestComplexity.MEDIUM));
final LocalList<double[]> p = new LocalList<>();
for (final double background : testbackground) {
// Peak 1
for (final double signal1 : testsignal1) {
for (final double cx1 : testcx1) {
for (final double cy1 : testcy1) {
for (final double cz1 : testcz1) {
for (final double[] w1 : testw1) {
for (final double angle1 : testangle1) {
p.add(createParameters(background, signal1, cx1, cy1, cz1, w1[0], w1[1], angle1));
}
}
}
}
}
}
}
final int n = (int) Math.ceil(10000.0 / p.size());
double s1 = 0;
double s2 = 0;
long t1 = System.nanoTime();
for (int i = n; i-- > 0;) {
for (int j = p.size(); j-- > 0;) {
s1 += new IntegralValueProcedure().getIntegral(f1, p.unsafeGet(j));
}
}
long t2 = System.nanoTime();
for (int i = n; i-- > 0;) {
for (int j = p.size(); j-- > 0;) {
s2 += f1.integral(p.unsafeGet(j));
}
}
final long t3 = System.nanoTime();
t1 = t2 - t1;
t2 = t3 - t2;
logger.log(TestLogUtils.getRecord(Level.INFO, "computeIntegralIsFaster %s %d vs %d (%gx)",
f1.getClass().getSimpleName(), t1, t2, (double) t1 / t2));
TestAssertions.assertTest(s1, s2, TestHelper.doublesAreClose(1e-3, 0));
Assertions.assertTrue(t2 < t1);
}
@Test
void functionCanComputeIntegralWith2Peaks() {
Assumptions.assumeTrue(null != f2);
final DoubleDoubleBiPredicate predicate = TestHelper.doublesAreClose(1e-8, 0);
double[] params;
for (final double background : testbackground) {
// Peak 1
for (final double signal1 : testsignal1) {
for (final double cx1 : testcx1) {
for (final double cy1 : testcy1) {
for (final double cz1 : testcz1) {
for (final double[] w1 : testw1) {
for (final double angle1 : testangle1) {
// Peak 2
for (final double signal2 : testsignal2) {
for (final double cx2 : testcx2) {
for (final double cy2 : testcy2) {
for (final double cz2 : testcz2) {
for (final double[] w2 : testw2) {
for (final double angle2 : testangle2) {
params = createParameters(background, signal1, cx1, cy1, cz1, w1[0],
w1[1], angle1, signal2, cx2, cy2, cz2, w2[0], w2[1], angle2);
final double e = new IntegralValueProcedure().getIntegral(f2, params);
final double o = f2.integral(params);
TestAssertions.assertTest(e, o, predicate);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
@Test
void computeIntegralIsFasterWith2Peaks() {
Assumptions.assumeTrue(TestSettings.allow(TestComplexity.MEDIUM));
Assumptions.assumeTrue(null != f2);
final LocalList<double[]> p = new LocalList<>();
for (final double background : testbackground) {
// Peak 1
for (final double signal1 : testsignal1) {
for (final double cx1 : testcx1) {
for (final double cy1 : testcy1) {
for (final double cz1 : testcz1) {
for (final double[] w1 : testw1) {
for (final double angle1 : testangle1) {
// Peak 2
for (final double signal2 : testsignal2) {
for (final double cx2 : testcx2) {
for (final double cy2 : testcy2) {
for (final double cz2 : testcz2) {
for (final double[] w2 : testw2) {
for (final double angle2 : testangle2) {
p.add(createParameters(background, signal1, cx1, cy1, cz1, w1[0],
w1[1], angle1, signal2, cx2, cy2, cz2, w2[0], w2[1], angle2));
}
}
}
}
}
}
}
}
}
}
}
}
}
final int n = (int) Math.ceil(10000.0 / p.size());
double s1 = 0;
double s2 = 0;
long t1 = System.nanoTime();
for (int i = n; i-- > 0;) {
for (int j = p.size(); j-- > 0;) {
s1 += new IntegralValueProcedure().getIntegral(f2, p.unsafeGet(j));
}
}
long t2 = System.nanoTime();
for (int i = n; i-- > 0;) {
for (int j = p.size(); j-- > 0;) {
s2 += f2.integral(p.unsafeGet(j));
}
}
final long t3 = System.nanoTime();
t1 = t2 - t1;
t2 = t3 - t2;
logger.log(
TestLogUtils.getRecord(Level.INFO, "computeIntegralIsFasterWith2Peaks %s %d vs %d (%gx)",
f1.getClass().getSimpleName(), t1, t2, (double) t1 / t2));
TestAssertions.assertTest(s1, s2, TestHelper.doublesAreClose(1e-3, 0));
Assertions.assertTrue(t2 < t1);
}
}
| aherbert/GDSC-SMLM | src/test/java/uk/ac/sussex/gdsc/smlm/function/gaussian/erf/ErfGaussian2DFunctionTest.java | Java | gpl-3.0 | 48,790 |