repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
zhangjianying/12306-android-Decompile | src/org/apache/commons/codec/binary/BinaryCodec.java | 5027 | package org.apache.commons.codec.binary;
import org.apache.commons.codec.BinaryDecoder;
import org.apache.commons.codec.BinaryEncoder;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.EncoderException;
public class BinaryCodec
implements BinaryDecoder, BinaryEncoder
{
private static final int[] BITS;
private static final int BIT_0 = 1;
private static final int BIT_1 = 2;
private static final int BIT_2 = 4;
private static final int BIT_3 = 8;
private static final int BIT_4 = 16;
private static final int BIT_5 = 32;
private static final int BIT_6 = 64;
private static final int BIT_7 = 128;
private static final byte[] EMPTY_BYTE_ARRAY;
private static final char[] EMPTY_CHAR_ARRAY = new char[0];
static
{
EMPTY_BYTE_ARRAY = new byte[0];
BITS = new int[] { 1, 2, 4, 8, 16, 32, 64, 128 };
}
public static byte[] fromAscii(byte[] paramArrayOfByte)
{
byte[] arrayOfByte;
if (isEmpty(paramArrayOfByte))
arrayOfByte = EMPTY_BYTE_ARRAY;
while (true)
{
return arrayOfByte;
arrayOfByte = new byte[paramArrayOfByte.length >> 3];
int i = 0;
for (int j = -1 + paramArrayOfByte.length; i < arrayOfByte.length; j -= 8)
{
for (int k = 0; k < BITS.length; k++)
{
if (paramArrayOfByte[(j - k)] != 49)
continue;
arrayOfByte[i] = (byte)(arrayOfByte[i] | BITS[k]);
}
i++;
}
}
}
public static byte[] fromAscii(char[] paramArrayOfChar)
{
byte[] arrayOfByte;
if ((paramArrayOfChar == null) || (paramArrayOfChar.length == 0))
arrayOfByte = EMPTY_BYTE_ARRAY;
while (true)
{
return arrayOfByte;
arrayOfByte = new byte[paramArrayOfChar.length >> 3];
int i = 0;
for (int j = -1 + paramArrayOfChar.length; i < arrayOfByte.length; j -= 8)
{
for (int k = 0; k < BITS.length; k++)
{
if (paramArrayOfChar[(j - k)] != '1')
continue;
arrayOfByte[i] = (byte)(arrayOfByte[i] | BITS[k]);
}
i++;
}
}
}
private static boolean isEmpty(byte[] paramArrayOfByte)
{
return (paramArrayOfByte == null) || (paramArrayOfByte.length == 0);
}
public static byte[] toAsciiBytes(byte[] paramArrayOfByte)
{
byte[] arrayOfByte;
if (isEmpty(paramArrayOfByte))
arrayOfByte = EMPTY_BYTE_ARRAY;
while (true)
{
return arrayOfByte;
arrayOfByte = new byte[paramArrayOfByte.length << 3];
int i = 0;
for (int j = -1 + arrayOfByte.length; i < paramArrayOfByte.length; j -= 8)
{
int k = 0;
if (k < BITS.length)
{
if ((paramArrayOfByte[i] & BITS[k]) == 0)
arrayOfByte[(j - k)] = 48;
while (true)
{
k++;
break;
arrayOfByte[(j - k)] = 49;
}
}
i++;
}
}
}
public static char[] toAsciiChars(byte[] paramArrayOfByte)
{
char[] arrayOfChar;
if (isEmpty(paramArrayOfByte))
arrayOfChar = EMPTY_CHAR_ARRAY;
while (true)
{
return arrayOfChar;
arrayOfChar = new char[paramArrayOfByte.length << 3];
int i = 0;
for (int j = -1 + arrayOfChar.length; i < paramArrayOfByte.length; j -= 8)
{
int k = 0;
if (k < BITS.length)
{
if ((paramArrayOfByte[i] & BITS[k]) == 0)
arrayOfChar[(j - k)] = '0';
while (true)
{
k++;
break;
arrayOfChar[(j - k)] = '1';
}
}
i++;
}
}
}
public static String toAsciiString(byte[] paramArrayOfByte)
{
return new String(toAsciiChars(paramArrayOfByte));
}
public Object decode(Object paramObject)
throws DecoderException
{
if (paramObject == null)
return EMPTY_BYTE_ARRAY;
if ((paramObject instanceof byte[]))
return fromAscii((byte[])(byte[])paramObject);
if ((paramObject instanceof char[]))
return fromAscii((char[])(char[])paramObject);
if ((paramObject instanceof String))
return fromAscii(((String)paramObject).toCharArray());
throw new DecoderException("argument not a byte array");
}
public byte[] decode(byte[] paramArrayOfByte)
{
return fromAscii(paramArrayOfByte);
}
public Object encode(Object paramObject)
throws EncoderException
{
if (!(paramObject instanceof byte[]))
throw new EncoderException("argument not a byte array");
return toAsciiChars((byte[])(byte[])paramObject);
}
public byte[] encode(byte[] paramArrayOfByte)
{
return toAsciiBytes(paramArrayOfByte);
}
public byte[] toByteArray(String paramString)
{
if (paramString == null)
return EMPTY_BYTE_ARRAY;
return fromAscii(paramString.toCharArray());
}
}
/* Location: D:\开发工具\dex2jar-0.0.9.13\classes_dex2jar.jar
* Qualified Name: org.apache.commons.codec.binary.BinaryCodec
* JD-Core Version: 0.6.0
*/ | gpl-3.0 |
sjholden/traveller-universe | travelleruniverse/world/world.py | 1259 | '''
Created on May 30, 2017
@author: Sam Holden <sholden@holden.id.au>
'''
class World(object):
'''
classdocs
'''
def __init__(self, port, size, atmo, hydro, pop, govt, law, tech, bases=None, extra=None):
'''
Constructor
'''
self._port = port
self._size = size
self._atmo = atmo
self._hydro = hydro
self._pop = pop
self._govt = govt
self._law = law
self._tech = tech
if bases:
self._bases = bases
else:
self._bases = []
if extra:
self._extra = extra
else:
self._extra = {}
@property
def port(self): return self._port
@property
def size(self): return self._size
@property
def atmo(self): return self._atmo
@property
def hydro(self): return self._hydro
@property
def pop(self): return self._pop
@property
def govt(self): return self._govt
@property
def law(self): return self._law
@property
def tech(self): return self._tech
@property
def bases(self): return self._bases
@property
def extra(self): return self._extra
| gpl-3.0 |
piwik/piwik | plugins/Tour/Engagement/Challenge.php | 4123 | <?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\Tour\Engagement;
use Piwik\Piwik;
use Piwik\Settings\Storage\Backend\PluginSettingsTable;
/**
* Defines a new challenge which a super user needs to complete in order to become a "Matomo expert".
* Plugins can add new challenges by listening to the {@hook Tour.filterChallenges} event.
*
* @since 3.10.0
* @api
*/
abstract class Challenge
{
const APPENDIX_SKIPPED = '_skipped';
const APPENDIX_COMPLETED = '_completed';
private static $settings = null;
/**
* The human readable name that will be shown in the onboarding widget. Should be max 3 or 4 words and represent an
* action, like "Add a report"
* @return string
*/
abstract public function getName();
/**
* A short unique ID that represents this challenge, for example "add_report".
* @return string
*/
abstract public function getId();
/**
* By default, we attribute a challenge as soon as it was completed manually by calling `$challenge->setCompleted()`.
*
* If we can detect whether a particular user has already completed a challenge in the past then we mark it automatically
* as completed. We can detect this automatically eg by querying the DB and check if a particular login has for example
* created a segment etc. We do this only if the query is supposed to be fast. Otherwise we would fallback to the manual
* way.
*
* @return bool
*/
public function isCompleted()
{
return $this->hasAttribute(self::APPENDIX_COMPLETED);
}
/**
* A detailed description that describes the value of the action the user needs to complete, or some tips on how
* to complete this challenge. Will be shown when hovering a challenge name.
* @return string
*/
public function getDescription()
{
return '';
}
/**
* A URL that has more information about how to complete the given event or a URL within the Matomo app to directly
* complete a challenge. For example "add_user" challenge could directly link to the user management.
* @return string
*/
public function getUrl()
{
return '';
}
private function getPluginSettingsInstance()
{
return new PluginSettingsTable('Tour', Piwik::getCurrentUserLogin());
}
private function getSettings()
{
if (!isset(self::$settings)) {
$pluginSettings = $this->getPluginSettingsInstance();
self::$settings = $pluginSettings->load();
}
return self::$settings;
}
public static function clearCache()
{
self::$settings = null;
}
/**
* Detect if the challenge was skipped.
* @ignore
* @return bool
*/
public function isSkipped()
{
return $this->hasAttribute(self::APPENDIX_SKIPPED);
}
/**
* Skip this challenge.
* @ignore
* @return bool
*/
public function skipChallenge()
{
$this->storeAttribute(self::APPENDIX_SKIPPED);
}
/**
* Set this challenge was completed successfully by the current user. Only works for a super user.
* @return bool
*/
public function setCompleted()
{
$this->storeAttribute(self::APPENDIX_COMPLETED);
}
private function hasAttribute($appendix)
{
$settings = $this->getSettings();
if (!empty($settings[$this->getId() . $appendix])) {
return true;
}
return false;
}
private function storeAttribute($appendix)
{
if (!Piwik::hasUserSuperUserAccess()) {
return;
}
$pluginSettings = $this->getPluginSettingsInstance();
$settings = $pluginSettings->load();
if (empty($settings[$this->getId() . $appendix])) {
$settings[$this->getId() . $appendix] = '1';
$pluginSettings->save($settings);
self::clearCache();
}
}
} | gpl-3.0 |
donatellosantoro/Llunatic | LunaticGUI/gui/src/it/unibas/lunatic/gui/window/db/actions/ActionFirstPage.java | 1059 | package it.unibas.lunatic.gui.window.db.actions;
import it.unibas.lunatic.gui.window.db.TablePaginationSupport;
import it.unibas.lunatic.gui.window.db.PagedTableView;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import static javax.swing.Action.SMALL_ICON;
import org.openide.util.ImageUtilities;
public class ActionFirstPage extends AbstractAction {
private final TablePaginationSupport offsetCalculator;
private final PagedTableView pagedTableView;
public ActionFirstPage(PagedTableView pagedTableView, TablePaginationSupport tablePaginationSupport) {
this.offsetCalculator = tablePaginationSupport;
this.pagedTableView = pagedTableView;
putValue(SMALL_ICON, ImageUtilities.loadImage("it/unibas/lunatic/icons/navigate_beginning.png"));
}
@Override
public void actionPerformed(ActionEvent e) {
int newOffset = offsetCalculator.getFirstPageOffset();
if (newOffset != pagedTableView.getOffset()) {
pagedTableView.updatePage(newOffset);
}
}
}
| gpl-3.0 |
sonidosmutantes/apicultor | apicultor/tests/Test_API.py | 6785 | #!/usr/bin/python2
# -*- coding: UTF-8 -*-
import unittest
import urllib.request, urllib.error, urllib.parse
URL_BASE = "http://127.0.0.1:5000" #TODO: get from a config file
# URL_BASE = "http://api.redpanal.org.ar"
def count_response_lines(response):
count = 0
for line in response.split('\n'):
count += 1
return count
class Test_REST_API(unittest.TestCase):
def test_list_pistas(self):
"""
Lista pistas DB
"""
call = '/list/pistas'
response = urllib.request.urlopen(URL_BASE + call).read()
# for file in response.split('\n'):
# print(file)
self.assertNotEqual(response.find("1288.ogg"), -1)
self.assertNotEqual(response.find("795.ogg"), -1)
def test_mir_samples_hfc_greater(self):
""" HFC > 40. """
call = '/search/mir/samples/HFC/greaterthan/40000/5' #max 5 results
response = urllib.request.urlopen(URL_BASE + call).read()
self.assertNotEqual(response.find("984_sample4.wav"), -1)
self.assertNotEqual(response.find("984_sample1.wav"), -1)
def test_mir_samples_hfc_less(self):
""" HFC < 1. """
call = '/search/mir/samples/HFC/lessthan/1000/5' #max 5 results
response = urllib.request.urlopen(URL_BASE + call).read()
self.assertNotEqual(response.find("982_sample3.wav"), -1)
# self.assertNotEqual(response.find("1288_sample3.wav"), -1)
def test_mir_samples_duration_greater(self):
""" Duration > 2 seg """
call = '/search/mir/samples/duration/greaterthan/2000/11' #max 10 results
response = urllib.request.urlopen(URL_BASE + call).read()
self.assertNotEqual(response.find("982_sample3.wav"), -1)
self.assertNotEqual(response.find("795_sample0.wav"), -1)
self.assertNotEqual(response.find("126_sample1.wav"), -1)
self.assertNotEqual(response.find("983_sample3.wav"), -1)
self.assertNotEqual(response.find("983_sample2.wav"), -1)
self.assertNotEqual(response.find("984_sample4.wav"), -1)
self.assertNotEqual(response.find("1288_sample3.wav"), -1)
self.assertNotEqual(response.find("982_sample0.wav"), -1)
self.assertNotEqual(response.find("982_sample3.wav"), -1)
self.assertNotEqual(response.find("126_sample3.wav"), -1)
def test_mir_samples_duration_less(self):
""" Duration < 1 seg """
call = '/search/mir/samples/duration/lessthan/1000/5' #max 5 results
response = urllib.request.urlopen(URL_BASE + call).read()
self.assertNotEqual(response.find("126_sample2.wav"), -1)
# self.assertNotEqual(response.find("795_sample4.wav"), -1)
# self.assertNotEqual(response.find("795_sample2.wav"), -1)
def test_list_samples(self):
"""
Lista samples DB
"""
call = '/list/samples'
response = urllib.request.urlopen(URL_BASE + call).read()
# for file in response.split('\n'):
# print(file)
# self.assertNotEqual(response.find(".wav"), -1)
def test_get_pista_info(self):
"""
Getinfo de la pista (json)
"""
call = '/pistas/126'
response = urllib.request.urlopen(URL_BASE + call).read()
#print(response)
self.assertNotEqual(response.find("audio"), -1)
self.assertNotEqual(response.find("desc"), -1)
self.assertNotEqual(response.find("126"), -1)
def test_get_pista_file_path_audio(self):
"""
Get audio file path by ID
"""
call = '/pistas/126/audio'
response = urllib.request.urlopen(URL_BASE + call).read()
#print(response)
self.assertNotEqual(response.find("126"), -1)
def test_pista_descriptor(self):
"""
Get full json desc by id
"""
#WARNING: descriptor not in the repo, run mir analysis first to generate json file (WARNING)
call = '/pistas/76/descriptor' #id 76 (no existente en la DB) retorna 404
try:
response = urllib.request.urlopen(URL_BASE + call).read()
except Exception as e:
self.assertNotEqual(str(e).find("Error 404"), -1)
call = '/pistas/126/descriptor' # id 126 (existente, retorna json)
response = urllib.request.urlopen(URL_BASE + call).read()
self.assertNotEqual(response.find("lowlevel.dissonance.mean"), -1)
self.assertNotEqual(response.find("sfx.inharmonicity.mean"), -1)
def test_pista_descriptor_value(self):
"""
Get desc json value by id
"""
#WARNING: descriptor not in the repo, run mir analysis first to generate json file (WARNING)
call = '/pistas/126/descriptor/lowlevel.hfc.mean' # id 126 (existente, retorna json)
response = urllib.request.urlopen(URL_BASE + call).read()
self.assertEqual(int(response), 2)
def test_pista_search(self):
"""
Search query
"""
call = '/search/bass/10'
response = urllib.request.urlopen(URL_BASE + call).read()
# print(response)
self.assertNotEqual(response.find("10 resultados"), -1)
call = '/search/clarinete/10'
response = urllib.request.urlopen(URL_BASE + call).read()
# print(response)
self.assertNotEqual(response.find("10 resultados"), -1)
def test_last_5_searchs(self):
"""
Search last results
"""
call = '/search/last/5'
response = urllib.request.urlopen(URL_BASE + call).read()
# print(response)
self.assertNotEqual(response.find("últimas 5"), -1)
def test_search_by_tag(self):
"""
Search by tag
"""
call = '/search/tag/bajo'
response = urllib.request.urlopen(URL_BASE + call).read()
# print(response)
self.assertNotEqual(response.find("tag bajo"), -1)
def test_search_mir_desc_greater_than(self):
"""
Search by HFC >40
"""
call = '/search/mir/samples/HFC/greaterthan/40000/5'
response = urllib.request.urlopen(URL_BASE + call).read()
# print(response)
self.assertNotEqual(response.find("984_sample4.wav"), -1)
self.assertEqual( 5, count_response_lines(response) )
def test_search_mir_desc_less_than(self):
"""
Search by HFC <1 (5 results)
"""
call = '/search/mir/samples/HFC/lessthan/1000/5'
response = urllib.request.urlopen(URL_BASE + call).read()
# print(response)
self.assertNotEqual(response.find("126_sample2.wav"), -1)
self.assertEqual( 6, count_response_lines(response) )
if __name__ == '__main__':
unittest.main(verbosity=2)
| gpl-3.0 |
mgshk0712/bon | config.php | 2911 | <?php
define('ROOT_BON_FOLDER', 'projects/bon/');
// HTTP
define('HTTP_SERVER', 'http://localhost/'.ROOT_BON_FOLDER);//http://192.168.0.25
// HTTPS
define('HTTPS_SERVER', 'http://localhost/'.ROOT_BON_FOLDER);
// DIR
define('DIR_APPLICATION', $_SERVER['DOCUMENT_ROOT'].'/'.ROOT_BON_FOLDER.'catalog/');
define('DIR_SYSTEM', $_SERVER['DOCUMENT_ROOT'].'/'.ROOT_BON_FOLDER.'system/');
define('DIR_IMAGE', $_SERVER['DOCUMENT_ROOT'].'/'.ROOT_BON_FOLDER.'image/');
define('DIR_LANGUAGE', $_SERVER['DOCUMENT_ROOT'].'/'.ROOT_BON_FOLDER.'catalog/language/');
define('DIR_TEMPLATE', $_SERVER['DOCUMENT_ROOT'].'/'.ROOT_BON_FOLDER.'catalog/view/theme/');
define('DIR_CONFIG', $_SERVER['DOCUMENT_ROOT'].'/'.ROOT_BON_FOLDER.'system/config/');
define('DIR_CACHE', $_SERVER['DOCUMENT_ROOT'].'/'.ROOT_BON_FOLDER.'system/storage/cache/');
define('DIR_DOWNLOAD', $_SERVER['DOCUMENT_ROOT'].'/'.ROOT_BON_FOLDER.'system/storage/download/');
define('DIR_LOGS', $_SERVER['DOCUMENT_ROOT'].'/'.ROOT_BON_FOLDER.'system/storage/logs/');
define('DIR_MODIFICATION', $_SERVER['DOCUMENT_ROOT'].'/'.ROOT_BON_FOLDER.'system/storage/modification/');
define('DIR_UPLOAD', $_SERVER['DOCUMENT_ROOT'].'/'.ROOT_BON_FOLDER.'system/storage/upload/');
// DB
define('DB_DRIVER', 'mysqli');
define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'opencart_2.30');
define('DB_PORT', '3306');
define('DB_PREFIX', 'oc_');
// HTTP
/*define('HTTP_SERVER', 'http://connectivelinkstechnology.com/demo/bon6-2017/');
// HTTPS
define('HTTPS_SERVER', 'http://connectivelinkstechnology.com/demo/bon6-2017/');
// DIR
define('DIR_APPLICATION', '/home/connectivelinks/public_html/demo/bon6-2017/catalog/');
define('DIR_SYSTEM', '/home/connectivelinks/public_html/demo/bon6-2017/system/');
define('DIR_IMAGE', '/home/connectivelinks/public_html/demo/bon6-2017/image/');
define('DIR_LANGUAGE', '/home/connectivelinks/public_html/demo/bon6-2017/catalog/language/');
define('DIR_TEMPLATE', '/home/connectivelinks/public_html/demo/bon6-2017/catalog/view/theme/');
define('DIR_CONFIG', '/home/connectivelinks/public_html/demo/bon6-2017/system/config/');
define('DIR_CACHE', '/home/connectivelinks/public_html/demo/bon6-2017/system/storage/cache/');
define('DIR_DOWNLOAD', '/home/connectivelinks/public_html/demo/bon6-2017/system/storage/download/');
define('DIR_LOGS', '/home/connectivelinks/public_html/demo/bon6-2017/system/storage/logs/');
define('DIR_MODIFICATION', '/home/connectivelinks/public_html/demo/bon6-2017/system/storage/modification/');
define('DIR_UPLOAD', '/home/connectivelinks/public_html/demo/bon6-2017/system/storage/upload/');
// DB
define('DB_DRIVER', 'mysqli');
define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'connecti_bonclt');
define('DB_PASSWORD', '06Z+)IfWAl.H');
define('DB_DATABASE', 'connecti_clt_bonclt_new1');
define('DB_PORT', '3306');
define('DB_PREFIX', 'oc_');*/
| gpl-3.0 |
glouis/Laima-Discord-Bot | laima/model.py | 12691 | """
This file is part of Laima Discord Bot.
Copyright 2017 glouis
Laima Discord Bot 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.
Laima Discord Bot 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 Laima Discord Bot. If not, see <http://www.gnu.org/licenses/>.
"""
import enum
import json
import os
from peewee import *
import re
import unidecode
laima_db = SqliteDatabase("laima.db")
languages = [("EN", 1), ("FR", 2), ("ES", 3)]
class PackColour(enum.Enum):
BRONZE = 3
SILVER = 2
GOLD = 1
NECRO = 4
OROPO = 5
class Trophy(enum.Enum):
FIRST = 1
SECOND = 2
THIRD = 3
TOP20 = 20
TOP100 = 100
VETERAN = 30
class CardType(enum.Enum):
CREATURE = 0
SPELL = 1
OBJECT = 2
class Extension(enum.Enum):
BASE = 1
OROPO = 281
NECRO = 518
class Family(enum.Enum):
NONE = 0
IOP = 1
CRA = 2
ENIRIPSA = 3
ENUTROF = 4
SRAM = 5
SACRIER = 6
FECA = 7
ECAFLIP = 8
XELOR = 9
OSAMODAS = 10
MULTIMAN = 11
ARACHNEE = 12
TOFU = 13
GOBBALL = 14
BOOWOLF = 15
LARVA = 16
TREECHNID = 17
WABBITS = 18
RAT = 19
DRHELLER = 20
VAMPIRE = 21
CRACKLER = 22
SCARALEAF = 23
PIWI = 24
BLIBLI = 25
STRICH = 26
MONK = 27
CHAFER = 28
CAWWOT = 29
JELLY = 30
WHISPERER = 31
SADIDA = 32
BROTHERHOOD_OF_THE_TOFU = 33
UNKNOW = 34
HUPPERMAGE = 35
BOW_MEOW = 36
RIKTUS = 37
KOKOKO = 38
MOOGRR = 39
SNAPPER = 40
SCHNEK = 41
CROBAK = 42
DOLL = 43
OUGINAK = 44
MASQUERAIDER = 45
ROGUE = 46
BANDIT = 47
BELLAPHONE = 48
MUSHD = 49
BWORK = 50
PIG = 51
CASTUC = 52
TOAD = 53
KWISMAS_CREATURE = 54
DRAGON = 55
ELIATROPE = 56
SCARECROW = 57
PUDDLY = 58
GRAMBO = 59
VIGILANTE = 60
KRALOVE = 61
MOSKITO = 62
PRINCESS = 63
PRESPIC = 64
PLANT = 65
POLTER = 66
FLEA = 67
SHARK = 68
ALBATROCIOUS = 69
SHUSHU = 70
FOGGERNAUT = 71
TAUR = 72
TROOL = 73
MIDGINS = 74
LOOT = 75
CHEST = 76
PALADIR = 77
NECRO = 78
TRAP = 79
SNOOFLE = 80
DRHELLZERKER = 81
GHOUL = 82
BROTHERHOOD_OF_THE_FORGOTTEN = 83
PANDAWA = 84
ELIOTROPE = 85
FAN = 86
class God(enum.Enum):
NEUTRAL = 0
IOP = 1
CRA = 2
ENIRIPSA = 3
ECAFLIP = 4
ENUTROF = 5
SRAM = 6
XELOR = 7
SACRIER = 8
FECA = 9
SADIDA = 10
RUSHU = 17
class Rarity(enum.Enum):
COMMON = 0
UNCOMMON = 1
RARE = 2
KROSMIC = 3
INFINITE = 4
class BaseModel(Model):
class Meta:
database = laima_db
class Draft(BaseModel):
victories_number = IntegerField(unique=True)
level = IntegerField()
pack = IntegerField()
kamas = CharField()
chips = CharField()
earnings = CharField()
class Meta:
order_by = ('victories_number',)
class Server(BaseModel):
id = CharField(unique=True)
lang = IntegerField(default=1)
prefix = CharField(default="&")
class Meta:
order_by = ('id',)
class Channel(BaseModel):
id = CharField(unique=True)
lang = IntegerField(default=None, null=True)
twitter = BooleanField(default=False)
rss = BooleanField(default=False)
server = ForeignKeyField(Server, related_name='channels')
class Meta:
order_by = ('id',)
class Rank(BaseModel):
number = CharField(unique=True)
common = IntegerField(default = 0)
uncommon = IntegerField(default = 0)
rare = IntegerField(default = 0)
krosmic = IntegerField(default = 0)
infinite = IntegerField(default = 0)
kamas = IntegerField()
pedestal = BooleanField(default = True)
trophy = IntegerField(default = None, null=True)
class Meta:
order_by = ('number',)
class CardData(BaseModel):
card_id = CharField(unique=True)
card_type = IntegerField()
ap_cost = IntegerField()
life = IntegerField()
attack = IntegerField()
movement_point = IntegerField()
extension = IntegerField()
families = CharField(default="0")
god = IntegerField(default=0)
rarity = IntegerField()
infinite_level = IntegerField(null=True, default=None)
is_token = BooleanField(default=False)
class Meta:
order_by = ('card_id',)
class CardText(BaseModel):
card_data = ForeignKeyField(CardData, related_name='texts')
name = CharField()
description = TextField()
lang = IntegerField()
class Meta:
order_by = ('name',)
class Tag(BaseModel):
name = CharField(unique=True)
class Meta:
order_by = ('name',)
class CardTextTag(BaseModel):
cardtext = ForeignKeyField(CardText, related_name='tags')
tag = ForeignKeyField(Tag, related_name='cardtexts')
class RssFeeder(BaseModel):
lang = IntegerField(unique=True)
last_entry_id = CharField(default=None)
class TwitterFeeder(BaseModel):
lang = IntegerField(unique=True)
last_tweet_id = CharField(default=None)
def create_tables():
laima_db.connect()
laima_db.create_tables([CardData, CardText, CardTextTag, Channel, Draft, Rank, RssFeeder, Server, Tag, TwitterFeeder])
laima_db.close()
def init_draft():
for i in range(13):
if i < 7:
pack = PackColour.BRONZE.value
if i == 0:
level = 1
kamas = "15-25"
chips = "0"
earnings = "15-25"
elif i < 4:
level = 2
kamas = "25-35"
if i == 1:
chips = "50"
earnings = "30-40"
if i == 2:
chips = "100-150"
earnings = "35-50"
if i == 3:
chips = "150-250"
earnings = "40-60"
else:
level = 3
kamas = "35-45"
if i == 4:
chips = "250-350"
earnings = "60-80"
if i == 5:
chips = "350-600"
earnings = "70-105"
if i == 6:
chips = "450-850"
earnings = "80-130"
else:
level = 4
if i < 10:
pack = PackColour.SILVER.value
kamas = "50-60"
if i == 7:
chips = "700-1100"
earnings = "120-170"
if i == 8:
chips = "950-1700"
earnings = "145-230"
if i == 9:
chips = "1200-2300"
earnings = "170-290"
else:
pack = PackColour.GOLD.value
kamas = "200"
if i == 10:
chips = "1800-2900"
earnings = "380-490"
if i == 11:
chips = "2400-2950"
earnings = "440-495"
if i == 12:
chips = "3000"
earnings = "500"
with laima_db.transaction():
Draft.create(victories_number=i,
level=level,
pack=pack,
kamas=kamas,
chips=chips,
earnings=earnings)
def init_rank():
for i in range(6, 31):
number = str(i)
if i < 18:
kamas = (i - 3) * 5
if i < 11:
with laima_db.transaction():
Rank.create(number=number,
common=2,
uncommon=1,
kamas=kamas)
elif i < 16:
with laima_db.transaction():
Rank.create(number=number,
common=2,
rare=1,
kamas=kamas)
else:
with laima_db.transaction():
Rank.create(number=number,
uncommon=2,
rare=1,
kamas=kamas)
elif i < 26:
kamas = (i - 10) * 10
if i < 21:
with laima_db.transaction():
Rank.create(number=number,
uncommon=2,
rare=1,
kamas=kamas)
else:
with laima_db.transaction():
Rank.create(number=number,
uncommon=2,
krosmic=1,
kamas=kamas)
else:
if i == 30:
with laima_db.transaction():
Rank.create(number=number,
uncommon=2,
infinite=1,
kamas=300,
trophy=Trophy.VETERAN.value)
else:
kamas = (i - 19) * 25
with laima_db.transaction():
Rank.create(number=number,
uncommon=2,
infinite=1,
kamas=kamas)
with laima_db.transaction():
Rank.create(number="Top 100",
uncommon=2,
infinite=1,
kamas=300,
trophy=Trophy.TOP100.value)
Rank.create(number="Top 20",
uncommon=2,
infinite=1,
kamas=300,
trophy=Trophy.TOP20.value)
Rank.create(number="3rd",
uncommon=2,
infinite=1,
kamas=300,
trophy=Trophy.THIRD.value)
Rank.create(number="2nd",
uncommon=2,
infinite=1,
kamas=300,
trophy=Trophy.SECOND.value)
Rank.create(number="1st",
uncommon=2,
infinite=1,
kamas=300,
trophy=Trophy.FIRST.value)
def init_card_and_tag(directory):
for filename in os.listdir(directory):
print(filename)
filepath = directory + "/" + filename
json_to_card_and_tag(filepath)
def json_to_card_and_tag(filepath):
inf_lvl_regex = re.compile(r"\d$")
bold_regex = re.compile(r"<.?b>")
with open(filepath, 'r') as file_data:
data = json.load(file_data)
name = {}
tags = {}
desc = {}
families = ','.join([str(fam) for fam in data["Families"]])
infinite_level = None
if data["Rarity"] == 4:
inf_lvl = inf_lvl_regex.search(data["Name"]).group(0)
infinite_level = int(inf_lvl)
for language, __ in languages:
name[language] = data["Texts"]["Name" + language]
tags[language] = unidecode.unidecode(name[language]).lower().split()
desc[language] = ' '.join(data["Texts"]["Desc" + language].split())
desc[language] = bold_regex.subn("**", desc[language])[0]
if data["Rarity"] == 4:
tags[language].append(inf_lvl)
with laima_db.transaction():
card_data = CardData.create(card_id=data["Name"],
card_type=data["CardType"],
ap_cost=data["CostAP"],
life=data["Life"],
attack=data["Attack"],
movement_point=data["MovementPoint"],
extension=data["Extension"],
families=families,
god=data["GodType"],
rarity=data["Rarity"],
infinite_level=infinite_level,
is_token=data["IsToken"])
for language, lang_id in languages:
card_text = CardText.create(card_data=card_data,
name=name[language],
description=desc[language],
lang = lang_id)
for tag in tags[language]:
tag_row = Tag.get_or_create(name=tag)[0]
card_tag = CardTextTag.create(cardtext=card_text, tag=tag_row)
def init_rss_feeder():
with laima_db.transaction():
for __, lang_id in languages:
RssFeeder.create(lang=lang_id)
def init_twitter_feeder():
with laima_db.transaction():
for __, lang_id in languages:
TwitterFeeder.create(lang=lang_id)
| gpl-3.0 |
potty-dzmeia/db4o | src/db4oj.tests/src/com/db4o/db4ounit/common/foundation/Path4TestCase.java | 1076 | /* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o 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.db4o.db4ounit.common.foundation;
import com.db4o.foundation.io.*;
import db4ounit.*;
/**
* @exclude
*/
public class Path4TestCase implements TestCase{
/**
* @sharpen.if !SILVERLIGHT
*/
public void testGetTempFileName(){
String tempFileName = Path4.getTempFileName();
Assert.isTrue(File4.exists(tempFileName));
File4.delete(tempFileName);
}
}
| gpl-3.0 |
408657544/springbank | springbank-dao/src/main/java/com/springbank/dao/generate/mapper/ScheduledjobMapper.java | 3196 | package com.springbank.dao.generate.mapper;
import com.springbank.dao.generate.model.Scheduledjob;
import com.springbank.dao.generate.model.ScheduledjobExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface ScheduledjobMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table scheduledjob
*
* @mbggenerated Wed Oct 17 17:54:47 CST 2018
*/
int countByExample(ScheduledjobExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table scheduledjob
*
* @mbggenerated Wed Oct 17 17:54:47 CST 2018
*/
int deleteByExample(ScheduledjobExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table scheduledjob
*
* @mbggenerated Wed Oct 17 17:54:47 CST 2018
*/
int deleteByPrimaryKey(String jobid);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table scheduledjob
*
* @mbggenerated Wed Oct 17 17:54:47 CST 2018
*/
int insert(Scheduledjob record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table scheduledjob
*
* @mbggenerated Wed Oct 17 17:54:47 CST 2018
*/
int insertSelective(Scheduledjob record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table scheduledjob
*
* @mbggenerated Wed Oct 17 17:54:47 CST 2018
*/
List<Scheduledjob> selectByExample(ScheduledjobExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table scheduledjob
*
* @mbggenerated Wed Oct 17 17:54:47 CST 2018
*/
Scheduledjob selectByPrimaryKey(String jobid);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table scheduledjob
*
* @mbggenerated Wed Oct 17 17:54:47 CST 2018
*/
int updateByExampleSelective(@Param("record") Scheduledjob record, @Param("example") ScheduledjobExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table scheduledjob
*
* @mbggenerated Wed Oct 17 17:54:47 CST 2018
*/
int updateByExample(@Param("record") Scheduledjob record, @Param("example") ScheduledjobExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table scheduledjob
*
* @mbggenerated Wed Oct 17 17:54:47 CST 2018
*/
int updateByPrimaryKeySelective(Scheduledjob record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table scheduledjob
*
* @mbggenerated Wed Oct 17 17:54:47 CST 2018
*/
int updateByPrimaryKey(Scheduledjob record);
} | gpl-3.0 |
andrewseward/Cronosync | node_modules/passport-oauth2-refresh/lib/refresh.js | 2965 | 'use strict';
var AuthTokenRefresh = {};
AuthTokenRefresh._strategies = {};
/**
* Register a passport strategy so it can refresh an access token,
* with optional `name`, overridding the strategy's default name.
*
* Examples:
*
* refresh.use(strategy);
* refresh.use('facebook', strategy);
*
* @param {String|Strategy} name
* @param {Strategy} passport strategy
*/
AuthTokenRefresh.use = function(name, strategy) {
if(arguments.length === 1) {
// Infer name from strategy
strategy = name;
name = strategy && strategy.name;
}
/* jshint eqnull: true */
if(strategy == null) {
throw new Error('Cannot register: strategy is null');
}
/* jshint eqnull: false */
if(!name) {
throw new Error('Cannot register: name must be specified, or strategy must include name');
}
if(!strategy._oauth2) {
throw new Error('Cannot register: not an OAuth2 strategy');
}
// Use the strategy's OAuth2 object, since it might have been overwritten.
// https://github.com/fiznool/passport-oauth2-refresh/issues/3
var OAuth2 = strategy._oauth2.constructor;
// Generate our own oauth2 object for use later.
// Use the strategy's _refreshURL, if defined,
// otherwise use the regular accessTokenUrl.
AuthTokenRefresh._strategies[name] = {
strategy: strategy,
refreshOAuth2: new OAuth2(
strategy._oauth2._clientId,
strategy._oauth2._clientSecret,
strategy._oauth2._baseSite,
strategy._oauth2._authorizeUrl,
strategy._refreshURL || strategy._oauth2._accessTokenUrl,
strategy._oauth2._customHeaders)
};
};
/**
* Check if a strategy is registered for refreshing.
* @param {String} name Strategy name
* @return {Boolean}
*/
AuthTokenRefresh.has = function(name) {
return !!AuthTokenRefresh._strategies[name];
};
/**
* Request a new access token, using the passed refreshToken,
* for the given strategy.
* @param {String} name Strategy name. Must have already
* been registered.
* @param {String} refreshToken Refresh token to be sent to request
* a new access token.
* @param {Object} params (optional) an object containing additional
* params to use when requesting the token.
* @param {Function} done Callback when all is done.
*/
AuthTokenRefresh.requestNewAccessToken = function(name, refreshToken, params, done) {
if(arguments.length === 3) {
done = params;
params = {};
}
// Send a request to refresh an access token, and call the passed
// callback with the result.
var strategy = AuthTokenRefresh._strategies[name];
if(!strategy) {
return done(new Error('Strategy was not registered to refresh a token'));
}
params = params || {};
params.grant_type = 'refresh_token';
strategy.refreshOAuth2.getOAuthAccessToken(refreshToken, params, done);
};
module.exports = AuthTokenRefresh;
| gpl-3.0 |
DarioGT/OMS-PluginXML | org.modelsphere.jack/src/org/modelsphere/jack/srtool/graphic/ApplicationDiagram.java | 12805 | /*************************************************************************
Copyright (C) 2009 Grandite
This file is part of Open ModelSphere.
Open ModelSphere 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
or see http://www.gnu.org/licenses/.
You can redistribute and/or modify this particular file even under the
terms of the GNU Lesser General Public License (LGPL) as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
You should have received a copy of the GNU Lesser General Public License
(LGPL) along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
or see http://www.gnu.org/licenses/.
You can reach Grandite at:
20-1220 Lebourgneuf Blvd.
Quebec, QC
Canada G2K 2G4
or
open-modelsphere@grandite.com
**********************************************************************/
package org.modelsphere.jack.srtool.graphic;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.print.PageFormat;
import java.util.HashSet;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import org.modelsphere.jack.actions.ActionInformation;
import org.modelsphere.jack.awt.JackPopupMenu;
import org.modelsphere.jack.awt.choosers.PageTitlePanel;
import org.modelsphere.jack.baseDb.db.Db;
import org.modelsphere.jack.baseDb.db.DbEnumeration;
import org.modelsphere.jack.baseDb.db.DbException;
import org.modelsphere.jack.baseDb.db.DbGraphicalObjectI;
import org.modelsphere.jack.baseDb.db.DbObject;
import org.modelsphere.jack.baseDb.db.DbProject;
import org.modelsphere.jack.baseDb.db.DbSemanticalObject;
import org.modelsphere.jack.baseDb.db.event.DbRefreshListener;
import org.modelsphere.jack.baseDb.db.event.DbUpdateEvent;
import org.modelsphere.jack.baseDb.db.srtypes.PageNoPosition;
import org.modelsphere.jack.graphic.Diagram;
import org.modelsphere.jack.graphic.DiagramView;
import org.modelsphere.jack.graphic.GraphicComponent;
import org.modelsphere.jack.graphic.GraphicNode;
import org.modelsphere.jack.graphic.Grid;
import org.modelsphere.jack.graphic.ZoneBox;
import org.modelsphere.jack.graphic.tool.ToolButtonGroup;
import org.modelsphere.jack.graphic.zone.CellID;
import org.modelsphere.jack.preference.PropertiesManager;
import org.modelsphere.jack.preference.PropertiesSet;
import org.modelsphere.jack.srtool.ApplicationContext;
import org.modelsphere.jack.srtool.international.LocaleMgr;
public class ApplicationDiagram extends Diagram implements DbRefreshListener {
public static final String PAGE_TITLE = "diagram.pageTitle"; // NOT LOCALIZABLE, property
public static final String PAGE_TITLE_DEFAULT = "{1},{2}";
public static boolean lockGridAlignment = true;
/**
* @return Returns the diagGO.
*/
protected DbSemanticalObject semObj;
protected DbObject diagGO;
protected DbProject project;
protected ApplDiagramView mainView;
private GraphicComponentFactory gcFactory;
public DbSemanticalObject getSemObj() {
return semObj;
}
public ApplicationDiagram(DbSemanticalObject semObj, DbObject diagGO,
GraphicComponentFactory gcFactory, ToolButtonGroup toolGroup) throws DbException {
this.semObj = semObj;
this.diagGO = diagGO;
this.gcFactory = gcFactory;
project = diagGO.getProject();
addObjectTriggers();
populateContent();
mainView = new ApplDiagramView(this);
mainView.setToolGroup(toolGroup);
}
private void addObjectTriggers() {
diagGO.addDbRefreshListener(this);
}
private void removeObjectTriggers() {
diagGO.removeDbRefreshListener(this);
}
public final void delete() {
removeObjectTriggers();
super.delete();
}
public final DbSemanticalObject getSemanticalObject() {
return semObj;
}
public final DbObject getDiagramGO() {
return diagGO;
}
public final DbProject getProject() {
return project;
}
public final DiagramView getMainView() {
return mainView;
}
public final DiagramInternalFrame getDiagramInternalFrame() {
return (DiagramInternalFrame) SwingUtilities.getAncestorOfClass(DiagramInternalFrame.class,
mainView);
}
public final Object[] getSelectedObjects() {
GraphicComponent[] selComps = getSelectedComponents();
if (selComps.length == 0)
return new Object[0];
HashSet selObjs = new HashSet();
for (int i = 0; i < selComps.length; i++) {
GraphicComponent gc = selComps[i];
if (gc.selectAtCellLevel()) {
CellID[] cellIds = ((ZoneBox) gc).getSelectedCells();
if (cellIds.length == 0)
selObjs.add(gc);
else {
for (int j = 0; j < cellIds.length; j++) {
Object obj = ((ZoneBox) gc).getCell(cellIds[j]).getObject();
selObjs.add(obj == ((ActionInformation) gc).getSemanticalObject() ? gc
: obj);
}
}
} else
selObjs.add(gc);
}
return selObjs.toArray();
}
public final void populateContent() throws DbException {
try {
removeAll();
setDrawingArea();
setPageNoParams();
if (diagGO.getDb().getTransMode() != Db.TRANS_REFRESH)
beginComputePos();
DbEnumeration dbEnum = diagGO.getComponents().elements();
while (dbEnum.hasMoreElements()) {
DbObject obj = dbEnum.nextElement();
createComponent(obj);
}
dbEnum.close();
if (diagGO.getDb().getTransMode() != Db.TRANS_REFRESH) {
Graphics g = ApplicationContext.getDefaultMainFrame().getGraphics();
endComputePos(g);
g.dispose();
}
} catch (DbException ex) {
throw ex;
}
}
public final void fireSelectionChanged() {
super.fireSelectionChanged();
ApplicationContext.getFocusManager().selectionChanged(this);
}
public final JPopupMenu getPopupMenu(Point ptClicked, GraphicComponent gcClicked) {
JackPopupMenu popup = ApplicationContext.getApplPopupMenu().getPopupMenu(gcClicked == null);
if (popup != null) {
popup.setDiagramLocation(ptClicked, gcClicked);
}
return popup;
}
public final void editCell(ZoneBox box, CellID cellID) {
// If the cell to be edited is outside the box,
// increase the height of the box to make the cell visible.
if (cellID == null)
return;
Rectangle rect = box.getCellRect(cellID);
int heightIncr = rect.y + rect.height;
rect = box.getContentRect();
heightIncr -= rect.y + rect.height;
if (heightIncr > 0) {
rect = new Rectangle(box.getRectangle());
rect.y -= heightIncr / 2;
rect.height += heightIncr;
DbObject go = ((ActionInformation) box).getGraphicalObject();
try {
go.getDb().beginTrans(Db.WRITE_TRANS, LocaleMgr.action.getString("fit"));
go.set(DbGraphic.fGraphicalObjectRectangle, rect);
go.getDb().commitTrans();
} catch (Exception e) {
org.modelsphere.jack.util.ExceptionHandler.processUncatchedException(mainView, e);
return;
}
}
setEditor(mainView, box, cellID);
}
// ////////////////////////////////////////////
// DbRefreshListener SUPPORT
//
// Overridden
public void refreshAfterDbUpdate(DbUpdateEvent event) throws DbException {
if (event.metaField == DbObject.fComponents) {
if (event.op == Db.ADD_TO_RELN) {
createComponent(event.neighbor);
} else if (event.op == Db.REMOVE_FROM_RELN) {
GraphicComponent gc = (GraphicComponent) ((DbGraphicalObjectI) event.neighbor)
.getGraphicPeer();
if (gc != null)
gc.delete(false);
}
} else if (event.metaField == DbGraphic.fDiagramNbPages
|| event.metaField == DbGraphic.fDiagramPageFormat
|| event.metaField == DbGraphic.fDiagramPrintScale) {
setDrawingArea();
} else if (event.metaField == DbGraphic.fDiagramStyle) {
populateContent();
} else if (event.metaField == DbGraphic.fDiagramPageNoFont
|| event.metaField == DbGraphic.fDiagramPageNoPsition) {
setPageNoParams();
}
}
//
// End of DbRefreshListener SUPPORT
// ///////////////////////////////////////////
// called from Diagram
protected String getStringPageNo(int row, int col, Dimension nbPages) {
// get pattern
PropertiesSet options = PropertiesManager.APPLICATION_PROPERTIES_SET;
String pattern = options.getPropertyString(ApplicationDiagram.class,
ApplicationDiagram.PAGE_TITLE, ApplicationDiagram.PAGE_TITLE_DEFAULT);
// get diagram and project names
String diagramName, projectName;
try {
boolean bManageTrans = false;
Db db = diagGO.getDb();
if (db.getTransMode() == Db.TRANS_NONE) {
bManageTrans = true;
db.beginReadTrans();
}
diagramName = diagGO.getName();
DbProject proj = diagGO.getProject();
projectName = proj.getName();
if (bManageTrans)
db.commitTrans();
} catch (DbException ex) {
diagramName = "";
projectName = "";
} // end try
String str = PageTitlePanel.getPageTitle(pattern, row, col, nbPages, diagramName,
projectName);
return str;
}
//
// private methods
//
private void setDrawingArea() throws DbException {
PageFormat pageFormat = (PageFormat) diagGO.get(DbGraphic.fDiagramPageFormat);
int printScale = ((Integer) diagGO.get(DbGraphic.fDiagramPrintScale)).intValue();
Dimension nbPages = (Dimension) diagGO.get(DbGraphic.fDiagramNbPages);
setDrawingArea(pageFormat, printScale, nbPages);
}
private void setPageNoParams() throws DbException {
PageNoPosition pnp = (PageNoPosition) diagGO.get(DbGraphic.fDiagramPageNoPsition);
Font pageNoFont = (Font) diagGO.get(DbGraphic.fDiagramPageNoFont);
if (pnp != null && pageNoFont != null)
setPageNoParams(pnp.getValue(), pageNoFont);
}
private GraphicComponent createComponent(DbObject go) throws DbException {
GraphicComponent gc = (GraphicComponent) ((DbGraphicalObjectI) go).getGraphicPeer();
if (gc != null)
return gc; // already created
if (go.hasField(DbGraphic.fLineGoPolyline)) {
DbObject frontGo = (DbObject) go.get(DbGraphic.fLineGoFrontEndGo);
DbObject backGo = (DbObject) go.get(DbGraphic.fLineGoBackEndGo);
GraphicNode node1 = (frontGo == null ? null : (GraphicNode) createComponent(frontGo));
GraphicNode node2 = (backGo == null ? null : (GraphicNode) createComponent(backGo));
if (gcFactory != null) {
gc = gcFactory.createLine(this, go, node1, node2);
} // end if
} else {
if (gcFactory != null) {
gc = gcFactory.createGraphic(this, go);
} // end if
} // end if
return gc;
}
}
| gpl-3.0 |
vymio/vym-chrome-extension | app/scripts.babel/vym_api.js | 1096 | import {get} from 'request';
const endpoint = '__VYM_HOST__/api/v1';
export default {
/**
* options {Object}
* options.ownerName {String}
* options.repoName {String}
* options.prNumber {String}
* options.vymToken {String} - used to authorize user
*/
getSlideDeck(options, done) {
let url =
'__VYM_HOST__/api/v1' +
'/slide_decks' +
`/${options.ownerName}` +
`/${options.repoName}` +
`/${options.prNumber}`;
get({url, qs: {vymToken: options.vymToken}, json: true}, done);
},
/**
* options {Object}
* options.ownerName {String}
* options.repoName {String}
* options.vymToken {String} - used to authorize user
*/
checkRepoActivated(options, done) {
let url =
'__VYM_HOST__/api/v1' +
'/repo' +
`/${options.ownerName}` +
`/${options.repoName}`;
get({url, qs: {vymToken: options.vymToken}, json: true}, done);
},
syncRepoAccess(options, done) {
let url =
'__VYM_HOST__/api/v1' +
'/user/sync_access';
get({url, qs: {vymToken: options.vymToken}}, done);
}
};
| gpl-3.0 |
ricargoes/Roguey | src/ResourceManager.cpp | 11870 | /*
* ResourceManager.cpp
*
* Created on: Feb 3, 2015
* Author: elgatil
*/
#include "ResourceManager.h"
ResourceManager::ResourceManager() {
//Start up SDL and create window
if ( !init() ){
printf( "Failed to initialize!\n" );
success = false;
return;
}
//Load media
if ( !loadMedia() ){
printf( "Failed to load media!\n" );
success = false;
return;
}
success = true;
}
ResourceManager::~ResourceManager() {
}
// Singleton instance manager.
ResourceManager* ResourceManager::instance(int instanceMode) {
static ResourceManager *instance;
if(instance) {
switch(instanceMode) {
case RESOURCEMANAGER_MODE_RESET:
delete instance;
instance = new ResourceManager();
break;
case RESOURCEMANAGER_MODE_CLOSE:
delete instance;
break;
case RESOURCEMANAGER_MODE_INIT:
break;
default:
return 0;
break;
}
} else {
switch(instanceMode) {
case RESOURCEMANAGER_MODE_INIT:
instance = new ResourceManager();
break;
case RESOURCEMANAGER_MODE_CLOSE:
case RESOURCEMANAGER_MODE_RESET:
default:
return 0;
break;
}
}
return instance;
}
void ResourceManager::close(){
//Free loaded images
free( heroSheet->texture );
delete heroSheet;
free( dungeonSheet->texture );
delete dungeonSheet;
free( stuffSheet->texture );
delete stuffSheet;
//Free global font
TTF_CloseFont( gameFont );
gameFont = NULL;
//Destroy window
SDL_DestroyRenderer( gameRenderer );
SDL_DestroyWindow( gameWindow );
gameWindow = NULL;
gameRenderer = NULL;
//Quit SDL subsystems
TTF_Quit();
IMG_Quit();
SDL_Quit();
}
void ResourceManager::free( SDL_Texture* texture ) {
//Free texture if it exists
if( texture != NULL ) {
SDL_DestroyTexture( texture );
texture = NULL;
}
}
Image* ResourceManager::loadFromFile( std::string path, Uint8 r, Uint8 g, Uint8 b ){
//The final image
Image* image = new Image();
//Load image at specified path
SDL_Surface* loadedSurface = IMG_Load( path.c_str() );
if( loadedSurface == NULL ) {
printf( "Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError() );
return NULL;
}
//Color key image
SDL_SetColorKey( loadedSurface, SDL_TRUE, SDL_MapRGB( loadedSurface->format, r, g, b ) );
//Create texture from surface pixels
image->texture = SDL_CreateTextureFromSurface( gameRenderer, loadedSurface );
if( image->texture == NULL ) {
printf( "Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError() );
return NULL;
}
//Get image dimensions
image->textSize.x = loadedSurface->w;
image->textSize.y = loadedSurface->h;
//Get rid of old loaded surface
SDL_FreeSurface( loadedSurface );
return image;
}
void ResourceManager::render(Image* image, int x, int y, SDL_Rect* clip, double angle, SDL_Point* center, SDL_RendererFlip flip ) {
//Set rendering space and render to screen
SDL_Rect renderQuad = { x, y, image->textSize.x, image->textSize.y };
//Set clip rendering dimensions
if( clip != NULL ) {
renderQuad.w = clip->w;
renderQuad.h = clip->h;
}
//Render to screen
SDL_RenderCopyEx( gameRenderer, image->texture, clip, &renderQuad, angle, center, flip );
}
bool ResourceManager::init(){
//Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) {
printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
return false;
}
//Create window
gameWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
if( gameWindow == NULL ) {
printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
return false;
}
//Create renderer for window
gameRenderer = SDL_CreateRenderer( gameWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC );
if( gameRenderer == NULL ) {
printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
return false;
}
SDL_SetRenderDrawColor( gameRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); //Initialize renderer color
//Initialize PNG loading
int imgFlags = IMG_INIT_PNG;
if( !( IMG_Init( imgFlags ) & imgFlags ) ) {
printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
return false;
}
//Initialize SDL_ttf
if( TTF_Init() == -1 ) {
printf( "SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError() );
return false;
}
return true;
}
bool ResourceManager::loadMedia(){
// TEXTURES
//Load sprite sheet texture
heroSheet = loadFromFile( "media/heroSprite.png" );
dungeonSheet = loadFromFile( "media/dungeonSpritesMod.gif" );
stuffSheet = loadFromFile( "media/stuffMod.png", 0x46, 0x6D, 0x6C );
if( dungeonSheet->texture==NULL || heroSheet->texture==NULL || stuffSheet->texture==NULL ) {
printf( "Failed to load sprite sheet textures!\n" );
return false;
}
int wDunSp = dungeonSheet->textSize.x/9; // 32px
int hDunSp = dungeonSheet->textSize.y/10; // 32px
int wHeroSp = heroSheet->textSize.x/12; // 32px
int hHeroSp = heroSheet->textSize.y/8; // 32px
int wStuffSp = stuffSheet->textSize.x/40; // 26px
int hStuffSp = stuffSheet->textSize.y/30; // 26px
SDL_Rect dummyRect; // { x, y, width, height }
for (int i=0; i<0+4; i++){ // Scarf Hero Sprites
for (int j=0; j<0+3; j++){
dummyRect = { j*wHeroSp, i*hHeroSp, wHeroSp, hHeroSp }; // { x, y, width, height }
heroSpriteRects["ScarfHero"].push_back(dummyRect);
}
}
for (int i=0; i<0+4; i++){ // Blue Hero Sprites
for (int j=3; j<3+3; j++){
dummyRect = { j*wHeroSp, i*hHeroSp, wHeroSp, hHeroSp }; // { x, y, width, height }
heroSpriteRects["BlueHero"].push_back(dummyRect);
}
}
for (int i=0; i<0+4; i++){ // Red Hero Sprites
for (int j=6; j<6+3; j++){
dummyRect = { j*wHeroSp, i*hHeroSp, wHeroSp, hHeroSp }; // { x, y, width, height }
heroSpriteRects["RedHero"].push_back(dummyRect);
}
}
for (int i=0; i<0+4; i++){ // Brown Hero Sprites
for (int j=9; j<9+3; j++){
dummyRect = { j*wHeroSp, i*hHeroSp, wHeroSp, hHeroSp }; // { x, y, width, height }
heroSpriteRects["BrownHero"].push_back(dummyRect);
}
}
for (int i=4; i<4+4; i++){ // Ash Hero Sprites
for (int j=0; j<0+3; j++){
dummyRect = { j*wHeroSp, i*hHeroSp, wHeroSp, hHeroSp }; // { x, y, width, height }
heroSpriteRects["AshHero"].push_back(dummyRect);
}
}
for (int i=4; i<4+4; i++){ // Ash Heroine Sprites
for (int j=3; j<3+3; j++){
dummyRect = { j*wHeroSp, i*hHeroSp, wHeroSp, hHeroSp }; // { x, y, width, height }
heroSpriteRects["AshHeroine"].push_back(dummyRect);
}
}
for (int i=4; i<4+4; i++){ // Scarf White Hero Sprites
for (int j=6; j<6+3; j++){
dummyRect = { j*wHeroSp, i*hHeroSp, wHeroSp, hHeroSp }; // { x, y, width, height }
heroSpriteRects["ScarfWhiteHero"].push_back(dummyRect);
}
}
for (int i=4; i<4+4; i++){ // Angel Sprites
for (int j=9; j<9+3; j++){
dummyRect = { j*wHeroSp, i*hHeroSp, wHeroSp, hHeroSp }; // { x, y, width, height }
heroSpriteRects["Angel"].push_back(dummyRect);
}
}
dummyRect = { 0*wDunSp, 5*hDunSp, wDunSp, hDunSp }; // { x, y, width, height }
dungeonSpriteRects["Wall"].push_back(dummyRect);
dummyRect = { 2*wDunSp, 5*hDunSp, wDunSp, hDunSp }; // { x, y, width, height }
dungeonSpriteRects["WallVar"].push_back(dummyRect);
dummyRect = { 4*wDunSp, 5*hDunSp, wDunSp, hDunSp }; // { x, y, width, height }
dungeonSpriteRects["WallVar"].push_back(dummyRect);
dummyRect = { 0*wDunSp, 8*hDunSp, wDunSp, hDunSp }; // { x, y, width, height }
dungeonSpriteRects["Floor"].push_back(dummyRect);
dummyRect = { 3*wDunSp, 8*hDunSp, wDunSp, hDunSp }; // { x, y, width, height }
dungeonSpriteRects["FloorVar"].push_back(dummyRect);
dummyRect = { 4*wStuffSp, 16*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["Life"].push_back(dummyRect);
dummyRect = { 5*wStuffSp, 15*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["Mana"].push_back(dummyRect);
dummyRect = { 10*wStuffSp, 13*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["Defense"].push_back(dummyRect);
dummyRect = { 16*wStuffSp, 13*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["Boots"].push_back(dummyRect);
dummyRect = { 31*wStuffSp, 10*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["Sword"].push_back(dummyRect);
dummyRect = { 19*wStuffSp, 11*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["Bow"].push_back(dummyRect);
dummyRect = { 35*wStuffSp, 9*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["Arrow"].push_back(dummyRect);
dummyRect = { 12*wStuffSp, 22*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["Explosion"].push_back(dummyRect);
dummyRect = { 17*wStuffSp, 22*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["Explosion"].push_back(dummyRect);
dummyRect = { 20*wStuffSp, 22*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["Explosion"].push_back(dummyRect);
dummyRect = { 22*wStuffSp, 22*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["Explosion"].push_back(dummyRect);
dummyRect = { 39*wStuffSp, 2*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["Teleport"].push_back(dummyRect);
dummyRect = { 2*wStuffSp, 20*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["LockerRed"].push_back(dummyRect);
dummyRect = { 10*wStuffSp, 20*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["LockerBlue"].push_back(dummyRect);
dummyRect = { 0*wStuffSp, 29*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["lightRed"].push_back(dummyRect);
dummyRect = { 1*wStuffSp, 29*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["lightBlue"].push_back(dummyRect);
dummyRect = { 2*wStuffSp, 29*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["lightGreen"].push_back(dummyRect);
dummyRect = { 3*wStuffSp, 29*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["lightYellow"].push_back(dummyRect);
dummyRect = { 0*wStuffSp, 28*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["darkRed"].push_back(dummyRect);
dummyRect = { 1*wStuffSp, 28*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["darkBlue"].push_back(dummyRect);
dummyRect = { 2*wStuffSp, 28*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["darkGreen"].push_back(dummyRect);
dummyRect = { 3*wStuffSp, 28*hStuffSp, wStuffSp, hStuffSp }; // { x, y, width, height }
stuffSpriteRects["darkYellow"].push_back(dummyRect);
tileSize.x = dungeonSpriteRects["Floor"][0].w;
tileSize.y = dungeonSpriteRects["Floor"][0].h;
// FONTS
//Open the font
gameFont = TTF_OpenFont( "media/FreeMono.ttf", 18 );
if( gameFont == NULL ){
printf( "Failed to load lazy font! SDL_ttf Error: %s\n", TTF_GetError() );
return false;
}
return true;
}
INIConfig ResourceManager::read_INIConfig( std::string filename ){
std::ifstream file(filename.c_str());
std::string s;
INIConfig Map;
std::string tempGroupKey;
Group tempControl;
std::string tempKey;
std::string tempValue;
std::string::size_type i=0;
std::string::size_type j=0;
while (getline(file, s)){
if ((i = s.find('[')) != std::string::npos && (j = s.find(']')) != std::string::npos && (j-i)>1 ){
if ( !tempGroupKey.empty() )
Map[tempGroupKey] = tempControl;
tempGroupKey = s.substr(i+1,j-1-i);
} else if ( (i = s.find('=')) != std::string::npos ){
tempKey = s.substr(0,i);
tempValue = s.substr(i+1);
tempControl[tempKey] = std::stoi(tempValue);
}
Map[tempGroupKey] = tempControl;
}
file.close();
return Map;
}
| gpl-3.0 |
byrokrat/accounting | src/Template/Translator.php | 2003 | <?php
/**
* This file is part of byrokrat/accounting.
*
* byrokrat/accounting 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.
*
* byrokrat/accounting 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 byrokrat/accounting. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2016-21 Hannes Forsgård
*/
declare(strict_types=1);
namespace byrokrat\accounting\Template;
use byrokrat\accounting\Exception\InvalidArgumentException;
/**
* Translate raw data by expanding placeholders
*/
final class Translator implements TranslatorInterface
{
/** @var array<string, string> */
private array $translations;
/**
* @param array<string, string> $translations
*/
public function __construct(array $translations)
{
foreach ($translations as $placeholder => $replacement) {
if (!is_string($placeholder)) {
throw new InvalidArgumentException('Placeholder must be string');
}
if (!is_string($replacement)) {
throw new InvalidArgumentException('Replacement must be string');
}
}
$this->translations = (array)array_combine(
array_map(
fn ($placeholder) => '{' . $placeholder . '}',
array_keys($translations)
),
$translations
);
}
public function translate(string $raw): string
{
return str_replace(
array_keys($this->translations),
$this->translations,
$raw
);
}
}
| gpl-3.0 |
valmynd/MediaFetcher | src/plugins/youtube_dl/youtube_dl/extractor/servingsys.py | 1873 | from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
int_or_none,
)
class ServingSysIE(InfoExtractor):
_VALID_URL = r'https?://(?:[^.]+\.)?serving-sys\.com/BurstingPipe/adServer\.bs\?.*?&pli=(?P<id>[0-9]+)'
_TEST = {
'url': 'http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=is&c=23&pl=VAST&pli=5349193&PluID=0&pos=7135&ord=[timestamp]&cim=1?',
'info_dict': {
'id': '5349193',
'title': 'AdAPPter_Hyundai_demo',
},
'playlist': [{
'md5': 'baed851342df6846eb8677a60a011a0f',
'info_dict': {
'id': '29955898',
'ext': 'flv',
'title': 'AdAPPter_Hyundai_demo (1)',
'duration': 74,
'tbr': 1378,
'width': 640,
'height': 400,
},
}, {
'md5': '979b4da2655c4bc2d81aeb915a8c5014',
'info_dict': {
'id': '29907998',
'ext': 'flv',
'title': 'AdAPPter_Hyundai_demo (2)',
'duration': 34,
'width': 854,
'height': 480,
'tbr': 516,
},
}],
'params': {
'playlistend': 2,
},
'_skip': 'Blocked in the US [sic]',
}
def _real_extract(self, url):
pl_id = self._match_id(url)
vast_doc = self._download_xml(url, pl_id)
title = vast_doc.find('.//AdTitle').text
media = vast_doc.find('.//MediaFile').text
info_url = self._search_regex(r'&adData=([^&]+)&', media, 'info URL')
doc = self._download_xml(info_url, pl_id, 'Downloading video info')
entries = [{
'_type': 'video',
'id': a.attrib['id'],
'title': '%s (%s)' % (title, a.attrib['assetID']),
'url': a.attrib['URL'],
'duration': int_or_none(a.attrib.get('length')),
'tbr': int_or_none(a.attrib.get('bitrate')),
'height': int_or_none(a.attrib.get('height')),
'width': int_or_none(a.attrib.get('width')),
} for a in doc.findall('.//AdditionalAssets/asset')]
return {
'_type': 'playlist',
'id': pl_id,
'title': title,
'entries': entries,
}
| gpl-3.0 |
rcbrgs/tuna | tuna/test/unit/unit_io/unit_test_io_adhoc.py | 1907 | __version__ = "0.1.1"
__changelog = {
"0.1.1": {"Tuna": "0.16.5", "Change": "PEP8 and PEP 257 compliance."},
"0.1.0": {"Tuna": "0.13.0", "Change": "Updated test_wrong_dimension to use "\
"newly protected method _discover_adhoc_type of tuna.io.adhoc."}
}
import logging
import os
import tuna
import unittest
class unit_test_io_adhoc(unittest.TestCase):
def setUp(self):
self.here = os.getcwd()
self.home = os.path.expanduser("~")
tuna.log.set_path(self.home + "/nose.log")
self.log = logging.getLogger(__name__)
self.log.error("here = {}".format(self.here))
def test_empty_file(self):
tuna.io.read(self.here + "/tuna/test/unit/unit_io/fake_adhoc.ad2")
def test_no_file_name(self):
ad = tuna.io.Adhoc()
ad.read()
def test_nonexisting_file(self):
flag = False
nonexisting_file_number = 0
file_name = ""
while not flag:
nonexisting_file_number += 1
file_name = 'adhoc_test_file_' + str(nonexisting_file_number) +'.ad2'
try:
open(file_name, 'r')
except OSError:
flag = True
# Unless a race condition, adhoc_test_file_?.ad2 does not exist.
self.assertRaises(OSError, tuna.io.read, file_name)
def test_valid_2d_file ( self ):
tuna.io.read(self.here + "/tuna/test/unit/unit_io/adhoc.ad2")
def test_valid_3d_file ( self ):
tuna.io.read(self.here + "/tuna/test/unit/unit_io/adhoc.ad3")
def test_wrong_dimenson ( self ):
ad = tuna.io.Adhoc(file_name = self.here \
+ "/tuna/test/unit/unit_io/adhoc.ad3")
ad._discover_adhoc_type()
self.assertRaises(ValueError, ad._read_adhoc_2d)
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
| gpl-3.0 |
tristanklempka/TerrainGenerator | source/display.cpp | 932 | #include "display.hpp"
#include <iostream>
Display::Display(int width, int height, const std::string& title):
m_window(sf::VideoMode(width, height), title, sf::Style::Default, sf::ContextSettings(24, 8, 4, 3, 0))
{
m_window.setVerticalSyncEnabled(true);
GLenum res = glewInit();
if(res != GLEW_OK)
{
std::cerr << "Glew failed to initialize!" << std::endl;
}
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
// WIREFRAME
//glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
}
Display::~Display()
{
}
void Display::Clear(float r, float g, float b, float a)
{
glClearColor(r, g, b, a);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Display::Show()
{
m_window.display();
}
bool Display::PollEvent(sf::Event& event)
{
return m_window.pollEvent(event);
}
void Display::Close()
{
m_window.close();
}
bool Display::IsOpen()
{
return m_window.isOpen();
}
| gpl-3.0 |
bencesomogyi/pyCFD | pyCFD_mesh/patch.py | 5840 | """
module for patches
"""
__author__ = "Bence Somogyi"
__copyright__ = "Copyright 2014"
__version__ = "0.1"
__maintainer__ = "Bence Somogyi"
__email__ = "bencesomogyi@ivt.tugraz.at"
__status__ = "Prototype"
import sys
import numpy
class Patch:
"""
class for geometric patches
"""
def __init__(self, face_list, patch_name, check_independent=False):
"""
**Constructor**
:param face_list: list of faces in the patch
:type face_list: :class:`pyCFD_mesh.face.Face`
:param patch_name: name to use for the resulting patch
:type patch_name: string
:param check_independent: default: False, whether to check if faces are independent
:type check_independent: bool
"""
if check_independent:
facesIndependent = True
for indFaceI in range(len(face_list)-1):
for faceJ in face_list[indFaceI+1:]:
if faceJ.are_faces_equal(face_list[indFaceI],faceJ):
facesIndependent = False
if facesIndependent == False:
print "faces are not independent in ", self
return
self.faces = face_list
"""list of faces in the patch"""
self.name = patch_name
"""name of patch"""
self.ids = [face_list[face_i].id for face_i in xrange(len(face_list))]
"""list of face ids in the patch"""
class FieldPatch:
"""class for field patches"""
def __init__(self, field, geometric_patch):
"""
**Constructor**
The field patch is initialized with fixedValue type and with face
values of 0.0.
:param field: reference to field object
:type field: :class:`pyCFD_fields.fields.VolumeField`
:param geometric_patch: reference to geometric patch
:type geometric_patch: :class:`Patch`
"""
self.father = []
"""reference to father geometric patch object"""
self.type = "fixedValue"
"""patch type: 'fixedValue' or 'fixedGradient'"""
if field.type == "scalar":
self.values = numpy.zeros(len(geometric_patch.faces))
else:
self.values = numpy.zeros((len(geometric_patch.faces),3))
"""list of boundary values for each patch faces"""
self.field = field
"""reference to owner field"""
self.father.append(geometric_patch)
self.name = geometric_patch.name + "__" + field.name
def set_patch_uniform(self, boundary_value, boundary_type):
"""
set up patch with uniform boundary values
"""
# check type
available_types = []
available_types.append("fixedValue")
available_types.append("fixedGradient")
if boundary_type not in available_types:
print "not supported boundary type "+boundary_type+" defined, availabe types are:"
print available_types
sys.exit()
self.type = boundary_type
vector_field = False
if (self.field.type == "vector"):
vector_field = True
fixed_value = False
if boundary_type == "fixedValue":
fixed_value = True
if vector_field and fixed_value:
self.values = numpy.zeros((len(self.father[0].faces),3))
for face_i,face_ in enumerate(self.father[0].faces):
self.values[face_i, :] = boundary_value
face_.bndType = boundary_type
else:
self.values = numpy.zeros(len(self.father[0].faces))
for face_i,face_ in enumerate(self.father[0].faces):
self.values[face_i] = boundary_value
face_.bndType = boundary_type
def set_patch_distributed(self, boundary_values, boundary_type):
"""
set up patch with non-uniform boundary values
"""
# check boundary type
if boundary_type != "fixedValue" and boundary_type != "fixedGradient":
print "not supported boundary type '" + boundary_type + "' in set_patch_uniform"
print "supported types are: 'fixedValue' and 'fixedGradient'"
sys.exit()
self.type = boundary_type
# check length of boundary value vector
if len(boundary_values) != len(self.father[0].faces):
print "define distributed patch with "+str(len(self.father[0].faces))+" faces, only "+str(len(boundary_values))+" defined..."
sys.exit()
vector_field = False
if (self.field.type == "vector"):
vector_field = True
fixed_value = False
if boundary_type == "fixedValue":
fixed_value = True
if vector_field and fixed_value:
self.values = numpy.zeros((len(self.father[0].faces),3))
for face_i,face_ in enumerate(self.father[0].faces):
self.values[face_i, :] = boundary_values[face_i]
face_.bndType = boundary_type
else:
self.values = numpy.zeros(len(self.father[0].faces))
for face_i,face_ in enumerate(self.father[0].faces):
self.values[face_i] = boundary_values[face_i]
face_.bndType = boundary_type
def find_face_id_in_patch(self, face_):
"""
return face id within the patch
:param face_: face object to find
:type face_: :class:`pyCFD_mesh.face.face`
:return: face id in patch
:rtype: int
"""
return face_.id - self.father[0].ids[0] | gpl-3.0 |
ftninformatika/bisis-v5 | bisis-swing-client/src/main/java/com/ftninformatika/utils/sort/Sorter.java | 3922 | package com.ftninformatika.utils.sort;
import com.ftninformatika.utils.string.StringUtils;
import java.util.Vector;
/**
* Created by Petar on 8/7/2017.
*/
public class Sorter
{
public Sorter() {}
public static String qsort(String s)
{
byte[] b = StringUtils.getLowerBytes(s);
qsort(0, b.length - 1, b);
return StringUtils.getStringLower(b);
}
public static void qsort(int[] niz)
{
qsort(0, niz.length - 1, niz);
}
public static void qsort(byte[] niz)
{
qsort(0, niz.length - 1, niz);
}
public static void qsort(String[] niz)
{
qsort(0, niz.length - 1, niz);
}
public static void qsort(Sortable[] array)
{
qsort(0, array.length - 1, array);
}
public static Vector sortVector(Vector v)
{
Vector retVal = new Vector();
String[] niz = (String[])null;
String[] sniz = (String[])null;
niz = new String[v.size()];
v.copyInto(niz);
qsort(niz);
for (int i = 0; i < niz.length; i++)
retVal.addElement(niz[i]);
return retVal;
}
public static void qsort(int d, int g, byte[] a)
{
if (d >= g) {
return;
}
if (d + 1 == g) {
if (a[d] > a[g])
{
byte k = a[d];
a[d] = a[g];
a[g] = k;
}
return;
}
int j = d;
for (int i = d + 1; i <= g; i++) {
if (a[i] <= a[d])
{
j++;
byte k = a[j];
a[j] = a[i];
a[i] = k;
}
}
byte k = a[d];
a[d] = a[j];
a[j] = k;
qsort(d, j - 1, a);
qsort(j + 1, g, a);
}
public static void qsort(int d, int g, String[] a)
{
if (d >= g) {
return;
}
if (d + 1 == g) {
if (a[d].compareTo(a[g]) > 0)
{
String k = a[d];
a[d] = a[g];
a[g] = k;
}
return;
}
int j = d;
for (int i = d + 1; i <= g; i++) {
if (a[i].compareTo(a[d]) <= 0)
{
j++;
String k = a[j];
a[j] = a[i];
a[i] = k;
}
}
String k = a[d];
a[d] = a[j];
a[j] = k;
qsort(d, j - 1, a);
qsort(j + 1, g, a);
}
public static void qsort(int d, int g, int[] a)
{
if (d >= g) {
return;
}
if (d + 1 == g) {
if (a[d] > a[g])
{
int k = a[d];
a[d] = a[g];
a[g] = k;
}
return;
}
int j = d;
for (int i = d + 1; i <= g; i++) {
if (a[i] <= a[d])
{
j++;
int k = a[j];
a[j] = a[i];
a[i] = k;
}
}
int k = a[d];
a[d] = a[j];
a[j] = k;
qsort(d, j - 1, a);
qsort(j + 1, g, a);
}
public static void qsort(int d, int g, Sortable[] a)
{
if (d >= g) {
return;
}
if (d + 1 == g) {
if (a[d].compareTo(a[g]) > 0)
{
Sortable k = a[d];
a[d] = a[g];
a[g] = k;
}
return;
}
int j = d;
for (int i = d + 1; i <= g; i++) {
if (a[i].compareTo(a[d]) <= 0)
{
j++;
Sortable k = a[j];
a[j] = a[i];
a[i] = k;
}
}
Sortable k = a[d];
a[d] = a[j];
a[j] = k;
qsort(d, j - 1, a);
qsort(j + 1, g, a);
}
} | gpl-3.0 |
JacobCZ/GitHub-Monitor | jHUB/Loggator.Designer.cs | 2935 | namespace jHUB
{
partial class Loggator
{
/// <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.listBox1 = new System.Windows.Forms.ListBox();
this.panel1 = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// listBox1
//
this.listBox1.BackColor = System.Drawing.Color.Black;
this.listBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.listBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
this.listBox1.ForeColor = System.Drawing.Color.LawnGreen;
this.listBox1.FormattingEnabled = true;
this.listBox1.ItemHeight = 18;
this.listBox1.Location = new System.Drawing.Point(0, 0);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(605, 301);
this.listBox1.TabIndex = 0;
//
// panel1
//
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(605, 301);
this.panel1.TabIndex = 1;
//
// Loggator
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(605, 301);
this.Controls.Add(this.listBox1);
this.Controls.Add(this.panel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
this.Name = "Loggator";
this.Text = "Console";
this.Load += new System.EventHandler(this.Console_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.Panel panel1;
}
} | gpl-3.0 |
AmazingCow-Game/Game_BowAndArrow | project/Game/Enemies/Fireball.cs | 6977 | //----------------------------------------------------------------------------//
// █ █ //
// ████████ //
// ██ ██ //
// ███ █ █ ███ Fireball.cs //
// █ █ █ █ Game_BowAndArrow //
// ████████████ //
// █ █ Copyright (c) 2016 //
// █ █ █ █ AmazingCow - www.AmazingCow.com //
// █ █ █ █ //
// █ █ N2OMatt - n2omatt@amazingcow.com //
// ████████████ www.amazingcow.com/n2omatt //
// //
// This software is licensed as GPLv3 //
// CHECK THE COPYING FILE TO MORE DETAILS //
// //
// Permission is granted to anyone to use this software for any purpose, //
// including commercial applications, and to alter it and redistribute it //
// freely, subject to the following restrictions: //
// //
// 0. You **CANNOT** change the type of the license. //
// 1. The origin of this software must not be misrepresented; //
// you must not claim that you wrote the original software. //
// 2. If you use this software in a product, an acknowledgment in the //
// product IS HIGHLY APPRECIATED, both in source and binary forms. //
// (See opensource.AmazingCow.com/acknowledgment.html for details). //
// If you will not acknowledge, just send us a email. We'll be //
// *VERY* happy to see our work being used by other people. :) //
// The email is: acknowledgment_opensource@AmazingCow.com //
// 3. Altered source versions must be plainly marked as such, //
// and must not be misrepresented as being the original software. //
// 4. This notice may not be removed or altered from any source //
// distribution. //
// 5. Most important, you must have fun. ;) //
// //
// Visit opensource.amazingcow.com for more open-source projects. //
// //
// Enjoy :) //
//----------------------------------------------------------------------------//
#region Usings
//System
using System;
//Xna
using Microsoft.Xna.Framework;
#endregion //Usings
namespace com.amazingcow.BowAndArrow
{
public class Fireball : Enemy
{
#region Constants
//Public
public const int kHeight = 49;
public const int kWidth = 39;
public const int kScoreValue = 600;
//Private
const int kSpeedMin = 120;
const int kSpeedMax = 180;
#endregion
#region Public Properties
public override int ScoreValue { get { return kScoreValue; } }
#endregion
#region iVars
Clock _dyingClock;
#endregion //iVars
#region CTOR
public Fireball(Vector2 position)
: base(position, Vector2.Zero, 100)
{
//Initialize the textures...
var resMgr = ResourcesManager.Instance;
AliveTexturesList.Add(resMgr.GetTexture("fire1"));
AliveTexturesList.Add(resMgr.GetTexture("fire2"));
DyingTexturesList.Add(resMgr.GetTexture("fire_dead"));
//Init the Speed...
int xSpeed = GameManager.Instance.RandomNumGen.Next(kSpeedMin,
kSpeedMax);
Speed = new Vector2(-xSpeed, 0);
//Init the timers...
_dyingClock = new Clock(500, 1);
_dyingClock.OnTick += OnDyingClockTick;
}
#endregion //CTOR
#region Update / Draw
public override void Update(GameTime gt)
{
//Fireball is already dead - Don't need to do anything else.
if(CurrentState == State.Dead)
return;
base.Update(gt);
_dyingClock.Update(gt.ElapsedGameTime.Milliseconds);
//Just move in alive - Dying it will only glow.
if(CurrentState == State.Alive)
MoveAlive(gt);
}
#endregion //Update / Draw
#region Public Methods
public override void Kill()
{
//Already Dead - Don't do anything else...
if(CurrentState != State.Alive)
return;
CurrentState = State.Dying;
_dyingClock.Start();
Speed = Vector2.Zero;
}
public override bool CheckCollisionPlayer(Archer archer)
{
if(CurrentState != State.Alive)
return false;
return archer.BoundingBox.Intersects(this.BoundingBox);
}
#endregion //Public Methods
#region Private Methods
void MoveAlive(GameTime gt)
{
//Update the position.
Position += (Speed * (gt.ElapsedGameTime.Milliseconds / 1000f));
var bounds = GameManager.Instance.CurrentLevel.PlayField;
if(BoundingBox.Right < bounds.Left)
ResetPosition();
}
#endregion //Private Methods
#region Timers Callbacks
void OnDyingClockTick(object sender, EventArgs e)
{
CurrentState = State.Dead;
}
#endregion //Timers Callbacks
#region Helper Methods
void ResetPosition()
{
var bounds = GameManager.Instance.CurrentLevel.PlayField;
var rnd = GameManager.Instance.RandomNumGen;
var x = rnd.Next(bounds.Right, bounds.Right * 2);
var y = rnd.Next(bounds.Top + BoundingBox.Height,
bounds.Bottom - BoundingBox.Height);
Position = new Vector2(x, y);
}
#endregion //Helper Methods
}//Class Fireball
}//namespace com.amazingcow.BowAndArrow
| gpl-3.0 |
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2 | src/finiteVolume/fields/fvPatchFields/derived/partialSlip/partialSlipFvPatchField.H | 6369 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration | Version: 3.2
\\ / A nd | Web: http://www.foam-extend.org
\\/ M anipulation | For copyright notice see file Copyright
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend 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.
foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::partialSlipFvPatchField
Description
Foam::partialSlipFvPatchField
SourceFiles
partialSlipFvPatchField.C
\*---------------------------------------------------------------------------*/
#ifndef partialSlipFvPatchField_H
#define partialSlipFvPatchField_H
#include "transformFvPatchField.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class partialSlipFvPatch Declaration
\*---------------------------------------------------------------------------*/
template<class Type>
class partialSlipFvPatchField
:
public transformFvPatchField<Type>
{
// Private data
//- Fraction (0-1) of value used for boundary condition
scalarField valueFraction_;
public:
//- Runtime type information
TypeName("partialSlip");
// Constructors
//- Construct from patch and internal field
partialSlipFvPatchField
(
const fvPatch&,
const DimensionedField<Type, volMesh>&
);
//- Construct from patch, internal field and dictionary
partialSlipFvPatchField
(
const fvPatch&,
const DimensionedField<Type, volMesh>&,
const dictionary&
);
//- Construct by mapping given partialSlipFvPatchField onto a new patch
partialSlipFvPatchField
(
const partialSlipFvPatchField<Type>&,
const fvPatch&,
const DimensionedField<Type, volMesh>&,
const fvPatchFieldMapper&
);
//- Construct as copy
partialSlipFvPatchField
(
const partialSlipFvPatchField<Type>&
);
//- Construct and return a clone
virtual tmp<fvPatchField<Type> > clone() const
{
return tmp<fvPatchField<Type> >
(
new partialSlipFvPatchField<Type>(*this)
);
}
//- Construct as copy setting internal field reference
partialSlipFvPatchField
(
const partialSlipFvPatchField<Type>&,
const DimensionedField<Type, volMesh>&
);
//- Construct and return a clone setting internal field reference
virtual tmp<fvPatchField<Type> > clone
(
const DimensionedField<Type, volMesh>& iF
) const
{
return tmp<fvPatchField<Type> >
(
new partialSlipFvPatchField<Type>(*this, iF)
);
}
// Member functions
// Mapping functions
//- Map (and resize as needed) from self given a mapping object
virtual void autoMap
(
const fvPatchFieldMapper&
);
//- Reverse map the given fvPatchField onto this fvPatchField
virtual void rmap
(
const fvPatchField<Type>&,
const labelList&
);
// Return defining fields
virtual scalarField& valueFraction()
{
return valueFraction_;
}
virtual const scalarField& valueFraction() const
{
return valueFraction_;
}
// Evaluation functions
//- Return gradient at boundary
virtual tmp<Field<Type> > snGrad() const;
//- Evaluate the patch field
// Default argument needed to allow call in constructors
// HJ, 30/Jun/2009
virtual void evaluate
(
const Pstream::commsTypes commsType = Pstream::blocking
);
//- Return face-gradient transform diagonal
virtual tmp<Field<Type> > snGradTransformDiag() const;
//- Write
virtual void write(Ostream&) const;
// Member operators
virtual void operator=(const UList<Type>&) {}
virtual void operator=(const fvPatchField<Type>&) {}
virtual void operator+=(const fvPatchField<Type>&) {}
virtual void operator-=(const fvPatchField<Type>&) {}
virtual void operator*=(const fvPatchField<scalar>&) {}
virtual void operator/=(const fvPatchField<scalar>&) {}
virtual void operator+=(const Field<Type>&) {}
virtual void operator-=(const Field<Type>&) {}
virtual void operator*=(const Field<scalar>&) {}
virtual void operator/=(const Field<scalar>&) {}
virtual void operator=(const Type&) {}
virtual void operator+=(const Type&) {}
virtual void operator-=(const Type&) {}
virtual void operator*=(const scalar) {}
virtual void operator/=(const scalar) {}
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#ifdef NoRepository
# include "partialSlipFvPatchField.C"
#endif
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| gpl-3.0 |
mc-suchecki/MSc | scripts/display_photos.py | 559 | from PIL import Image
# settings
PHOTOS_LOCATION = '../data/train/'
PHOTOS_LIST_FILE = PHOTOS_LOCATION + 'list.txt'
with open(PHOTOS_LIST_FILE) as photos_list_file:
photos_list = photos_list_file.readlines()
for line in photos_list:
photo_metadata_list = line.split(',')
photo_id = str(photo_metadata_list[0])
photo_label = int(photo_metadata_list[1])
photo = Image.open(PHOTOS_LOCATION + photo_id + '.jpg')
photo.show()
input('Showing a {} photo. Press any key for the next one.'.format('bad' if photo_label == 0 else 'good'))
| gpl-3.0 |
mscg82/Slide | app/src/main/java/me/ccrama/redditslide/Fragments/SubmissionsView.java | 33202 | package me.ccrama.redditslide.Fragments;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.view.MarginLayoutParamsCompat;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.view.ContextThemeWrapper;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.afollestad.materialdialogs.AlertDialogWrapper;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.mikepenz.itemanimators.AlphaInAnimator;
import com.mikepenz.itemanimators.SlideUpAlphaAnimator;
import me.ccrama.redditslide.Activities.*;
import net.dean.jraw.models.Submission;
import java.util.List;
import java.util.Locale;
import me.ccrama.redditslide.Adapters.SubmissionAdapter;
import me.ccrama.redditslide.Adapters.SubmissionDisplay;
import me.ccrama.redditslide.Adapters.SubredditPosts;
import me.ccrama.redditslide.ColorPreferences;
import me.ccrama.redditslide.Constants;
import me.ccrama.redditslide.HasSeen;
import me.ccrama.redditslide.Hidden;
import me.ccrama.redditslide.OfflineSubreddit;
import me.ccrama.redditslide.R;
import me.ccrama.redditslide.Reddit;
import me.ccrama.redditslide.SettingValues;
import me.ccrama.redditslide.Views.CatchStaggeredGridLayoutManager;
import me.ccrama.redditslide.Views.CreateCardView;
import me.ccrama.redditslide.Visuals.Palette;
import me.ccrama.redditslide.handler.ToolbarScrollHideHandler;
public class SubmissionsView extends Fragment implements SubmissionDisplay {
private static int adapterPosition;
private static int currentPosition;
public SubredditPosts posts;
public RecyclerView rv;
public SubmissionAdapter adapter;
public String id;
public boolean main;
public boolean forced;
int diff;
boolean forceLoad;
private FloatingActionButton fab;
private int visibleItemCount;
private int pastVisiblesItems;
private int totalItemCount;
private SwipeRefreshLayout mSwipeRefreshLayout;
private static Submission currentSubmission;
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
final int currentOrientation = newConfig.orientation;
final CatchStaggeredGridLayoutManager mLayoutManager =
(CatchStaggeredGridLayoutManager) rv.getLayoutManager();
mLayoutManager.setSpanCount(getNumColumns(currentOrientation, getActivity()));
}
Runnable mLongPressRunnable;
GestureDetector detector = new GestureDetector(getActivity(), new GestureDetector.SimpleOnGestureListener());
float origY;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(),
new ColorPreferences(inflater.getContext()).getThemeSubreddit(id));
final View v = ((LayoutInflater) contextThemeWrapper.getSystemService(
Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.fragment_verticalcontent,
container, false);
if (getActivity() instanceof MainActivity) {
v.findViewById(R.id.back).setBackgroundResource(0);
}
rv = v.findViewById(R.id.vertical_content);
rv.setHasFixedSize(true);
final RecyclerView.LayoutManager mLayoutManager;
mLayoutManager =
createLayoutManager(getNumColumns(getResources().getConfiguration().orientation, getActivity()));
if (!(getActivity() instanceof SubredditView)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
v.findViewById(R.id.back).setBackground(null);
} else {
v.findViewById(R.id.back).setBackgroundDrawable(null);
}
}
rv.setLayoutManager(mLayoutManager);
rv.setItemAnimator(new SlideUpAlphaAnimator().withInterpolator(new LinearOutSlowInInterpolator()));
rv.getLayoutManager().scrollToPosition(0);
mSwipeRefreshLayout = v.findViewById(R.id.activity_main_swipe_refresh_layout);
mSwipeRefreshLayout.setColorSchemeColors(Palette.getColors(id, getContext()));
/**
* If using List view mode, we need to remove the start margin from the SwipeRefreshLayout.
* The scrollbar style of "outsideInset" creates a 4dp padding around it. To counter this,
* change the scrollbar style to "insideOverlay" when list view is enabled.
* To recap: this removes the margins from the start/end so list view is full-width.
*/
if (SettingValues.defaultCardView == CreateCardView.CardEnum.LIST) {
RelativeLayout.LayoutParams params =
new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
params.setMarginStart(0);
} else {
MarginLayoutParamsCompat.setMarginStart(params, 0);
}
rv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mSwipeRefreshLayout.setLayoutParams(params);
}
/**
* If we use 'findViewById(R.id.header).getMeasuredHeight()', 0 is always returned.
* So, we estimate the height of the header in dp.
* If the view type is "single" (and therefore "commentPager"), we need a different offset
*/
final int HEADER_OFFSET = (SettingValues.single || getActivity() instanceof SubredditView)
? Constants.SINGLE_HEADER_VIEW_OFFSET : Constants.TAB_HEADER_VIEW_OFFSET;
mSwipeRefreshLayout.setProgressViewOffset(false, HEADER_OFFSET - Constants.PTR_OFFSET_TOP,
HEADER_OFFSET + Constants.PTR_OFFSET_BOTTOM);
if (SettingValues.fab) {
fab = v.findViewById(R.id.post_floating_action_button);
if (SettingValues.fabType == Constants.FAB_POST) {
fab.setImageResource(R.drawable.add);
fab.setContentDescription(getString(R.string.btn_fab_post));
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent inte = new Intent(getActivity(), Submit.class);
inte.putExtra(Submit.EXTRA_SUBREDDIT, id);
getActivity().startActivity(inte);
}
});
} else if (SettingValues.fabType == Constants.FAB_SEARCH) {
fab.setImageResource(R.drawable.search);
fab.setContentDescription(getString(R.string.btn_fab_search));
fab.setOnClickListener(new View.OnClickListener() {
String term;
@Override
public void onClick(View v) {
MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity())
.title(R.string.search_title)
.alwaysCallInputCallback()
.input(getString(R.string.search_msg), "",
new MaterialDialog.InputCallback() {
@Override
public void onInput(MaterialDialog materialDialog,
CharSequence charSequence) {
term = charSequence.toString();
}
});
//Add "search current sub" if it is not frontpage/all/random
if (!id.equalsIgnoreCase("frontpage")
&& !id.equalsIgnoreCase("all")
&& !id.contains(".")
&& !id.contains("/m/")
&& !id.equalsIgnoreCase("friends")
&& !id.equalsIgnoreCase("random")
&& !id.equalsIgnoreCase("popular")
&& !id.equalsIgnoreCase("myrandom")
&& !id.equalsIgnoreCase("randnsfw")) {
builder.positiveText(getString(R.string.search_subreddit, id))
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog materialDialog,
@NonNull DialogAction dialogAction) {
Intent i = new Intent(getActivity(), Search.class);
i.putExtra(Search.EXTRA_TERM, term);
i.putExtra(Search.EXTRA_SUBREDDIT, id);
startActivity(i);
}
});
builder.neutralText(R.string.search_all)
.onNeutral(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog materialDialog,
@NonNull DialogAction dialogAction) {
Intent i = new Intent(getActivity(), Search.class);
i.putExtra(Search.EXTRA_TERM, term);
startActivity(i);
}
});
} else {
builder.positiveText(R.string.search_all)
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog materialDialog,
@NonNull DialogAction dialogAction) {
Intent i = new Intent(getActivity(), Search.class);
i.putExtra(Search.EXTRA_TERM, term);
startActivity(i);
}
});
}
builder.show();
}
});
} else {
fab.setImageResource(R.drawable.hide);
fab.setContentDescription(getString(R.string.btn_fab_hide));
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!Reddit.fabClear) {
new AlertDialogWrapper.Builder(getActivity()).setTitle(
R.string.settings_fabclear)
.setMessage(R.string.settings_fabclear_msg)
.setPositiveButton(R.string.btn_ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
Reddit.colors.edit()
.putBoolean(
SettingValues.PREF_FAB_CLEAR,
true)
.apply();
Reddit.fabClear = true;
clearSeenPosts(false);
}
})
.show();
} else {
clearSeenPosts(false);
}
}
});
final Handler handler = new Handler();
fab.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
detector.onTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
origY = event.getY();
handler.postDelayed(mLongPressRunnable, android.view.ViewConfiguration.getLongPressTimeout());
}
if (((event.getAction() == MotionEvent.ACTION_MOVE) && Math.abs(event.getY() - origY) > fab.getHeight()/2)|| (event.getAction() == MotionEvent.ACTION_UP)) {
handler.removeCallbacks(mLongPressRunnable);
}
return false;
}
});
mLongPressRunnable = new Runnable() {
public void run() {
fab.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
if (!Reddit.fabClear) {
new AlertDialogWrapper.Builder(getActivity()).setTitle(
R.string.settings_fabclear)
.setMessage(R.string.settings_fabclear_msg)
.setPositiveButton(R.string.btn_ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
Reddit.colors.edit()
.putBoolean(
SettingValues.PREF_FAB_CLEAR,
true)
.apply();
Reddit.fabClear = true;
clearSeenPosts(true);
}
})
.show();
} else {
clearSeenPosts(true);
}
Snackbar s = Snackbar.make(rv,
getResources().getString(R.string.posts_hidden_forever),
Snackbar.LENGTH_LONG);
/*Todo a way to unhide
s.setAction(R.string.btn_undo, new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});*/
View view = s.getView();
TextView tv = view.findViewById(
android.support.design.R.id.snackbar_text);
tv.setTextColor(Color.WHITE);
s.show();
}
};
}
} else {
v.findViewById(R.id.post_floating_action_button).setVisibility(View.GONE);
}
if (fab != null) fab.show();
header = getActivity().findViewById(R.id.header);
//TODO, have it so that if the user clicks anywhere in the rv to hide and cancel GoToSubreddit?
// final TextInputEditText GO_TO_SUB_FIELD = (TextInputEditText) getActivity().findViewById(R.id.toolbar_search);
// final Toolbar TOOLBAR = ((Toolbar) getActivity().findViewById(R.id.toolbar));
// final String PREV_TITLE = TOOLBAR.getTitle().toString();
// final ImageView CLOSE_BUTTON = (ImageView) getActivity().findViewById(R.id.close);
//
// rv.setOnTouchListener(new View.OnTouchListener() {
// @Override
// public boolean onTouch(View v, MotionEvent event) {
// System.out.println("touched");
// InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
//
// GO_TO_SUB_FIELD.setText("");
// GO_TO_SUB_FIELD.setVisibility(View.GONE);
// CLOSE_BUTTON.setVisibility(View.GONE);
// TOOLBAR.setTitle(PREV_TITLE);
//
// return false;
// }
// });
resetScroll();
Reddit.isLoading = false;
if (MainActivity.shouldLoad == null
|| id == null
|| (MainActivity.shouldLoad != null
&& MainActivity.shouldLoad.equals(id))
|| !(getActivity() instanceof MainActivity)) {
doAdapter();
}
return v;
}
View header;
ToolbarScrollHideHandler toolbarScroll;
@NonNull
public static RecyclerView.LayoutManager createLayoutManager(final int numColumns) {
return new CatchStaggeredGridLayoutManager(numColumns,
CatchStaggeredGridLayoutManager.VERTICAL);
}
public static int getNumColumns(final int orientation, Activity context) {
final int numColumns;
boolean singleColumnMultiWindow = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
singleColumnMultiWindow = context.isInMultiWindowMode() && SettingValues.singleColumnMultiWindow;
}
if (orientation == Configuration.ORIENTATION_LANDSCAPE && SettingValues.isPro && !singleColumnMultiWindow) {
numColumns = Reddit.dpWidth;
} else if (orientation == Configuration.ORIENTATION_PORTRAIT
&& SettingValues.dualPortrait) {
numColumns = 2;
} else {
numColumns = 1;
}
return numColumns;
}
public void doAdapter() {
if (!MainActivity.isRestart) {
mSwipeRefreshLayout.post(new Runnable() {
@Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
}
});
}
posts = new SubredditPosts(id, getContext());
adapter = new SubmissionAdapter(getActivity(), posts, rv, id, this);
adapter.setHasStableIds(true);
rv.setAdapter(adapter);
posts.loadMore(getActivity(), this, true);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refresh();
}
});
}
public void doAdapter(boolean force18) {
mSwipeRefreshLayout.post(new Runnable() {
@Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
}
});
posts = new SubredditPosts(id, getContext(), force18);
adapter = new SubmissionAdapter(getActivity(), posts, rv, id, this);
adapter.setHasStableIds(true);
rv.setAdapter(adapter);
posts.loadMore(getActivity(), this, true);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refresh();
}
});
}
public List<Submission> clearSeenPosts(boolean forever) {
if (adapter.dataSet.posts != null) {
List<Submission> originalDataSetPosts = adapter.dataSet.posts;
OfflineSubreddit o =
OfflineSubreddit.getSubreddit(id.toLowerCase(Locale.ENGLISH), false, getActivity());
for (int i = adapter.dataSet.posts.size(); i > -1; i--) {
try {
if (HasSeen.getSeen(adapter.dataSet.posts.get(i))) {
if (forever) {
Hidden.setHidden(adapter.dataSet.posts.get(i));
}
o.clearPost(adapter.dataSet.posts.get(i));
adapter.dataSet.posts.remove(i);
if (adapter.dataSet.posts.isEmpty()) {
adapter.notifyDataSetChanged();
} else {
rv.setItemAnimator(new AlphaInAnimator());
adapter.notifyItemRemoved(i + 1);
}
}
} catch (IndexOutOfBoundsException e) {
//Let the loop reset itself
}
}
adapter.notifyItemRangeChanged(0, adapter.dataSet.posts.size());
o.writeToMemoryNoStorage();
rv.setItemAnimator(new SlideUpAlphaAnimator().withInterpolator(new LinearOutSlowInInterpolator()));
return originalDataSetPosts;
}
return null;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
id = bundle.getString("id", "");
main = bundle.getBoolean("main", false);
forceLoad = bundle.getBoolean("load", false);
}
@Override
public void onResume() {
super.onResume();
if (adapter != null && adapterPosition > 0 && currentPosition == adapterPosition) {
if (adapter.dataSet.getPosts().size() >= adapterPosition - 1
&& adapter.dataSet.getPosts().get(adapterPosition - 1) == currentSubmission) {
adapter.performClick(adapterPosition);
adapterPosition = -1;
}
}
}
public static void datachanged(int adaptorPosition2) {
adapterPosition = adaptorPosition2;
}
private void refresh() {
posts.forced = true;
forced = true;
posts.loadMore(mSwipeRefreshLayout.getContext(), this, true, id);
}
public void forceRefresh() {
toolbarScroll.toolbarShow();
rv.getLayoutManager().scrollToPosition(0);
mSwipeRefreshLayout.post(new Runnable() {
@Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
refresh();
}
});
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void updateSuccess(final List<Submission> submissions, final int startIndex) {
if (getActivity() != null) {
if (getActivity() instanceof MainActivity) {
if (((MainActivity) getActivity()).runAfterLoad != null) {
new Handler().post(((MainActivity) getActivity()).runAfterLoad);
}
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (mSwipeRefreshLayout != null) {
mSwipeRefreshLayout.setRefreshing(false);
}
if (startIndex != -1 && !forced ) {
adapter.notifyItemRangeInserted(startIndex + 1, posts.posts.size());
adapter.notifyDataSetChanged();
} else {
forced = false;
rv.scrollToPosition(0);
adapter.notifyDataSetChanged();
}
}
});
if (MainActivity.isRestart) {
MainActivity.isRestart = false;
posts.offline = false;
rv.getLayoutManager().scrollToPosition(MainActivity.restartPage + 1);
}
if (startIndex < 10) resetScroll();
}
}
@Override
public void updateOffline(List<Submission> submissions, final long cacheTime) {
if (getActivity() instanceof MainActivity) {
if (((MainActivity) getActivity()).runAfterLoad != null) {
new Handler().post(((MainActivity) getActivity()).runAfterLoad);
}
}
if (this.isAdded()) {
if (mSwipeRefreshLayout != null) {
mSwipeRefreshLayout.setRefreshing(false);
}
adapter.notifyDataSetChanged();
}
}
@Override
public void updateOfflineError() {
if (getActivity() instanceof MainActivity) {
if (((MainActivity) getActivity()).runAfterLoad != null) {
new Handler().post(((MainActivity) getActivity()).runAfterLoad);
}
}
mSwipeRefreshLayout.setRefreshing(false);
adapter.setError(true);
}
@Override
public void updateError() {
if (getActivity() instanceof MainActivity) {
if (((MainActivity) getActivity()).runAfterLoad != null) {
new Handler().post(((MainActivity) getActivity()).runAfterLoad);
}
}
mSwipeRefreshLayout.setRefreshing(false);
adapter.setError(true);
}
@Override
public void updateViews() {
if (adapter.dataSet.posts != null) {
for (int i = adapter.dataSet.posts.size(); i > -1; i--) {
try {
if (HasSeen.getSeen(adapter.dataSet.posts.get(i))) {
adapter.notifyItemChanged(i + 1);
}
} catch (IndexOutOfBoundsException e) {
//Let the loop reset itself
}
}
}
}
@Override
public void onAdapterUpdated() {
adapter.notifyDataSetChanged();
}
public void resetScroll() {
if (toolbarScroll == null) {
toolbarScroll =
new ToolbarScrollHideHandler(((BaseActivity) getActivity()).mToolbar, header) {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (!posts.loading && !posts.nomore && !posts.offline && !adapter.isError){
visibleItemCount = rv.getLayoutManager().getChildCount();
totalItemCount = rv.getLayoutManager().getItemCount();
int[] firstVisibleItems;
firstVisibleItems =
((CatchStaggeredGridLayoutManager) rv.getLayoutManager()).findFirstVisibleItemPositions(
null);
if (firstVisibleItems != null && firstVisibleItems.length > 0) {
for (int firstVisibleItem : firstVisibleItems) {
pastVisiblesItems = firstVisibleItem;
if (SettingValues.scrollSeen
&& pastVisiblesItems > 0
&& SettingValues.storeHistory) {
HasSeen.addSeenScrolling(posts.posts.get(pastVisiblesItems - 1)
.getFullName());
}
}
}
if ((visibleItemCount + pastVisiblesItems) + 5 >= totalItemCount) {
posts.loading = true;
posts.loadMore(mSwipeRefreshLayout.getContext(),
SubmissionsView.this, false, posts.subreddit);
}
}
/*
if(dy <= 0 && !down){
(getActivity()).findViewById(R.id.header).animate().translationY(((BaseActivity)getActivity()).mToolbar.getTop()).setInterpolator(new AccelerateInterpolator()).start();
down = true;
} else if(down){
(getActivity()).findViewById(R.id.header).animate().translationY(((BaseActivity)getActivity()).mToolbar.getTop()).setInterpolator(new AccelerateInterpolator()).start();
down = false;
}*///todo For future implementation instead of scrollFlags
if (recyclerView.getScrollState()
== RecyclerView.SCROLL_STATE_DRAGGING) {
diff += dy;
} else {
diff = 0;
}
if (fab != null) {
if (dy <= 0 && fab.getId() != 0 && SettingValues.fab) {
if (recyclerView.getScrollState()
!= RecyclerView.SCROLL_STATE_DRAGGING
|| diff < -fab.getHeight() * 2) {
fab.show();
}
} else {
fab.hide();
}
}
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
// switch (newState) {
// case RecyclerView.SCROLL_STATE_IDLE:
// ((Reddit)getActivity().getApplicationContext()).getImageLoader().resume();
// break;
// case RecyclerView.SCROLL_STATE_DRAGGING:
// ((Reddit)getActivity().getApplicationContext()).getImageLoader().resume();
// break;
// case RecyclerView.SCROLL_STATE_SETTLING:
// ((Reddit)getActivity().getApplicationContext()).getImageLoader().pause();
// break;
// }
super.onScrollStateChanged(recyclerView, newState);
//If the toolbar search is open, and the user scrolls in the Main view--close the search UI
if (getActivity() instanceof MainActivity
&& (SettingValues.subredditSearchMethod
== Constants.SUBREDDIT_SEARCH_METHOD_TOOLBAR
|| SettingValues.subredditSearchMethod
== Constants.SUBREDDIT_SEARCH_METHOD_BOTH)
&& ((MainActivity) getContext()).findViewById(
R.id.toolbar_search).getVisibility() == View.VISIBLE) {
((MainActivity) getContext()).findViewById(
R.id.close_search_toolbar).performClick();
}
}
};
rv.addOnScrollListener(toolbarScroll);
} else {
toolbarScroll.reset = true;
}
}
public static void currentPosition(int adapterPosition) {
currentPosition = adapterPosition;
}
public static void currentSubmission(Submission current) {
currentSubmission = current;
}
} | gpl-3.0 |
waikato-datamining/adams-base | adams-core/src/main/java/adams/gui/visualization/core/plot/HitDetectorSupporter.java | 1208 | /*
* 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/>.
*/
/*
* HitDetectorSupporter.java
* Copyright (C) 2012-2017 University of Waikato, Hamilton, New Zealand
*/
package adams.gui.visualization.core.plot;
/**
* Interface for classes that use hit detectors.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @param <T> the type of hit detector to use
*/
public interface HitDetectorSupporter<T extends HitDetector> {
/**
* Returns the hit detector to use for this paintlet.
*
* @return the detector
*/
public T getHitDetector();
}
| gpl-3.0 |
wallet77/tinydailytaskmanager | serverSide/resources/RootGroup.php | 960 | <?php
use Tonic\Resource,
Tonic\Response,
Tonic\ConditionException;
/**
* This resource handles root group access
* @uri /project/:projectid/root
*/
class RootGroup extends Resource
{
/**
* Retrieve a root group
*
*
* @method GET
* @accepts application/json
* @provides application/json
* @json
* @return Response
*/
public function getRootGroup($projectid)
{
/* @var $service GroupService */
$service = $GLOBALS["TDTM"]["container"]["serviceGroup"];
$group = $service->getRootGroup($projectid);
if($group["group"] === null) {
return new Response(Response::IMATEAPOT, json_encode(array("code" => "noRootGroup", "msg" => $group["error"])), array('content-type' => 'application/json'));
}
return new Response(Response::OK, ToJsonConverter::convertGroupBean($group["group"]), array('content-type' => 'application/json'));
}
} | gpl-3.0 |
schleuder/schleuder3 | lib/schleuder/errors/too_many_keys.rb | 209 | module Schleuder
module Errors
class TooManyKeys < Base
def initialize(listdir, listname)
super t('errors.too_many_keys', listdir: listdir, listname: listname)
end
end
end
end
| gpl-3.0 |
nt001-01/Practicas | Clinic/src/main/java/com/unsis/clinic/service/PrescriptionServiceImpl.java | 697 | package com.unsis.clinic.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.unsis.clinic.dao.PrescriptionDao;
import com.unsis.clinic.model.Prescription;
public class PrescriptionServiceImpl implements PrescriptionService{
@Autowired
private PrescriptionDao prescriptionDao;
@Override
public void insertPrescription(Prescription prescription) {
prescriptionDao.insertPrescription(prescription);
}
@Override
public List<Prescription> getAllPrescription() {
return prescriptionDao.getAllPrescription();
}
@Override
public Prescription getPrescriptionById(int id) {
return prescriptionDao.getPrescriptionById(id);
}
}
| gpl-3.0 |
LinearSoft/entrust-cli | src/Commands/PermCreate.php | 1488 | <?php
/**
* Created by PhpStorm.
* User: meej
* Date: 6/1/2016
* Time: 8:00 PM
*/
namespace LinearSoft\EntrustCli\Commands;
use LinearSoft\EntrustCli\Models\Permission;
class PermCreate extends BaseCommand
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'entrust-cli:permission:create
{name : Name of the permission}
{display_name? : Display name of the permission}
{description? : Description of the permission}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create an Entrust permission';
/**
* Create a new command instance.
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$name = $this->argument('name');
$perm = $this->loadPerm($name,true);
if($perm != null) return;
$displayName = $this->argument('display_name');
$description = $this->argument('description');
Permission::create([
Permission::PROPERTY_NAME => $name,
Permission::PROPERTY_DISPLAY => $displayName,
Permission::PROPERTY_DESC => $description
]);
$this->info("Successfully created the permission '$name'.");
}
} | gpl-3.0 |
gohdan/DFC | known_files/hashes/bitrix/wizards/bitrix/demo/modules/form_feedback/data/form.php | 61 | Bitrix 16.5 Business Demo = 4597e62a0bd305ea73a7556a347a329c
| gpl-3.0 |
cams7/erp | freedom-fw1/src/main/java/org/freedom/library/swing/component/JRadioGroup.java | 7243 | /**
* @version 23/01/2003 <BR>
* @author Setpoint Informática Ltda./Fernando Oliveira da Silva <BR>
*
* Projeto: Freedom <BR>
* Pacote: org.freedom.componentes <BR>
* Classe:
* @(#)JMenuItemPad.java <BR>
*
* Este arquivo é parte do sistema Freedom-ERP, o Freedom-ERP é um software livre; você pode redistribui-lo e/ou <BR>
* modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Fundação do Software Livre (FSF); <BR>
* na versão 2 da Licença, ou (na sua opnião) qualquer versão. <BR>
* Este programa é distribuido na esperança que possa ser util, mas SEM NENHUMA GARANTIA; <BR>
* sem uma garantia implicita de ADEQUAÇÂO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. <BR>
* Veja a Licença Pública Geral GNU para maiores detalhes. <BR>
* Você deve ter recebido uma cópia da Licença Pública Geral GNU junto com este programa, se não, <BR>
* de acordo com os termos da LPG-PC <BR>
* <BR>
*
* Comentários da classe.....
*/
package org.freedom.library.swing.component;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.Border;
import org.freedom.acao.DefaultRadioGroupListener;
import org.freedom.acao.RadioGroupEvent;
import org.freedom.acao.RadioGroupListener;
import org.freedom.library.persistence.ListaCampos;
public class JRadioGroup<S, T> extends JPanel implements ActionListener, KeyListener {
private static final long serialVersionUID = 1L;
public static final int TP_NONE = -1;
public static final int TP_STRING = 0;
public static final int TP_INTEGER = 4;
public static final int TP_BOOLEAN = 10;
private ButtonGroup bg = new ButtonGroup();
private Object oVals[] = null;
private Object oLabs[] = null;
private RadioGroupListener rgLis = new DefaultRadioGroupListener();
private ListaCampos lcRadio = null;
public int Tipo = -1;
private Border borda = null;
public JRadioGroup(int Lin, int Col, Vector<S> labs, Vector<T> vals) {
this(Lin, Col, labs.toArray(), vals.toArray());
}
public JRadioGroup(int Lin, int Col, Vector<S> labs, Vector<T> vals, int margin_top) {
this(Lin, Col, labs.toArray(), vals.toArray(), margin_top);
}
public Border getBorda() {
return borda;
}
public void setBorda(Border borda) {
this.borda = borda;
mudaBorda();
}
public void mudaBorda() {
setBorder(borda);
}
public JRadioGroup(int Lin, int Col, Object oLabs[], Object oVals[]) {
this(Lin, Col, oLabs, oVals, 0);
}
public JRadioGroup(int Lin, int Col, Object oLabs[], Object oVals[], int margin_top) {
setLayout(new GridLayout(Lin, Col));
borda = BorderFactory.createEtchedBorder();
setBorder(borda);
this.oVals = oVals;
this.oLabs = oLabs;
addKeyListener(this);
for (int i = 0; i < oVals.length; i++) {
JRadioButton rg = new JRadioButton(( String ) oLabs[i]);
rg.setMnemonic(i);
rg.addActionListener(this);
rg.addKeyListener(this);
JPanel pnCenter = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, margin_top));
pnCenter.add(rg);
add(pnCenter);
bg.add(rg);
rg.addKeyListener(this);
rg.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
JRadioButton radio = ( ( JRadioButton ) ( ( JPanel ) getComponent(0) ).getComponent(0) );
radio.setSelected(true);
setTipo();
}
public void setFont(Font fonte) {
try {
AbstractButton rbTmp = null;
if(bg!=null){
for (Enumeration<AbstractButton> e = bg.getElements(); e.hasMoreElements();) {
rbTmp = e.nextElement();
if (rbTmp != null) {
rbTmp.setFont(fonte);
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public void novo() {
JRadioButton radio = ( ( JRadioButton ) ( ( JPanel ) getComponent(0) ).getComponent(0) );
radio.setSelected(true);
fireValorAlterado(radio, 0);
}
private void setTipo() {
if (oVals[0] instanceof Integer)
Tipo = TP_INTEGER;
else if (oVals[0] instanceof String)
Tipo = TP_STRING;
else if (oVals[0] instanceof Boolean)
Tipo = TP_BOOLEAN;
}
public int getTipo() {
return Tipo;
}
public String getVlrString() {
return ( String ) oVals[bg.getSelection().getMnemonic()];
}
public Integer getVlrInteger() {
return ( Integer ) oVals[bg.getSelection().getMnemonic()];
}
public Boolean getVlrBoolean() {
return ( Boolean ) oVals[bg.getSelection().getMnemonic()];
}
public void setVlrString(String val) {
for (int i = 0; i < oVals.length; i++) {
if (val.compareTo(( String ) oVals[i]) == 0) {
( ( JRadioButton ) ( ( JPanel ) getComponent(i) ).getComponent(0) ).setSelected(true);
fireValorAlterado(( ( JRadioButton ) ( ( JPanel ) getComponent(i) ).getComponent(0) ), i);
break;
}
}
}
public void setVlrInteger(Integer val) {
for (int i = 0; i < oVals.length; i++) {
if (val == ( Integer ) oVals[i]) {
( ( JRadioButton ) ( ( JPanel ) getComponent(i) ).getComponent(0) ).setSelected(true);
fireValorAlterado(( ( JRadioButton ) ( ( JPanel ) getComponent(i) ).getComponent(0) ), i);
break;
}
}
}
public void setVlrBoolean(Boolean val) {
for (int i = 0; i < oVals.length; i++) {
if (val == ( Boolean ) oVals[i]) {
( ( JRadioButton ) ( ( JPanel ) getComponent(i) ).getComponent(0) ).setSelected(true);
fireValorAlterado(( ( JRadioButton ) ( ( JPanel ) getComponent(i) ).getComponent(0) ), i);
break;
}
}
}
public void actionPerformed(ActionEvent evt) {
for (int i = 0; i < oLabs.length; i++) {
if (evt.getActionCommand() == ( String ) oLabs[i]) {
if (lcRadio != null) {
lcRadio.edit();
}
fireValorAlterado(( ( JRadioButton ) ( ( JPanel ) getComponent(i) ).getComponent(0) ), i);
}
}
}
public void setAtivo(boolean bAtiva) {
AbstractButton rbTmp = null;
for (Enumeration<AbstractButton> e = bg.getElements(); e.hasMoreElements();) {
rbTmp = e.nextElement();
if (rbTmp != null)
rbTmp.setEnabled(bAtiva);
}
}
public void setAtivo(int ind, boolean ativ) {
( ( JRadioButton ) ( ( JPanel ) getComponent(ind) ).getComponent(0) ).setEnabled(ativ);
}
public void keyPressed(KeyEvent kevt) {
if (kevt.getKeyCode() == KeyEvent.VK_ENTER) {
transferFocus();
}
}
public void keyTyped(KeyEvent kevt) {
}
public void keyReleased(KeyEvent kevt) {
}
public void setListaCampos(ListaCampos lc) {
lcRadio = lc;
}
public void addRadioGroupListener(RadioGroupListener cl) {
rgLis = cl;
}
public void addKeyListener(KeyListener klis) {
// for (int i=0; i<valores.size(); i++) {
// Funcoes.mensagemInforma(null,"I: "+i);
// ((JRadioButton)((JPanel)getComponent(i)).getComponent(0)).addKeyListener(klis);
// }
super.addKeyListener(klis);
}
private void fireValorAlterado(JRadioButton rb, int ind) {
rgLis.valorAlterado(new RadioGroupEvent(rb, ind, this));
}
}
| gpl-3.0 |
meisamhe/GPLshared | Programming/MPI — AMath 483 583, Spring 2013 1.0 documentation_files/DeletionList.java | 511 | // @author Andrey Pavlov
public class DeletionList {
// @include
// Assumes nodeToDelete is not tail.
public static void deletionFromList(ListNode<Integer> nodeToDelete) {
nodeToDelete.data = nodeToDelete.next.data;
nodeToDelete.next = nodeToDelete.next.next;
}
// @exclude
public static void main(String[] args) {
ListNode<Integer> L
= new ListNode<>(1, new ListNode<>(2, new ListNode<>(3, null)));
deletionFromList(L);
assert(L.data == 2 && L.next.data == 3);
}
}
| gpl-3.0 |
lsuits/OBSOLETE--DO-NOT-USE--gradebook_moodle | grade/report/grader/index.php | 6455 | <?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/>.
/**
* The gradebook grader report
*
* @package gradereport_grader
* @copyright 2007 Moodle Pty Ltd (http://moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once '../../../config.php';
require_once $CFG->libdir.'/gradelib.php';
require_once $CFG->dirroot.'/grade/lib.php';
require_once $CFG->dirroot.'/grade/report/grader/lib.php';
$courseid = required_param('id', PARAM_INT); // course id
$page = optional_param('page', 0, PARAM_INT); // active page
$edit = optional_param('edit', -1, PARAM_BOOL); // sticky editting mode
$sortitemid = optional_param('sortitemid', 0, PARAM_ALPHANUM); // sort by which grade item
$action = optional_param('action', 0, PARAM_ALPHAEXT);
$move = optional_param('move', 0, PARAM_INT);
$type = optional_param('type', 0, PARAM_ALPHA);
$target = optional_param('target', 0, PARAM_ALPHANUM);
$toggle = optional_param('toggle', NULL, PARAM_INT);
$toggle_type = optional_param('toggle_type', 0, PARAM_ALPHANUM);
$PAGE->set_url(new moodle_url('/grade/report/grader/index.php', array('id'=>$courseid)));
/// basic access checks
if (!$course = $DB->get_record('course', array('id' => $courseid))) {
print_error('nocourseid');
}
require_login($course);
$context = get_context_instance(CONTEXT_COURSE, $course->id);
require_capability('gradereport/grader:view', $context);
require_capability('moodle/grade:viewall', $context);
/// return tracking object
$gpr = new grade_plugin_return(array('type'=>'report', 'plugin'=>'grader', 'courseid'=>$courseid, 'page'=>$page));
/// last selected report session tracking
if (!isset($USER->grade_last_report)) {
$USER->grade_last_report = array();
}
$USER->grade_last_report[$course->id] = 'grader';
/// Build editing on/off buttons
if (!isset($USER->gradeediting)) {
$USER->gradeediting = array();
}
if (has_capability('moodle/grade:edit', $context)) {
if (!isset($USER->gradeediting[$course->id])) {
$USER->gradeediting[$course->id] = 0;
}
if (($edit == 1) and confirm_sesskey()) {
$USER->gradeediting[$course->id] = 1;
} else if (($edit == 0) and confirm_sesskey()) {
$USER->gradeediting[$course->id] = 0;
}
// page params for the turn editting on
$options = $gpr->get_options();
$options['sesskey'] = sesskey();
if ($USER->gradeediting[$course->id]) {
$options['edit'] = 0;
$string = get_string('turneditingoff');
} else {
$options['edit'] = 1;
$string = get_string('turneditingon');
}
$buttons = new single_button(new moodle_url('index.php', $options), $string, 'get');
} else {
$USER->gradeediting[$course->id] = 0;
$buttons = '';
}
$gradeserror = array();
// Handle toggle change request
if (!is_null($toggle) && !empty($toggle_type)) {
set_user_preferences(array('grade_report_show'.$toggle_type => $toggle));
}
//first make sure we have proper final grades - this must be done before constructing of the grade tree
grade_regrade_final_grades($courseid);
// Perform actions
if (!empty($target) && !empty($action) && confirm_sesskey()) {
grade_report_grader::process_action($target, $action);
}
$reportname = get_string('pluginname', 'gradereport_grader');
/// Print header
print_grade_page_head($COURSE->id, 'report', 'grader', $reportname, false, $buttons);
//Initialise the grader report object that produces the table
//the class grade_report_grader_ajax was removed as part of MDL-21562
$report = new grade_report_grader($courseid, $gpr, $context, $page, $sortitemid);
// make sure separate group does not prevent view
if ($report->currentgroup == -2) {
echo $OUTPUT->heading(get_string("notingroup"));
echo $OUTPUT->footer();
exit;
}
/// processing posted grades & feedback here
if ($data = data_submitted() and confirm_sesskey() and has_capability('moodle/grade:edit', $context)) {
$warnings = $report->process_data($data);
} else {
$warnings = array();
}
// final grades MUST be loaded after the processing
$report->load_users();
$numusers = $report->get_numusers();
$report->load_final_grades();
echo $report->group_selector;
echo $report->get_first_initial_bar();
echo $report->get_last_initial_bar();
echo '<div class="clearer"></div>';
// echo $report->get_toggles_html();
//show warnings if any
foreach($warnings as $warning) {
echo $OUTPUT->notification($warning);
}
$studentsperpage = $report->get_students_per_page();
// Don't use paging if studentsperpage is empty or 0 at course AND site levels
if (!empty($studentsperpage)) {
echo $OUTPUT->paging_bar($numusers, $report->page, $studentsperpage, $report->pbarurl);
}
$reporthtml = $report->get_grade_table();
// print submit button
if ($USER->gradeediting[$course->id] && ($report->get_pref('showquickfeedback') || $report->get_pref('quickgrading'))) {
echo '<form action="index.php" method="post">';
echo '<div>';
echo '<div class="submit"><input type="submit" value="'.s(get_string('update')).'" /></div>';
echo '<input type="hidden" value="'.s($courseid).'" name="id" />';
echo '<input type="hidden" value="'.sesskey().'" name="sesskey" />';
echo '<input type="hidden" value="grader" name="report"/>';
echo '<input type="hidden" value="'.$page.'" name="page"/>';
echo $reporthtml;
echo '<div class="submit"><input type="submit" id="gradersubmit" value="'.s(get_string('update')).'" /></div>';
echo '</div></form>';
} else {
echo $reporthtml;
}
// prints paging bar at bottom for large pages
if (!empty($studentsperpage) && $studentsperpage >= 20) {
echo $OUTPUT->paging_bar($numusers, $report->page, $studentsperpage, $report->pbarurl);
}
echo $OUTPUT->footer();
| gpl-3.0 |
Chrogeek/chrogeek-noi | BZOJ 2811 [Apio2012]Guard/bzoj2811.cpp | 2243 | #include <cstdio>
#include <algorithm>
using namespace std;
struct interval
{
int l, r;
bool operator<(const interval &b) const
{
if (l == b.l)
return r < b.r;
return l < b.l;
}
};
const int inf = 999999999;
const int maxn = 100005;
int n, k, m;
interval ints[maxn], outs[maxn];
int tot, to2;
int cnt[maxn];
int pl[maxn], pr[maxn], id[maxn], num;
int f[maxn], g[maxn];
int ql[maxn], qr[maxn], top;
int main()
{
scanf("%d%d%d", &n, &k, &m);
for (int i = 1; i <= m; i++)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
if (c)
ints[++tot] = (interval){a, b};
else
cnt[a]++, cnt[b + 1]--;
}
for (int i = 1, t = 0; i <= n; i++)
{
t += cnt[i];
if (!t)
pl[i] = pr[i] = ++num, id[num] = i;
}
if (num == k)
{
for (int i = 1; i <= num; i++)
printf("%d\n", id[i]);
return 0;
}
for (int i = 1; i <= n; i++)
if (!pr[i])
pr[i] = pr[i - 1];
pl[n + 1] = inf;
for (int i = n; i >= 1; i--)
if (!pl[i])
pl[i] = pl[i + 1];
for (int i = 1; i <= tot; i++)
{
int l = ints[i].l, r = ints[i].r;
l = pl[l], r = pr[r];
if (l > r)
continue;
outs[++to2] = (interval){l, r};
}
sort(outs + 1, outs + to2 + 1);
for (int i = 1; i <= to2; i++)
{
while (top != 0 && outs[i].l >= ql[top] && outs[i].r <= qr[top])
top--;
top++;
ql[top] = outs[i].l;
qr[top] = outs[i].r;
}
int mx = 0, mn = inf;
for (int i = 1; i <= top; i++)
if (ql[i] > mx)
f[i] = f[i - 1] + 1, mx = qr[i];
else
f[i] = f[i - 1];
for (int i = top; i; i--)
if (qr[i] < mn)
g[i] = g[i + 1] + 1, mn = ql[i];
else
g[i] = g[i + 1];
bool flag = false;
for (int i = 1; i <= top; i++)
{
if (f[i] != f[i - 1] + 1)
continue;
if (ql[i] == qr[i])
{
flag = true;
printf("%d\n", id[ql[i]]);
}
else
{
int x = qr[i] - 1, t1 = 0, t2 = top + 1;
int l = 1, r = i - 1;
while (l <= r)
{
int mid = (l + r) >> 1;
if (qr[mid] < x)
t1 = mid, l = mid + 1;
else
r = mid - 1;
}
l = i + 1, r = top;
while (l <= r)
{
int mid = (l + r) >> 1;
if (ql[mid] > x)
t2 = mid, r = mid - 1;
else
l = mid + 1;
}
if (f[t1] + g[t2] + 1 > k)
{
flag = true;
printf("%d\n", id[qr[i]]);
}
}
}
if (!flag)
printf("-1\n");
return 0;
}
| gpl-3.0 |
intoxicatedpenguin/DiscordGUI | src/main/bot/commands/Command.java | 262 | package main.bot.commands;
import main.bot.commands.CommandInterpret.CommandContainer;
/**
* Created by Adair on 03/16/17.
*/
public interface Command {
boolean safe(CommandContainer info);
void action(CommandContainer info);
String help();
}
| gpl-3.0 |
WilderPereira/Reciclo | app/src/main/java/com/wilderpereira/reciclo/fragments/ListFragment.java | 5313 | package com.wilderpereira.reciclo.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.mopub.nativeads.MoPubRecyclerAdapter;
import com.mopub.nativeads.MoPubStaticNativeAdRenderer;
import com.mopub.nativeads.RequestParameters;
import com.mopub.nativeads.ViewBinder;
import com.wilderpereira.reciclo.R;
import com.wilderpereira.reciclo.adapters.RecipesAdapter;
import com.wilderpereira.reciclo.models.Recipe;
import com.wilderpereira.reciclo.models.StockItem;
import com.wilderpereira.reciclo.utils.FirebaseUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Wilder on 10/07/16.
*/
public abstract class ListFragment extends Fragment {
private RecyclerView mRecyclerView;
private DatabaseReference mDatabase;
private RecipesAdapter adapter;
private MoPubRecyclerAdapter myMoPubAdapter;
List<StockItem> stock = new ArrayList<>();
String TAG = getResources().getString(R.string.ListFragment);
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.recycle_fragment, container, false);
mDatabase = FirebaseUtils.getDatabase().getReference();
final List<Recipe> recipes = new ArrayList<>();
loadItens();
Query recipesQuery = getQuery(mDatabase);
adapter = new RecipesAdapter(recipes, recipesQuery);
myMoPubAdapter = new MoPubRecyclerAdapter(getActivity(), adapter);
// Create an ad renderer and view binder that describe your native ad layout.
ViewBinder myViewBinder = new ViewBinder.Builder(R.layout.ad_item)
.titleId(R.id.tv_ad_title)
.textId(R.id.tv_ad_description)
.mainImageId(R.id.iv_ad_main_image)
.iconImageId(R.id.iv_ad_icon)
.callToActionId(R.id.btn_ad_call_to_action)
.build();
MoPubStaticNativeAdRenderer myRenderer = new MoPubStaticNativeAdRenderer(myViewBinder);
myMoPubAdapter.registerAdRenderer(myRenderer);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler);
mRecyclerView.setAdapter(myMoPubAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recipesQuery.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
recipes.clear();
Log.d(TAG, getResources().getString(R.string.onDataChange));
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
Recipe item = postSnapshot.getValue(Recipe.class);
item.setUid(postSnapshot.getKey());
Log.d(TAG, item.getName()+ getResources().getString(R.string.canbemade) +item.canBeMade(stock));
if(!shouldCheckStock() || item.canBeMade(stock)) {
recipes.add(item);
}
}
adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, getResources().getString(R.string.onCancelled));
}
});
return view;
}
@Override
public void onResume() {
// Optional targeting parameters
RequestParameters parameters = new RequestParameters.Builder()
.keywords(getResources().getString(R.string.recycling_nature))
.build();
myMoPubAdapter.loadAds(getResources().getString(R.string.ad_code), parameters);
super.onResume();
}
public abstract Query getQuery(DatabaseReference databaseReference);
public abstract boolean shouldCheckStock();
public void loadItens(){
DatabaseReference databaseReference = FirebaseUtils.getDatabase().getReference().child(getResources().getString(R.string.stocks)+FirebaseUtils.UID+getResources().getString(R.string.itens));
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
stock.clear();
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
StockItem item = postSnapshot.getValue(StockItem.class);
stock.add(item);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onDestroy() {
myMoPubAdapter.destroy();
super.onDestroy();
}
}
| gpl-3.0 |
wiki2014/Learning-Summary | alps/cts/tests/tests/view/src/android/view/cts/ViewTestCtsActivity.java | 2391 | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.view.cts;
import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.cts.R;
public class ViewTestCtsActivity extends Activity {
private boolean mHasWindowFocus = false;
private Object mHasWindowFocusLock = new Object();
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.view_layout);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (!hasFocus) {
Log.w("ViewTestCtsActivity", "ViewTestCtsActivity lost window focus");
}
synchronized(mHasWindowFocusLock) {
mHasWindowFocus = hasFocus;
mHasWindowFocusLock.notify();
}
}
/**
* Blocks the calling thread until the {@link ViewTestCtsActivity} has window focus or the
* specified duration (in milliseconds) has passed.
*/
public boolean waitForWindowFocus(long durationMillis) {
long elapsedMillis = SystemClock.elapsedRealtime();
synchronized(mHasWindowFocusLock) {
mHasWindowFocus = hasWindowFocus();
while (!mHasWindowFocus && durationMillis > 0) {
long newElapsedMillis = SystemClock.elapsedRealtime();
durationMillis -= (newElapsedMillis - elapsedMillis);
elapsedMillis = newElapsedMillis;
if (durationMillis > 0) {
try {
mHasWindowFocusLock.wait(durationMillis);
} catch (InterruptedException e) {
}
}
}
return mHasWindowFocus;
}
}
}
| gpl-3.0 |
CeutecIngDeSoftware/PropuestasInformatica | app/helpers/requests_closures_helper.rb | 34 | module RequestsClosuresHelper
end
| gpl-3.0 |
matriphe/laravel-linfo | tests/TestCase.php | 733 | <?php
use Linfo\Laravel\LinfoServiceProvider;
use Linfo\Laravel\Models\Linfo as LinfoModel;
use Orchestra\Testbench\TestCase as OrchestraTestCase;
abstract class TestCase extends OrchestraTestCase
{
/**
* @param \Illuminate\Foundation\Application $app
* @return array
*/
protected function getPackageProviders($app)
{
return [
LinfoServiceProvider::class,
];
}
/**
* Get application timezone.
*
* @param \Illuminate\Foundation\Application $app
* @return string
*/
protected function getApplicationTimezone($app)
{
return 'UTC';
}
protected function getModelInstance()
{
return new LinfoModel();
}
}
| gpl-3.0 |
niklasf/jumpnevolve | src/com/googlecode/jumpnevolve/graphics/gui/objects/InterfaceCheckbox.java | 1998 | package com.googlecode.jumpnevolve.graphics.gui.objects;
import java.util.ArrayList;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import com.googlecode.jumpnevolve.graphics.GraphicUtils;
import com.googlecode.jumpnevolve.graphics.gui.ContentListener;
import com.googlecode.jumpnevolve.graphics.gui.Contentable;
import com.googlecode.jumpnevolve.graphics.gui.InterfaceFunction;
import com.googlecode.jumpnevolve.math.Rectangle;
import com.googlecode.jumpnevolve.math.Vector;
import com.googlecode.jumpnevolve.util.Parameter;
public class InterfaceCheckbox extends InterfaceObject implements Contentable {
private static final float SIZE = Parameter.GUI_CHECKBOX_SIZE;
private boolean value = false;
private Rectangle shape = new Rectangle(Vector.ZERO, SIZE, SIZE);
private ArrayList<ContentListener> listener = new ArrayList<ContentListener>();
public InterfaceCheckbox(InterfaceFunction function, boolean startValue) {
super(function);
this.value = startValue;
}
public InterfaceCheckbox(InterfaceFunction function, int key,
boolean startValue) {
super(function, key);
this.value = startValue;
}
@Override
public Rectangle getNeededSize() {
return this.shape;
}
@Override
public void draw(Graphics g) {
if (this.value) {
GraphicUtils.fill(g,
this.shape.modifyCenter(this.getCenterVector()));
} else {
GraphicUtils.draw(g,
this.shape.modifyCenter(this.getCenterVector()));
}
}
@Override
public void poll(Input input, float secounds) {
super.poll(input, secounds);
if (this.getStatus() == STATUS_PRESSED) {
this.value = !this.value;
for (ContentListener cL : this.listener) {
cL.contentChanged(this);
}
}
}
@Override
public String getContent() {
return "" + this.value;
}
@Override
public void setContent(String newContent) {
this.value = Boolean.parseBoolean(newContent);
}
@Override
public void addContentListener(ContentListener listener) {
this.listener.add(listener);
}
}
| gpl-3.0 |
revelator/MHDoom | neo/libs/jpeg9a/jquant2.cpp | 48791 | /*
* jquant2.c
*
* Copyright (C) 1991-1996, Thomas G. Lane.
* Modified 2011 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains 2-pass color quantization (color mapping) routines.
* These routines provide selection of a custom color map for an image,
* followed by mapping of the image to that color map, with optional
* Floyd-Steinberg dithering.
* It is also possible to use just the second pass to map to an arbitrary
* externally-given color map.
*
* Note: ordered dithering is not supported, since there isn't any fast
* way to compute intercolor distances; it's unclear that ordered dither's
* fundamental assumptions even hold with an irregularly spaced color map.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
#ifdef QUANT_2PASS_SUPPORTED
/*
* This module implements the well-known Heckbert paradigm for color
* quantization. Most of the ideas used here can be traced back to
* Heckbert's seminal paper
* Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
* Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
*
* In the first pass over the image, we accumulate a histogram showing the
* usage count of each possible color. To keep the histogram to a reasonable
* size, we reduce the precision of the input; typical practice is to retain
* 5 or 6 bits per color, so that 8 or 4 different input values are counted
* in the same histogram cell.
*
* Next, the color-selection step begins with a box representing the whole
* color space, and repeatedly splits the "largest" remaining box until we
* have as many boxes as desired colors. Then the mean color in each
* remaining box becomes one of the possible output colors.
*
* The second pass over the image maps each input pixel to the closest output
* color (optionally after applying a Floyd-Steinberg dithering correction).
* This mapping is logically trivial, but making it go fast enough requires
* considerable care.
*
* Heckbert-style quantizers vary a good deal in their policies for choosing
* the "largest" box and deciding where to cut it. The particular policies
* used here have proved out well in experimental comparisons, but better ones
* may yet be found.
*
* In earlier versions of the IJG code, this module quantized in YCbCr color
* space, processing the raw upsampled data without a color conversion step.
* This allowed the color conversion math to be done only once per colormap
* entry, not once per pixel. However, that optimization precluded other
* useful optimizations (such as merging color conversion with upsampling)
* and it also interfered with desired capabilities such as quantizing to an
* externally-supplied colormap. We have therefore abandoned that approach.
* The present code works in the post-conversion color space, typically RGB.
*
* To improve the visual quality of the results, we actually work in scaled
* RGB space, giving G distances more weight than R, and R in turn more than
* B. To do everything in integer math, we must use integer scale factors.
* The 2/3/1 scale factors used here correspond loosely to the relative
* weights of the colors in the NTSC grayscale equation.
* If you want to use this code to quantize a non-RGB color space, you'll
* probably need to change these scale factors.
*/
#define R_SCALE 2 /* scale R distances by this much */
#define G_SCALE 3 /* scale G distances by this much */
#define B_SCALE 1 /* and B by this much */
/* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
* in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
* and B,G,R orders. If you define some other weird order in jmorecfg.h,
* you'll get compile errors until you extend this logic. In that case
* you'll probably want to tweak the histogram sizes too.
*/
#if RGB_RED == 0
#define C0_SCALE R_SCALE
#endif
#if RGB_BLUE == 0
#define C0_SCALE B_SCALE
#endif
#if RGB_GREEN == 1
#define C1_SCALE G_SCALE
#endif
#if RGB_RED == 2
#define C2_SCALE R_SCALE
#endif
#if RGB_BLUE == 2
#define C2_SCALE B_SCALE
#endif
/*
* First we have the histogram data structure and routines for creating it.
*
* The number of bits of precision can be adjusted by changing these symbols.
* We recommend keeping 6 bits for G and 5 each for R and B.
* If you have plenty of memory and cycles, 6 bits all around gives marginally
* better results; if you are short of memory, 5 bits all around will save
* some space but degrade the results.
* To maintain a fully accurate histogram, we'd need to allocate a "long"
* (preferably unsigned long) for each cell. In practice this is overkill;
* we can get by with 16 bits per cell. Few of the cell counts will overflow,
* and clamping those that do overflow to the maximum value will give close-
* enough results. This reduces the recommended histogram size from 256Kb
* to 128Kb, which is a useful savings on PC-class machines.
* (In the second pass the histogram space is re-used for pixel mapping data;
* in that capacity, each cell must be able to store zero to the number of
* desired colors. 16 bits/cell is plenty for that too.)
* Since the JPEG code is intended to run in small memory model on 80x86
* machines, we can't just allocate the histogram in one chunk. Instead
* of a true 3-D array, we use a row of pointers to 2-D arrays. Each
* pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
* each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
* on 80x86 machines, the pointer row is in near memory but the actual
* arrays are in far memory (same arrangement as we use for image arrays).
*/
#define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
/* These will do the right thing for either R,G,B or B,G,R color order,
* but you may not like the results for other color orders.
*/
#define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
#define HIST_C1_BITS 6 /* bits of precision in G histogram */
#define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
/* Number of elements along histogram axes. */
#define HIST_C0_ELEMS (1<<HIST_C0_BITS)
#define HIST_C1_ELEMS (1<<HIST_C1_BITS)
#define HIST_C2_ELEMS (1<<HIST_C2_BITS)
/* These are the amounts to shift an input value to get a histogram index. */
#define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
#define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
#define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
typedef histcell FAR *histptr; /* for pointers to histogram cells */
typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
typedef hist1d FAR *hist2d; /* type for the 2nd-level pointers */
typedef hist2d *hist3d; /* type for top-level pointer */
/* Declarations for Floyd-Steinberg dithering.
*
* Errors are accumulated into the array fserrors[], at a resolution of
* 1/16th of a pixel count. The error at a given pixel is propagated
* to its not-yet-processed neighbors using the standard F-S fractions,
* ... (here) 7/16
* 3/16 5/16 1/16
* We work left-to-right on even rows, right-to-left on odd rows.
*
* We can get away with a single array (holding one row's worth of errors)
* by using it to store the current row's errors at pixel columns not yet
* processed, but the next row's errors at columns already processed. We
* need only a few extra variables to hold the errors immediately around the
* current column. (If we are lucky, those variables are in registers, but
* even if not, they're probably cheaper to access than array elements are.)
*
* The fserrors[] array has (#columns + 2) entries; the extra entry at
* each end saves us from special-casing the first and last pixels.
* Each entry is three values long, one value for each color component.
*
* Note: on a wide image, we might not have enough room in a PC's near data
* segment to hold the error array; so it is allocated with alloc_large.
*/
#if BITS_IN_JSAMPLE == 8
typedef INT16 FSERROR; /* 16 bits should be enough */
typedef int LOCFSERROR; /* use 'int' for calculation temps */
#else
typedef INT32 FSERROR; /* may need more than 16 bits */
typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
#endif
typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
/* Private subobject */
typedef struct
{
struct jpeg_color_quantizer pub; /* public fields */
/* Space for the eventually created colormap is stashed here */
JSAMPARRAY sv_colormap; /* colormap allocated at init time */
int desired; /* desired # of colors = size of colormap */
/* Variables for accumulating image statistics */
hist3d histogram; /* pointer to the histogram */
boolean needs_zeroed; /* TRUE if next pass must zero histogram */
/* Variables for Floyd-Steinberg dithering */
FSERRPTR fserrors; /* accumulated errors */
boolean on_odd_row; /* flag to remember which row we are on */
int *error_limiter; /* table for clamping the applied error */
} my_cquantizer;
typedef my_cquantizer *my_cquantize_ptr;
/*
* Prescan some rows of pixels.
* In this module the prescan simply updates the histogram, which has been
* initialized to zeroes by start_pass.
* An output_buf parameter is required by the method signature, but no data
* is actually output (in fact the buffer controller is probably passing a
* NULL pointer).
*/
METHODDEF( void )
prescan_quantize( j_decompress_ptr cinfo, JSAMPARRAY input_buf,
JSAMPARRAY output_buf, int num_rows )
{
my_cquantize_ptr cquantize = ( my_cquantize_ptr ) cinfo->cquantize;
register JSAMPROW ptr;
register histptr histp;
register hist3d histogram = cquantize->histogram;
int row;
JDIMENSION col;
JDIMENSION width = cinfo->output_width;
for( row = 0; row < num_rows; row++ )
{
ptr = input_buf[row];
for( col = width; col > 0; col-- )
{
/* get pixel value and index into the histogram */
histp = & histogram[GETJSAMPLE( ptr[0] ) >> C0_SHIFT]
[GETJSAMPLE( ptr[1] ) >> C1_SHIFT]
[GETJSAMPLE( ptr[2] ) >> C2_SHIFT];
/* increment, check for overflow and undo increment if so. */
if( ++( *histp ) <= 0 )
{
( *histp )--;
}
ptr += 3;
}
}
}
/*
* Next we have the really interesting routines: selection of a colormap
* given the completed histogram.
* These routines work with a list of "boxes", each representing a rectangular
* subset of the input color space (to histogram precision).
*/
typedef struct
{
/* The bounds of the box (inclusive); expressed as histogram indexes */
int c0min, c0max;
int c1min, c1max;
int c2min, c2max;
/* The volume (actually 2-norm) of the box */
INT32 volume;
/* The number of nonzero histogram cells within this box */
long colorcount;
} box;
typedef box *boxptr;
LOCAL( boxptr )
find_biggest_color_pop( boxptr boxlist, int numboxes )
/* Find the splittable box with the largest color population */
/* Returns NULL if no splittable boxes remain */
{
register boxptr boxp;
register int i;
register long maxc = 0;
boxptr which = NULL;
for( i = 0, boxp = boxlist; i < numboxes; i++, boxp++ )
{
if( boxp->colorcount > maxc && boxp->volume > 0 )
{
which = boxp;
maxc = boxp->colorcount;
}
}
return which;
}
LOCAL( boxptr )
find_biggest_volume( boxptr boxlist, int numboxes )
/* Find the splittable box with the largest (scaled) volume */
/* Returns NULL if no splittable boxes remain */
{
register boxptr boxp;
register int i;
register INT32 maxv = 0;
boxptr which = NULL;
for( i = 0, boxp = boxlist; i < numboxes; i++, boxp++ )
{
if( boxp->volume > maxv )
{
which = boxp;
maxv = boxp->volume;
}
}
return which;
}
LOCAL( void )
update_box( j_decompress_ptr cinfo, boxptr boxp )
/* Shrink the min/max bounds of a box to enclose only nonzero elements, */
/* and recompute its volume and population */
{
my_cquantize_ptr cquantize = ( my_cquantize_ptr ) cinfo->cquantize;
hist3d histogram = cquantize->histogram;
histptr histp;
int c0, c1, c2;
int c0min, c0max, c1min, c1max, c2min, c2max;
INT32 dist0, dist1, dist2;
long ccount;
c0min = boxp->c0min;
c0max = boxp->c0max;
c1min = boxp->c1min;
c1max = boxp->c1max;
c2min = boxp->c2min;
c2max = boxp->c2max;
if( c0max > c0min )
for( c0 = c0min; c0 <= c0max; c0++ )
for( c1 = c1min; c1 <= c1max; c1++ )
{
histp = & histogram[c0][c1][c2min];
for( c2 = c2min; c2 <= c2max; c2++ )
if( *histp++ != 0 )
{
boxp->c0min = c0min = c0;
goto have_c0min;
}
}
have_c0min:
if( c0max > c0min )
for( c0 = c0max; c0 >= c0min; c0-- )
for( c1 = c1min; c1 <= c1max; c1++ )
{
histp = & histogram[c0][c1][c2min];
for( c2 = c2min; c2 <= c2max; c2++ )
if( *histp++ != 0 )
{
boxp->c0max = c0max = c0;
goto have_c0max;
}
}
have_c0max:
if( c1max > c1min )
for( c1 = c1min; c1 <= c1max; c1++ )
for( c0 = c0min; c0 <= c0max; c0++ )
{
histp = & histogram[c0][c1][c2min];
for( c2 = c2min; c2 <= c2max; c2++ )
if( *histp++ != 0 )
{
boxp->c1min = c1min = c1;
goto have_c1min;
}
}
have_c1min:
if( c1max > c1min )
for( c1 = c1max; c1 >= c1min; c1-- )
for( c0 = c0min; c0 <= c0max; c0++ )
{
histp = & histogram[c0][c1][c2min];
for( c2 = c2min; c2 <= c2max; c2++ )
if( *histp++ != 0 )
{
boxp->c1max = c1max = c1;
goto have_c1max;
}
}
have_c1max:
if( c2max > c2min )
for( c2 = c2min; c2 <= c2max; c2++ )
for( c0 = c0min; c0 <= c0max; c0++ )
{
histp = & histogram[c0][c1min][c2];
for( c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS )
if( *histp != 0 )
{
boxp->c2min = c2min = c2;
goto have_c2min;
}
}
have_c2min:
if( c2max > c2min )
for( c2 = c2max; c2 >= c2min; c2-- )
for( c0 = c0min; c0 <= c0max; c0++ )
{
histp = & histogram[c0][c1min][c2];
for( c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS )
if( *histp != 0 )
{
boxp->c2max = c2max = c2;
goto have_c2max;
}
}
have_c2max:
/* Update box volume.
* We use 2-norm rather than real volume here; this biases the method
* against making long narrow boxes, and it has the side benefit that
* a box is splittable iff norm > 0.
* Since the differences are expressed in histogram-cell units,
* we have to shift back to JSAMPLE units to get consistent distances;
* after which, we scale according to the selected distance scale factors.
*/
dist0 = ( ( c0max - c0min ) << C0_SHIFT ) * C0_SCALE;
dist1 = ( ( c1max - c1min ) << C1_SHIFT ) * C1_SCALE;
dist2 = ( ( c2max - c2min ) << C2_SHIFT ) * C2_SCALE;
boxp->volume = dist0 * dist0 + dist1 * dist1 + dist2 * dist2;
/* Now scan remaining volume of box and compute population */
ccount = 0;
for( c0 = c0min; c0 <= c0max; c0++ )
for( c1 = c1min; c1 <= c1max; c1++ )
{
histp = & histogram[c0][c1][c2min];
for( c2 = c2min; c2 <= c2max; c2++, histp++ )
if( *histp != 0 )
{
ccount++;
}
}
boxp->colorcount = ccount;
}
LOCAL( int )
median_cut( j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
int desired_colors )
/* Repeatedly select and split the largest box until we have enough boxes */
{
int n, lb;
int c0, c1, c2, cmax;
register boxptr b1, b2;
while( numboxes < desired_colors )
{
/* Select box to split.
* Current algorithm: by population for first half, then by volume.
*/
if( numboxes * 2 <= desired_colors )
{
b1 = find_biggest_color_pop( boxlist, numboxes );
}
else
{
b1 = find_biggest_volume( boxlist, numboxes );
}
if( b1 == NULL ) /* no splittable boxes left! */
{
break;
}
b2 = &boxlist[numboxes]; /* where new box will go */
/* Copy the color bounds to the new box. */
b2->c0max = b1->c0max;
b2->c1max = b1->c1max;
b2->c2max = b1->c2max;
b2->c0min = b1->c0min;
b2->c1min = b1->c1min;
b2->c2min = b1->c2min;
/* Choose which axis to split the box on.
* Current algorithm: longest scaled axis.
* See notes in update_box about scaling distances.
*/
c0 = ( ( b1->c0max - b1->c0min ) << C0_SHIFT ) * C0_SCALE;
c1 = ( ( b1->c1max - b1->c1min ) << C1_SHIFT ) * C1_SCALE;
c2 = ( ( b1->c2max - b1->c2min ) << C2_SHIFT ) * C2_SCALE;
/* We want to break any ties in favor of green, then red, blue last.
* This code does the right thing for R,G,B or B,G,R color orders only.
*/
#if RGB_RED == 0
cmax = c1;
n = 1;
if( c0 > cmax )
{
cmax = c0;
n = 0;
}
if( c2 > cmax )
{
n = 2;
}
#else
cmax = c1;
n = 1;
if( c2 > cmax )
{
cmax = c2;
n = 2;
}
if( c0 > cmax )
{
n = 0;
}
#endif
/* Choose split point along selected axis, and update box bounds.
* Current algorithm: split at halfway point.
* (Since the box has been shrunk to minimum volume,
* any split will produce two nonempty subboxes.)
* Note that lb value is max for lower box, so must be < old max.
*/
switch( n )
{
case 0:
lb = ( b1->c0max + b1->c0min ) / 2;
b1->c0max = lb;
b2->c0min = lb + 1;
break;
case 1:
lb = ( b1->c1max + b1->c1min ) / 2;
b1->c1max = lb;
b2->c1min = lb + 1;
break;
case 2:
lb = ( b1->c2max + b1->c2min ) / 2;
b1->c2max = lb;
b2->c2min = lb + 1;
break;
}
/* Update stats for boxes */
update_box( cinfo, b1 );
update_box( cinfo, b2 );
numboxes++;
}
return numboxes;
}
LOCAL( void )
compute_color( j_decompress_ptr cinfo, boxptr boxp, int icolor )
/* Compute representative color for a box, put it in colormap[icolor] */
{
/* Current algorithm: mean weighted by pixels (not colors) */
/* Note it is important to get the rounding correct! */
my_cquantize_ptr cquantize = ( my_cquantize_ptr ) cinfo->cquantize;
hist3d histogram = cquantize->histogram;
histptr histp;
int c0, c1, c2;
int c0min, c0max, c1min, c1max, c2min, c2max;
long count;
long total = 0;
long c0total = 0;
long c1total = 0;
long c2total = 0;
c0min = boxp->c0min;
c0max = boxp->c0max;
c1min = boxp->c1min;
c1max = boxp->c1max;
c2min = boxp->c2min;
c2max = boxp->c2max;
for( c0 = c0min; c0 <= c0max; c0++ )
for( c1 = c1min; c1 <= c1max; c1++ )
{
histp = & histogram[c0][c1][c2min];
for( c2 = c2min; c2 <= c2max; c2++ )
{
if( ( count = *histp++ ) != 0 )
{
total += count;
c0total += ( ( c0 << C0_SHIFT ) + ( ( 1 << C0_SHIFT ) >> 1 ) ) * count;
c1total += ( ( c1 << C1_SHIFT ) + ( ( 1 << C1_SHIFT ) >> 1 ) ) * count;
c2total += ( ( c2 << C2_SHIFT ) + ( ( 1 << C2_SHIFT ) >> 1 ) ) * count;
}
}
}
cinfo->colormap[0][icolor] = ( JSAMPLE )( ( c0total + ( total >> 1 ) ) / total );
cinfo->colormap[1][icolor] = ( JSAMPLE )( ( c1total + ( total >> 1 ) ) / total );
cinfo->colormap[2][icolor] = ( JSAMPLE )( ( c2total + ( total >> 1 ) ) / total );
}
LOCAL( void )
select_colors( j_decompress_ptr cinfo, int desired_colors )
/* Master routine for color selection */
{
boxptr boxlist;
int numboxes;
int i;
/* Allocate workspace for box list */
boxlist = ( boxptr )( *cinfo->mem->alloc_small )
( ( j_common_ptr ) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF( box ) );
/* Initialize one box containing whole space */
numboxes = 1;
boxlist[0].c0min = 0;
boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
boxlist[0].c1min = 0;
boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
boxlist[0].c2min = 0;
boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
/* Shrink it to actually-used volume and set its statistics */
update_box( cinfo, & boxlist[0] );
/* Perform median-cut to produce final box list */
numboxes = median_cut( cinfo, boxlist, numboxes, desired_colors );
/* Compute the representative color for each box, fill colormap */
for( i = 0; i < numboxes; i++ )
{
compute_color( cinfo, & boxlist[i], i );
}
cinfo->actual_number_of_colors = numboxes;
TRACEMS1( cinfo, 1, JTRC_QUANT_SELECTED, numboxes );
}
/*
* These routines are concerned with the time-critical task of mapping input
* colors to the nearest color in the selected colormap.
*
* We re-use the histogram space as an "inverse color map", essentially a
* cache for the results of nearest-color searches. All colors within a
* histogram cell will be mapped to the same colormap entry, namely the one
* closest to the cell's center. This may not be quite the closest entry to
* the actual input color, but it's almost as good. A zero in the cache
* indicates we haven't found the nearest color for that cell yet; the array
* is cleared to zeroes before starting the mapping pass. When we find the
* nearest color for a cell, its colormap index plus one is recorded in the
* cache for future use. The pass2 scanning routines call fill_inverse_cmap
* when they need to use an unfilled entry in the cache.
*
* Our method of efficiently finding nearest colors is based on the "locally
* sorted search" idea described by Heckbert and on the incremental distance
* calculation described by Spencer W. Thomas in chapter III.1 of Graphics
* Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
* the distances from a given colormap entry to each cell of the histogram can
* be computed quickly using an incremental method: the differences between
* distances to adjacent cells themselves differ by a constant. This allows a
* fairly fast implementation of the "brute force" approach of computing the
* distance from every colormap entry to every histogram cell. Unfortunately,
* it needs a work array to hold the best-distance-so-far for each histogram
* cell (because the inner loop has to be over cells, not colormap entries).
* The work array elements have to be INT32s, so the work array would need
* 256Kb at our recommended precision. This is not feasible in DOS machines.
*
* To get around these problems, we apply Thomas' method to compute the
* nearest colors for only the cells within a small subbox of the histogram.
* The work array need be only as big as the subbox, so the memory usage
* problem is solved. Furthermore, we need not fill subboxes that are never
* referenced in pass2; many images use only part of the color gamut, so a
* fair amount of work is saved. An additional advantage of this
* approach is that we can apply Heckbert's locality criterion to quickly
* eliminate colormap entries that are far away from the subbox; typically
* three-fourths of the colormap entries are rejected by Heckbert's criterion,
* and we need not compute their distances to individual cells in the subbox.
* The speed of this approach is heavily influenced by the subbox size: too
* small means too much overhead, too big loses because Heckbert's criterion
* can't eliminate as many colormap entries. Empirically the best subbox
* size seems to be about 1/512th of the histogram (1/8th in each direction).
*
* Thomas' article also describes a refined method which is asymptotically
* faster than the brute-force method, but it is also far more complex and
* cannot efficiently be applied to small subboxes. It is therefore not
* useful for programs intended to be portable to DOS machines. On machines
* with plenty of memory, filling the whole histogram in one shot with Thomas'
* refined method might be faster than the present code --- but then again,
* it might not be any faster, and it's certainly more complicated.
*/
/* log2(histogram cells in update box) for each axis; this can be adjusted */
#define BOX_C0_LOG (HIST_C0_BITS-3)
#define BOX_C1_LOG (HIST_C1_BITS-3)
#define BOX_C2_LOG (HIST_C2_BITS-3)
#define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
#define BOX_C1_ELEMS (1<<BOX_C1_LOG)
#define BOX_C2_ELEMS (1<<BOX_C2_LOG)
#define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
#define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
#define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
/*
* The next three routines implement inverse colormap filling. They could
* all be folded into one big routine, but splitting them up this way saves
* some stack space (the mindist[] and bestdist[] arrays need not coexist)
* and may allow some compilers to produce better code by registerizing more
* inner-loop variables.
*/
LOCAL( int )
find_nearby_colors( j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
JSAMPLE colorlist[] )
/* Locate the colormap entries close enough to an update box to be candidates
* for the nearest entry to some cell(s) in the update box. The update box
* is specified by the center coordinates of its first cell. The number of
* candidate colormap entries is returned, and their colormap indexes are
* placed in colorlist[].
* This routine uses Heckbert's "locally sorted search" criterion to select
* the colors that need further consideration.
*/
{
int numcolors = cinfo->actual_number_of_colors;
int maxc0, maxc1, maxc2;
int centerc0, centerc1, centerc2;
int i, x, ncolors;
INT32 minmaxdist, min_dist, max_dist, tdist;
INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
/* Compute true coordinates of update box's upper corner and center.
* Actually we compute the coordinates of the center of the upper-corner
* histogram cell, which are the upper bounds of the volume we care about.
* Note that since ">>" rounds down, the "center" values may be closer to
* min than to max; hence comparisons to them must be "<=", not "<".
*/
maxc0 = minc0 + ( ( 1 << BOX_C0_SHIFT ) - ( 1 << C0_SHIFT ) );
centerc0 = ( minc0 + maxc0 ) >> 1;
maxc1 = minc1 + ( ( 1 << BOX_C1_SHIFT ) - ( 1 << C1_SHIFT ) );
centerc1 = ( minc1 + maxc1 ) >> 1;
maxc2 = minc2 + ( ( 1 << BOX_C2_SHIFT ) - ( 1 << C2_SHIFT ) );
centerc2 = ( minc2 + maxc2 ) >> 1;
/* For each color in colormap, find:
* 1. its minimum squared-distance to any point in the update box
* (zero if color is within update box);
* 2. its maximum squared-distance to any point in the update box.
* Both of these can be found by considering only the corners of the box.
* We save the minimum distance for each color in mindist[];
* only the smallest maximum distance is of interest.
*/
minmaxdist = 0x7FFFFFFFL;
for( i = 0; i < numcolors; i++ )
{
/* We compute the squared-c0-distance term, then add in the other two. */
x = GETJSAMPLE( cinfo->colormap[0][i] );
if( x < minc0 )
{
tdist = ( x - minc0 ) * C0_SCALE;
min_dist = tdist * tdist;
tdist = ( x - maxc0 ) * C0_SCALE;
max_dist = tdist * tdist;
}
else if( x > maxc0 )
{
tdist = ( x - maxc0 ) * C0_SCALE;
min_dist = tdist * tdist;
tdist = ( x - minc0 ) * C0_SCALE;
max_dist = tdist * tdist;
}
else
{
/* within cell range so no contribution to min_dist */
min_dist = 0;
if( x <= centerc0 )
{
tdist = ( x - maxc0 ) * C0_SCALE;
max_dist = tdist * tdist;
}
else
{
tdist = ( x - minc0 ) * C0_SCALE;
max_dist = tdist * tdist;
}
}
x = GETJSAMPLE( cinfo->colormap[1][i] );
if( x < minc1 )
{
tdist = ( x - minc1 ) * C1_SCALE;
min_dist += tdist * tdist;
tdist = ( x - maxc1 ) * C1_SCALE;
max_dist += tdist * tdist;
}
else if( x > maxc1 )
{
tdist = ( x - maxc1 ) * C1_SCALE;
min_dist += tdist * tdist;
tdist = ( x - minc1 ) * C1_SCALE;
max_dist += tdist * tdist;
}
else
{
/* within cell range so no contribution to min_dist */
if( x <= centerc1 )
{
tdist = ( x - maxc1 ) * C1_SCALE;
max_dist += tdist * tdist;
}
else
{
tdist = ( x - minc1 ) * C1_SCALE;
max_dist += tdist * tdist;
}
}
x = GETJSAMPLE( cinfo->colormap[2][i] );
if( x < minc2 )
{
tdist = ( x - minc2 ) * C2_SCALE;
min_dist += tdist * tdist;
tdist = ( x - maxc2 ) * C2_SCALE;
max_dist += tdist * tdist;
}
else if( x > maxc2 )
{
tdist = ( x - maxc2 ) * C2_SCALE;
min_dist += tdist * tdist;
tdist = ( x - minc2 ) * C2_SCALE;
max_dist += tdist * tdist;
}
else
{
/* within cell range so no contribution to min_dist */
if( x <= centerc2 )
{
tdist = ( x - maxc2 ) * C2_SCALE;
max_dist += tdist * tdist;
}
else
{
tdist = ( x - minc2 ) * C2_SCALE;
max_dist += tdist * tdist;
}
}
mindist[i] = min_dist; /* save away the results */
if( max_dist < minmaxdist )
{
minmaxdist = max_dist;
}
}
/* Now we know that no cell in the update box is more than minmaxdist
* away from some colormap entry. Therefore, only colors that are
* within minmaxdist of some part of the box need be considered.
*/
ncolors = 0;
for( i = 0; i < numcolors; i++ )
{
if( mindist[i] <= minmaxdist )
{
colorlist[ncolors++] = ( JSAMPLE ) i;
}
}
return ncolors;
}
LOCAL( void )
find_best_colors( j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[] )
/* Find the closest colormap entry for each cell in the update box,
* given the list of candidate colors prepared by find_nearby_colors.
* Return the indexes of the closest entries in the bestcolor[] array.
* This routine uses Thomas' incremental distance calculation method to
* find the distance from a colormap entry to successive cells in the box.
*/
{
int ic0, ic1, ic2;
int i, icolor;
register INT32 *bptr; /* pointer into bestdist[] array */
JSAMPLE *cptr; /* pointer into bestcolor[] array */
INT32 dist0, dist1; /* initial distance values */
register INT32 dist2; /* current distance in inner loop */
INT32 xx0, xx1; /* distance increments */
register INT32 xx2;
INT32 inc0, inc1, inc2; /* initial values for increments */
/* This array holds the distance to the nearest-so-far color for each cell */
INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
/* Initialize best-distance for each cell of the update box */
bptr = bestdist;
for( i = BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS - 1; i >= 0; i-- )
{
*bptr++ = 0x7FFFFFFFL;
}
/* For each color selected by find_nearby_colors,
* compute its distance to the center of each cell in the box.
* If that's less than best-so-far, update best distance and color number.
*/
/* Nominal steps between cell centers ("x" in Thomas article) */
#define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
#define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
#define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
for( i = 0; i < numcolors; i++ )
{
icolor = GETJSAMPLE( colorlist[i] );
/* Compute (square of) distance from minc0/c1/c2 to this color */
inc0 = ( minc0 - GETJSAMPLE( cinfo->colormap[0][icolor] ) ) * C0_SCALE;
dist0 = inc0 * inc0;
inc1 = ( minc1 - GETJSAMPLE( cinfo->colormap[1][icolor] ) ) * C1_SCALE;
dist0 += inc1 * inc1;
inc2 = ( minc2 - GETJSAMPLE( cinfo->colormap[2][icolor] ) ) * C2_SCALE;
dist0 += inc2 * inc2;
/* Form the initial difference increments */
inc0 = inc0 * ( 2 * STEP_C0 ) + STEP_C0 * STEP_C0;
inc1 = inc1 * ( 2 * STEP_C1 ) + STEP_C1 * STEP_C1;
inc2 = inc2 * ( 2 * STEP_C2 ) + STEP_C2 * STEP_C2;
/* Now loop over all cells in box, updating distance per Thomas method */
bptr = bestdist;
cptr = bestcolor;
xx0 = inc0;
for( ic0 = BOX_C0_ELEMS - 1; ic0 >= 0; ic0-- )
{
dist1 = dist0;
xx1 = inc1;
for( ic1 = BOX_C1_ELEMS - 1; ic1 >= 0; ic1-- )
{
dist2 = dist1;
xx2 = inc2;
for( ic2 = BOX_C2_ELEMS - 1; ic2 >= 0; ic2-- )
{
if( dist2 < *bptr )
{
*bptr = dist2;
*cptr = ( JSAMPLE ) icolor;
}
dist2 += xx2;
xx2 += 2 * STEP_C2 * STEP_C2;
bptr++;
cptr++;
}
dist1 += xx1;
xx1 += 2 * STEP_C1 * STEP_C1;
}
dist0 += xx0;
xx0 += 2 * STEP_C0 * STEP_C0;
}
}
}
LOCAL( void )
fill_inverse_cmap( j_decompress_ptr cinfo, int c0, int c1, int c2 )
/* Fill the inverse-colormap entries in the update box that contains */
/* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
/* we can fill as many others as we wish.) */
{
my_cquantize_ptr cquantize = ( my_cquantize_ptr ) cinfo->cquantize;
hist3d histogram = cquantize->histogram;
int minc0, minc1, minc2; /* lower left corner of update box */
int ic0, ic1, ic2;
register JSAMPLE *cptr; /* pointer into bestcolor[] array */
register histptr cachep; /* pointer into main cache array */
/* This array lists the candidate colormap indexes. */
JSAMPLE colorlist[MAXNUMCOLORS];
int numcolors; /* number of candidate colors */
/* This array holds the actually closest colormap index for each cell. */
JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
/* Convert cell coordinates to update box ID */
c0 >>= BOX_C0_LOG;
c1 >>= BOX_C1_LOG;
c2 >>= BOX_C2_LOG;
/* Compute true coordinates of update box's origin corner.
* Actually we compute the coordinates of the center of the corner
* histogram cell, which are the lower bounds of the volume we care about.
*/
minc0 = ( c0 << BOX_C0_SHIFT ) + ( ( 1 << C0_SHIFT ) >> 1 );
minc1 = ( c1 << BOX_C1_SHIFT ) + ( ( 1 << C1_SHIFT ) >> 1 );
minc2 = ( c2 << BOX_C2_SHIFT ) + ( ( 1 << C2_SHIFT ) >> 1 );
/* Determine which colormap entries are close enough to be candidates
* for the nearest entry to some cell in the update box.
*/
numcolors = find_nearby_colors( cinfo, minc0, minc1, minc2, colorlist );
/* Determine the actually nearest colors. */
find_best_colors( cinfo, minc0, minc1, minc2, numcolors, colorlist,
bestcolor );
/* Save the best color numbers (plus 1) in the main cache array */
c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
c1 <<= BOX_C1_LOG;
c2 <<= BOX_C2_LOG;
cptr = bestcolor;
for( ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++ )
{
for( ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++ )
{
cachep = & histogram[c0 + ic0][c1 + ic1][c2];
for( ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++ )
{
*cachep++ = ( histcell )( GETJSAMPLE( *cptr++ ) + 1 );
}
}
}
}
/*
* Map some rows of pixels to the output colormapped representation.
*/
METHODDEF( void )
pass2_no_dither( j_decompress_ptr cinfo,
JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows )
/* This version performs no dithering */
{
my_cquantize_ptr cquantize = ( my_cquantize_ptr ) cinfo->cquantize;
hist3d histogram = cquantize->histogram;
register JSAMPROW inptr, outptr;
register histptr cachep;
register int c0, c1, c2;
int row;
JDIMENSION col;
JDIMENSION width = cinfo->output_width;
for( row = 0; row < num_rows; row++ )
{
inptr = input_buf[row];
outptr = output_buf[row];
for( col = width; col > 0; col-- )
{
/* get pixel value and index into the cache */
c0 = GETJSAMPLE( *inptr++ ) >> C0_SHIFT;
c1 = GETJSAMPLE( *inptr++ ) >> C1_SHIFT;
c2 = GETJSAMPLE( *inptr++ ) >> C2_SHIFT;
cachep = & histogram[c0][c1][c2];
/* If we have not seen this color before, find nearest colormap entry */
/* and update the cache */
if( *cachep == 0 )
{
fill_inverse_cmap( cinfo, c0, c1, c2 );
}
/* Now emit the colormap index for this cell */
*outptr++ = ( JSAMPLE )( *cachep - 1 );
}
}
}
METHODDEF( void )
pass2_fs_dither( j_decompress_ptr cinfo,
JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows )
/* This version performs Floyd-Steinberg dithering */
{
my_cquantize_ptr cquantize = ( my_cquantize_ptr ) cinfo->cquantize;
hist3d histogram = cquantize->histogram;
register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
register FSERRPTR errorptr; /* => fserrors[] at column before current */
JSAMPROW inptr; /* => current input pixel */
JSAMPROW outptr; /* => current output pixel */
histptr cachep;
int dir; /* +1 or -1 depending on direction */
int dir3; /* 3*dir, for advancing inptr & errorptr */
int row;
JDIMENSION col;
JDIMENSION width = cinfo->output_width;
JSAMPLE *range_limit = cinfo->sample_range_limit;
int *error_limit = cquantize->error_limiter;
JSAMPROW colormap0 = cinfo->colormap[0];
JSAMPROW colormap1 = cinfo->colormap[1];
JSAMPROW colormap2 = cinfo->colormap[2];
SHIFT_TEMPS
for( row = 0; row < num_rows; row++ )
{
inptr = input_buf[row];
outptr = output_buf[row];
if( cquantize->on_odd_row )
{
/* work right to left in this row */
inptr += ( width - 1 ) * 3; /* so point to rightmost pixel */
outptr += width - 1;
dir = -1;
dir3 = -3;
errorptr = cquantize->fserrors + ( width + 1 ) * 3; /* => entry after last column */
cquantize->on_odd_row = FALSE; /* flip for next time */
}
else
{
/* work left to right in this row */
dir = 1;
dir3 = 3;
errorptr = cquantize->fserrors; /* => entry before first real column */
cquantize->on_odd_row = TRUE; /* flip for next time */
}
/* Preset error values: no error propagated to first pixel from left */
cur0 = cur1 = cur2 = 0;
/* and no error propagated to row below yet */
belowerr0 = belowerr1 = belowerr2 = 0;
bpreverr0 = bpreverr1 = bpreverr2 = 0;
for( col = width; col > 0; col-- )
{
/* curN holds the error propagated from the previous pixel on the
* current line. Add the error propagated from the previous line
* to form the complete error correction term for this pixel, and
* round the error term (which is expressed * 16) to an integer.
* RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
* for either sign of the error value.
* Note: errorptr points to *previous* column's array entry.
*/
cur0 = RIGHT_SHIFT( cur0 + errorptr[dir3 + 0] + 8, 4 );
cur1 = RIGHT_SHIFT( cur1 + errorptr[dir3 + 1] + 8, 4 );
cur2 = RIGHT_SHIFT( cur2 + errorptr[dir3 + 2] + 8, 4 );
/* Limit the error using transfer function set by init_error_limit.
* See comments with init_error_limit for rationale.
*/
cur0 = error_limit[cur0];
cur1 = error_limit[cur1];
cur2 = error_limit[cur2];
/* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
* The maximum error is +- MAXJSAMPLE (or less with error limiting);
* this sets the required size of the range_limit array.
*/
cur0 += GETJSAMPLE( inptr[0] );
cur1 += GETJSAMPLE( inptr[1] );
cur2 += GETJSAMPLE( inptr[2] );
cur0 = GETJSAMPLE( range_limit[cur0] );
cur1 = GETJSAMPLE( range_limit[cur1] );
cur2 = GETJSAMPLE( range_limit[cur2] );
/* Index into the cache with adjusted pixel value */
cachep = & histogram[cur0 >> C0_SHIFT][cur1 >> C1_SHIFT][cur2 >> C2_SHIFT];
/* If we have not seen this color before, find nearest colormap */
/* entry and update the cache */
if( *cachep == 0 )
{
fill_inverse_cmap( cinfo, cur0 >> C0_SHIFT, cur1 >> C1_SHIFT, cur2 >> C2_SHIFT );
}
/* Now emit the colormap index for this cell */
{
register int pixcode = *cachep - 1;
*outptr = ( JSAMPLE ) pixcode;
/* Compute representation error for this pixel */
cur0 -= GETJSAMPLE( colormap0[pixcode] );
cur1 -= GETJSAMPLE( colormap1[pixcode] );
cur2 -= GETJSAMPLE( colormap2[pixcode] );
}
/* Compute error fractions to be propagated to adjacent pixels.
* Add these into the running sums, and simultaneously shift the
* next-line error sums left by 1 column.
*/
{
register LOCFSERROR bnexterr, delta;
bnexterr = cur0; /* Process component 0 */
delta = cur0 * 2;
cur0 += delta; /* form error * 3 */
errorptr[0] = ( FSERROR )( bpreverr0 + cur0 );
cur0 += delta; /* form error * 5 */
bpreverr0 = belowerr0 + cur0;
belowerr0 = bnexterr;
cur0 += delta; /* form error * 7 */
bnexterr = cur1; /* Process component 1 */
delta = cur1 * 2;
cur1 += delta; /* form error * 3 */
errorptr[1] = ( FSERROR )( bpreverr1 + cur1 );
cur1 += delta; /* form error * 5 */
bpreverr1 = belowerr1 + cur1;
belowerr1 = bnexterr;
cur1 += delta; /* form error * 7 */
bnexterr = cur2; /* Process component 2 */
delta = cur2 * 2;
cur2 += delta; /* form error * 3 */
errorptr[2] = ( FSERROR )( bpreverr2 + cur2 );
cur2 += delta; /* form error * 5 */
bpreverr2 = belowerr2 + cur2;
belowerr2 = bnexterr;
cur2 += delta; /* form error * 7 */
}
/* At this point curN contains the 7/16 error value to be propagated
* to the next pixel on the current line, and all the errors for the
* next line have been shifted over. We are therefore ready to move on.
*/
inptr += dir3; /* Advance pixel pointers to next column */
outptr += dir;
errorptr += dir3; /* advance errorptr to current column */
}
/* Post-loop cleanup: we must unload the final error values into the
* final fserrors[] entry. Note we need not unload belowerrN because
* it is for the dummy column before or after the actual array.
*/
errorptr[0] = ( FSERROR ) bpreverr0; /* unload prev errs into array */
errorptr[1] = ( FSERROR ) bpreverr1;
errorptr[2] = ( FSERROR ) bpreverr2;
}
}
/*
* Initialize the error-limiting transfer function (lookup table).
* The raw F-S error computation can potentially compute error values of up to
* +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
* much less, otherwise obviously wrong pixels will be created. (Typical
* effects include weird fringes at color-area boundaries, isolated bright
* pixels in a dark area, etc.) The standard advice for avoiding this problem
* is to ensure that the "corners" of the color cube are allocated as output
* colors; then repeated errors in the same direction cannot cause cascading
* error buildup. However, that only prevents the error from getting
* completely out of hand; Aaron Giles reports that error limiting improves
* the results even with corner colors allocated.
* A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
* well, but the smoother transfer function used below is even better. Thanks
* to Aaron Giles for this idea.
*/
LOCAL( void )
init_error_limit( j_decompress_ptr cinfo )
/* Allocate and fill in the error_limiter table */
{
my_cquantize_ptr cquantize = ( my_cquantize_ptr ) cinfo->cquantize;
int *table;
int in, out;
table = ( int * )( *cinfo->mem->alloc_small )
( ( j_common_ptr ) cinfo, JPOOL_IMAGE, ( MAXJSAMPLE * 2 + 1 ) * SIZEOF( int ) );
table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
cquantize->error_limiter = table;
#define STEPSIZE ((MAXJSAMPLE+1)/16)
/* Map errors 1:1 up to +- MAXJSAMPLE/16 */
out = 0;
for( in = 0; in < STEPSIZE; in++, out++ )
{
table[in] = out;
table[-in] = -out;
}
/* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
for( ; in < STEPSIZE * 3; in++, out += ( in & 1 ) ? 0 : 1 )
{
table[in] = out;
table[-in] = -out;
}
/* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
for( ; in <= MAXJSAMPLE; in++ )
{
table[in] = out;
table[-in] = -out;
}
#undef STEPSIZE
}
/*
* Finish up at the end of each pass.
*/
METHODDEF( void )
finish_pass1( j_decompress_ptr cinfo )
{
my_cquantize_ptr cquantize = ( my_cquantize_ptr ) cinfo->cquantize;
/* Select the representative colors and fill in cinfo->colormap */
cinfo->colormap = cquantize->sv_colormap;
select_colors( cinfo, cquantize->desired );
/* Force next pass to zero the color index table */
cquantize->needs_zeroed = TRUE;
}
METHODDEF( void )
finish_pass2( j_decompress_ptr cinfo )
{
/* no work */
}
/*
* Initialize for each processing pass.
*/
METHODDEF( void )
start_pass_2_quant( j_decompress_ptr cinfo, boolean is_pre_scan )
{
my_cquantize_ptr cquantize = ( my_cquantize_ptr ) cinfo->cquantize;
hist3d histogram = cquantize->histogram;
int i;
/* Only F-S dithering or no dithering is supported. */
/* If user asks for ordered dither, give him F-S. */
if( cinfo->dither_mode != JDITHER_NONE )
{
cinfo->dither_mode = JDITHER_FS;
}
if( is_pre_scan )
{
/* Set up method pointers */
cquantize->pub.color_quantize = prescan_quantize;
cquantize->pub.finish_pass = finish_pass1;
cquantize->needs_zeroed = TRUE; /* Always zero histogram */
}
else
{
/* Set up method pointers */
if( cinfo->dither_mode == JDITHER_FS )
{
cquantize->pub.color_quantize = pass2_fs_dither;
}
else
{
cquantize->pub.color_quantize = pass2_no_dither;
}
cquantize->pub.finish_pass = finish_pass2;
/* Make sure color count is acceptable */
i = cinfo->actual_number_of_colors;
if( i < 1 )
{
ERREXIT1( cinfo, JERR_QUANT_FEW_COLORS, 1 );
}
if( i > MAXNUMCOLORS )
{
ERREXIT1( cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS );
}
if( cinfo->dither_mode == JDITHER_FS )
{
size_t arraysize = ( size_t )( ( cinfo->output_width + 2 ) *
( 3 * SIZEOF( FSERROR ) ) );
/* Allocate Floyd-Steinberg workspace if we didn't already. */
if( cquantize->fserrors == NULL )
cquantize->fserrors = ( FSERRPTR )( *cinfo->mem->alloc_large )
( ( j_common_ptr ) cinfo, JPOOL_IMAGE, arraysize );
/* Initialize the propagated errors to zero. */
FMEMZERO( ( void FAR * ) cquantize->fserrors, arraysize );
/* Make the error-limit table if we didn't already. */
if( cquantize->error_limiter == NULL )
{
init_error_limit( cinfo );
}
cquantize->on_odd_row = FALSE;
}
}
/* Zero the histogram or inverse color map, if necessary */
if( cquantize->needs_zeroed )
{
for( i = 0; i < HIST_C0_ELEMS; i++ )
{
FMEMZERO( ( void FAR * ) histogram[i],
HIST_C1_ELEMS * HIST_C2_ELEMS * SIZEOF( histcell ) );
}
cquantize->needs_zeroed = FALSE;
}
}
/*
* Switch to a new external colormap between output passes.
*/
METHODDEF( void )
new_color_map_2_quant( j_decompress_ptr cinfo )
{
my_cquantize_ptr cquantize = ( my_cquantize_ptr ) cinfo->cquantize;
/* Reset the inverse color map */
cquantize->needs_zeroed = TRUE;
}
/*
* Module initialization routine for 2-pass color quantization.
*/
GLOBAL( void )
jinit_2pass_quantizer( j_decompress_ptr cinfo )
{
my_cquantize_ptr cquantize;
int i;
cquantize = ( my_cquantize_ptr )
( *cinfo->mem->alloc_small )( ( j_common_ptr ) cinfo, JPOOL_IMAGE,
SIZEOF( my_cquantizer ) );
cinfo->cquantize = ( struct jpeg_color_quantizer * ) cquantize;
cquantize->pub.start_pass = start_pass_2_quant;
cquantize->pub.new_color_map = new_color_map_2_quant;
cquantize->fserrors = NULL; /* flag optional arrays not allocated */
cquantize->error_limiter = NULL;
/* Make sure jdmaster didn't give me a case I can't handle */
if( cinfo->out_color_components != 3 )
{
ERREXIT( cinfo, JERR_NOTIMPL );
}
/* Allocate the histogram/inverse colormap storage */
cquantize->histogram = ( hist3d )( *cinfo->mem->alloc_small )
( ( j_common_ptr ) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF( hist2d ) );
for( i = 0; i < HIST_C0_ELEMS; i++ )
{
cquantize->histogram[i] = ( hist2d )( *cinfo->mem->alloc_large )
( ( j_common_ptr ) cinfo, JPOOL_IMAGE,
HIST_C1_ELEMS * HIST_C2_ELEMS * SIZEOF( histcell ) );
}
cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
/* Allocate storage for the completed colormap, if required.
* We do this now since it is FAR storage and may affect
* the memory manager's space calculations.
*/
if( cinfo->enable_2pass_quant )
{
/* Make sure color count is acceptable */
int desired = cinfo->desired_number_of_colors;
/* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
if( desired < 8 )
{
ERREXIT1( cinfo, JERR_QUANT_FEW_COLORS, 8 );
}
/* Make sure colormap indexes can be represented by JSAMPLEs */
if( desired > MAXNUMCOLORS )
{
ERREXIT1( cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS );
}
cquantize->sv_colormap = ( *cinfo->mem->alloc_sarray )
( ( j_common_ptr ) cinfo, JPOOL_IMAGE, ( JDIMENSION ) desired, ( JDIMENSION ) 3 );
cquantize->desired = desired;
}
else
{
cquantize->sv_colormap = NULL;
}
/* Only F-S dithering or no dithering is supported. */
/* If user asks for ordered dither, give him F-S. */
if( cinfo->dither_mode != JDITHER_NONE )
{
cinfo->dither_mode = JDITHER_FS;
}
/* Allocate Floyd-Steinberg workspace if necessary.
* This isn't really needed until pass 2, but again it is FAR storage.
* Although we will cope with a later change in dither_mode,
* we do not promise to honor max_memory_to_use if dither_mode changes.
*/
if( cinfo->dither_mode == JDITHER_FS )
{
cquantize->fserrors = ( FSERRPTR )( *cinfo->mem->alloc_large )
( ( j_common_ptr ) cinfo, JPOOL_IMAGE,
( size_t )( ( cinfo->output_width + 2 ) * ( 3 * SIZEOF( FSERROR ) ) ) );
/* Might as well create the error-limiting table too. */
init_error_limit( cinfo );
}
}
#endif /* QUANT_2PASS_SUPPORTED */
| gpl-3.0 |
wrobell/btzen | btzen/service.py | 2651 | #
# BTZen - library to asynchronously access Bluetooth devices.
#
# Copyright (C) 2015-2021 by Artur Wroblewski <wrobell@riseup.net>
#
# 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 annotations
import dataclasses as dtc
import typing as tp
from collections import defaultdict
from .data import T, AddressType, AnyTrigger, Converter, Make, NoTrigger, \
ServiceType
# registry of known services
_SERVICE_REGISTRY = defaultdict[
'Make',
dict['ServiceType', tuple['Service', Converter, AnyTrigger, 'AddressType']]
](dict)
@dtc.dataclass(frozen=True)
class Service:
"""
Bluetooth service descriptor.
:var uuid: UUID of Bluetooth service.
"""
uuid: str
@dtc.dataclass(frozen=True)
class ServiceInterface(Service):
"""
Bluetooth device information for device providing data via Bluez
interface property.
Example of interface for Battery Level Bluetooth characteristic is
`org.bluez.Battery1` Bluez interface, which provides data via
`Percentage` property.
:var interface: Bluez interface name.
:var property: Property name of the interface.
:var type: Type of property value.
"""
interface: str
property: str
type: str
@dtc.dataclass(frozen=True)
class ServiceCharacteristic(Service):
"""
Bluetooth service descriptor for Bluetooth characteristic.
:var uuid_data: UUID of characteristic to read data from.
:var size: Length of data received from Bluetooth characteristic on
read.
"""
uuid_data: str
size: int
def register_service(
make: Make,
service_type: ServiceType,
service: Service,
*,
convert: Converter[T]=tp.cast(Converter, lambda v: v),
trigger: AnyTrigger=NoTrigger(),
address_type=AddressType.PUBLIC,
):
"""
Register service with data conversion function.
"""
_SERVICE_REGISTRY[make][service_type] = (
service, convert, trigger, address_type
)
S = tp.TypeVar('S', bound=Service, covariant=True)
# vim: sw=4:et:ai
| gpl-3.0 |
Nimoab/DQN-Deepmind-NIPS-2013 | doc/html/search/functions_6.js | 540 | var searchData=
[
['gameover',['gameOver',['../classDQN-Deepmind-NIPS-2013_1_1GameEnv_1_1GameEnv.html#a1ccc35e029e05910c3c25ffa602e442b',1,'DQN-Deepmind-NIPS-2013::GameEnv::GameEnv']]],
['getscreen',['getScreen',['../classDQN-Deepmind-NIPS-2013_1_1GameEnv_1_1GameEnv.html#a37712548267b91afddb6866fddf22b94',1,'DQN-Deepmind-NIPS-2013::GameEnv::GameEnv']]],
['getscreenrgb',['getScreenRGB',['../classDQN-Deepmind-NIPS-2013_1_1GameEnv_1_1GameEnv.html#a553c6eac3cac494bff5c9703dcfea2fe',1,'DQN-Deepmind-NIPS-2013::GameEnv::GameEnv']]]
];
| gpl-3.0 |
Yonjuni/ExaltedDicer | app/src/main/java/de/pinyto/exalteddicer/dicing/Dicer.java | 1645 | package de.pinyto.exalteddicer.dicing;
public class Dicer {
public int targetNumber = 7; // Default
public int poolSize;
public void setPoolSize(int poolSize) {
this.poolSize = poolSize;
}
// For Special-Charms and Artifacts
public void setTargetNumber(int targetNumber) {
this.targetNumber = targetNumber;
}
public int[] rollDice() {
int[] dice = new int[poolSize];
for (int i = 0; i < dice.length; i++) {
dice[i] = (int) (Math.random() * 10) + 1;
}
return dice;
}
public int evaluateDamage() {
int success = 0;
int ones = 0;
int[] dice = rollDice();
for (int i = 0; i < dice.length; i++) {
if (dice[i] >= targetNumber) {
success = success + 1;
} else {
if (dice[i] == 1) {
ones = ones + 1;
}
}
}
if (success == 0 && ones > 0) {
return -1;
}
return success;
}
// Tens are counted twice
public int evaluatePool() {
int[] dice = rollDice();
int success = 0;
int ones = 0;
for (int i = 0; i < dice.length; i++) {
if (dice[i] >= targetNumber && dice[i] != 10) {
success = success + 1;
}
if (dice[i] == 1) {
ones = ones + 1;
}
if (dice[i] == 10) {
success = success + 2;
}
}
if (success == 0 && ones > 0) {
return -1;
}
return success;
}
}
| gpl-3.0 |
tectronics/quicktools | quickLoad/XPExplorerBar_src_v3_3_VS2005/XPExplorerBar VS2005/Expando.cs | 149705 | /*
* Copyright © 2004-2005, Mathew Hall
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Design;
using System.Drawing.Imaging;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Threading;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Xml.Serialization;
namespace XPExplorerBar
{
#region Delegates
/// <summary>
/// Represents the method that will handle the StateChanged, ExpandoAdded,
/// and ExpandoRemoved events of an Expando or TaskPane
/// </summary>
/// <param name="sender">The source of the event</param>
/// <param name="e">A ExpandoEventArgs that contains the event data</param>
public delegate void ExpandoEventHandler(object sender, ExpandoEventArgs e);
#endregion
#region Expando
/// <summary>
/// A Control that replicates the collapsable panels found in
/// Windows XP's Explorer Bar
/// </summary>
[ToolboxItem(true),
DefaultEvent("StateChanged"),
DesignerAttribute(typeof(ExpandoDesigner))]
public class Expando : Control, ISupportInitialize
{
#region added by Lucas
private ControlCollection ReallyHiddenControls;
#endregion
#region EventHandlers
/// <summary>
/// Occurs when the value of the Collapsed property changes
/// </summary>
public event ExpandoEventHandler StateChanged;
/// <summary>
/// Occurs when the value of the TitleImage property changes
/// </summary>
public event ExpandoEventHandler TitleImageChanged;
/// <summary>
/// Occurs when the value of the SpecialGroup property changes
/// </summary>
public event ExpandoEventHandler SpecialGroupChanged;
/// <summary>
/// Occurs when the value of the Watermark property changes
/// </summary>
public event ExpandoEventHandler WatermarkChanged;
/// <summary>
/// Occurs when an item (Control) is added to the Expando
/// </summary>
public event ControlEventHandler ItemAdded;
/// <summary>
/// Occurs when an item (Control) is removed from the Expando
/// </summary>
public event ControlEventHandler ItemRemoved;
/// <summary>
/// Occurs when a value in the CustomSettings or CustomHeaderSettings
/// proterties changes
/// </summary>
public event EventHandler CustomSettingsChanged;
#endregion
#region Class Data
/// <summary>
/// Required designer variable
/// </summary>
private Container components = null;
/// <summary>
/// System settings for the Expando
/// </summary>
private ExplorerBarInfo systemSettings;
/// <summary>
/// Is the Expando a special group
/// </summary>
private bool specialGroup;
/// <summary>
/// The height of the Expando in its expanded state
/// </summary>
private int expandedHeight;
/// <summary>
/// The image displayed on the left side of the titlebar
/// </summary>
private Image titleImage;
/// <summary>
/// The height of the header section
/// (includes titlebar and title image)
/// </summary>
private int headerHeight;
/// <summary>
/// Is the Expando collapsed
/// </summary>
private bool collapsed;
/// <summary>
/// The state of the titlebar
/// </summary>
private FocusStates focusState;
/// <summary>
/// The height of the titlebar
/// </summary>
private int titleBarHeight;
/// <summary>
/// Specifies whether the Expando is allowed to animate
/// </summary>
private bool animate;
/// <summary>
/// Spcifies whether the Expando is currently animating a fade
/// </summary>
private bool animatingFade;
/// <summary>
/// Spcifies whether the Expando is we currently animating a slide
/// </summary>
private bool animatingSlide;
/// <summary>
/// An image of the "client area" which is used
/// during a fade animation
/// </summary>
private Image animationImage;
/// <summary>
/// An AnimationHelper that help the Expando to animate
/// </summary>
private AnimationHelper animationHelper;
/// <summary>
/// The TaskPane the Expando belongs to
/// </summary>
private TaskPane taskpane;
/// <summary>
/// Should the Expando layout its items itself
/// </summary>
private bool autoLayout;
/// <summary>
/// The last known width of the Expando
/// (used while animating)
/// </summary>
private int oldWidth;
/// <summary>
/// Specifies whether the Expando is currently initialising
/// </summary>
private bool initialising;
/// <summary>
/// Internal list of items contained in the Expando
/// </summary>
private ItemCollection itemList;
/// <summary>
/// Internal list of controls that have been hidden
/// </summary>
private ArrayList hiddenControls;
/// <summary>
/// A panel the Expando can move its controls onto when it is
/// animating from collapsed to expanded.
/// </summary>
private AnimationPanel dummyPanel;
/// <summary>
/// Specifies whether the Expando is allowed to collapse
/// </summary>
private bool canCollapse;
/// <summary>
/// The height of the Expando at the end of its slide animation
/// </summary>
private int slideEndHeight;
/// <summary>
/// The index of the Image that is used as a watermark
/// </summary>
private Image watermark;
/// <summary>
/// Specifies whether the Expando should draw a focus rectangle
/// when it has focus
/// </summary>
private bool showFocusCues;
/// <summary>
/// Specifies whether the Expando is currently performing a
/// layout operation
/// </summary>
private bool layout = false;
/// <summary>
/// Specifies the custom settings for the Expando
/// </summary>
private ExpandoInfo customSettings;
/// <summary>
/// Specifies the custom header settings for the Expando
/// </summary>
private HeaderInfo customHeaderSettings;
/// <summary>
/// An array of pre-determined heights for use during a
/// fade animation
/// </summary>
private int[] fadeHeights;
/// <summary>
/// Specifies whether the Expando should use Windows
/// defsult Tab handling mechanism
/// </summary>
private bool useDefaultTabHandling;
/// <summary>
/// Specifies the number of times BeginUpdate() has been called
/// </summary>
private int beginUpdateCount;
/// <summary>
/// Specifies whether slide animations should be batched
/// </summary>
private bool slideAnimationBatched;
/// <summary>
/// Specifies whether the Expando is currently being dragged
/// </summary>
private bool dragging;
/// <summary>
/// Specifies the Point that a drag operation started at
/// </summary>
private Point dragStart;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the Expando class with default settings
/// </summary>
public Expando() : base()
{
// This call is required by the Windows.Forms Form Designer.
this.components = new System.ComponentModel.Container();
// set control styles
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.SetStyle(ControlStyles.Selectable, true);
this.TabStop = true;
// get the system theme settings
this.systemSettings = ThemeManager.GetSystemExplorerBarSettings();
this.customSettings = new ExpandoInfo();
this.customSettings.Expando = this;
this.customSettings.SetDefaultEmptyValues();
this.customHeaderSettings = new HeaderInfo();
this.customHeaderSettings.Expando = this;
this.customHeaderSettings.SetDefaultEmptyValues();
this.BackColor = this.systemSettings.Expando.NormalBackColor;
// the height of the Expando in the expanded state
this.expandedHeight = 100;
// animation
this.animate = false;
this.animatingFade = false;
this.animatingSlide = false;
this.animationImage = null;
this.slideEndHeight = -1;
this.animationHelper = null;
this.fadeHeights = new int[AnimationHelper.NumAnimationFrames];
// size
this.Size = new Size(this.systemSettings.Header.BackImageWidth, this.expandedHeight);
this.titleBarHeight = this.systemSettings.Header.BackImageHeight;
this.headerHeight = this.titleBarHeight;
this.oldWidth = this.Width;
// start expanded
this.collapsed = false;
// not a special group
this.specialGroup = false;
// unfocused titlebar
this.focusState = FocusStates.None;
// no title image
this.titleImage = null;
this.watermark = null;
this.Font = new Font(this.TitleFont.Name, 8.25f, FontStyle.Regular);
// don't get the Expando to layout its items itself
this.autoLayout = false;
// don't know which TaskPane we belong to
this.taskpane = null;
// internal list of items
this.itemList = new ItemCollection(this);
this.hiddenControls = new ArrayList();
// initialise the dummyPanel
this.dummyPanel = new AnimationPanel();
this.dummyPanel.Size = this.Size;
this.dummyPanel.Location = new Point(-1000, 0);
this.canCollapse = true;
this.showFocusCues = false;
this.useDefaultTabHandling = true;
this.CalcAnimationHeights();
this.slideAnimationBatched = false;
this.dragging = false;
this.dragStart = Point.Empty;
this.beginUpdateCount = 0;
this.initialising = false;
this.layout = false;
}
#endregion
#region Methods
#region Animation
#region Fade Collapse/Expand
/// <summary>
/// Collapses the group without any animation.
/// </summary>
public void Collapse()
{
this.collapsed = true;
if (!this.Animating && this.Height != this.HeaderHeight)
{
this.Height = this.headerHeight;
// fix: Raise StateChanged event
// Jewlin (jewlin88@hotmail.com)
// 22/10/2004
// v3.0
this.OnStateChanged(new ExpandoEventArgs(this));
}
}
/// <summary>
/// Expands the group without any animation.
/// </summary>
public void Expand()
{
this.collapsed = false;
if (!this.Animating && this.Height != this.ExpandedHeight)
{
this.Height = this.ExpandedHeight;
// fix: Raise StateChanged event
// Jewlin (jewlin88@hotmail.com)
// 22/10/2004
// v3.0
this.OnStateChanged(new ExpandoEventArgs(this));
}
}
/// <summary>
/// Gets the Expando ready to start its collapse/expand animation
/// </summary>
protected void StartFadeAnimation()
{
//
this.animatingFade = true;
//
this.SuspendLayout();
// get an image of the client area that we can
// use for alpha-blending in our animation
this.animationImage = this.GetFadeAnimationImage();
// set each control invisible (otherwise they
// appear to slide off the bottom of the group)
foreach (Control control in this.Controls)
{
control.Visible = false;
}
// restart the layout engine
this.ResumeLayout(false);
}
/// <summary>
/// Updates the next "frame" of the animation
/// </summary>
/// <param name="animationStepNum">The current step in the animation</param>
/// <param name="numAnimationSteps">The total number of steps in the animation</param>
protected void UpdateFadeAnimation(int animationStepNum, int numAnimationSteps)
{
// fix: use the precalculated heights to determine
// the correct height
// David Nissimoff (dudi_001@yahoo.com.br)
// 22/10/2004
// v3.0
// set the height of the group
if (this.collapsed)
{
this.Height = this.fadeHeights[animationStepNum-1] + this.headerHeight;
}
else
{
this.Height = (this.ExpandedHeight - this.HeaderHeight) - this.fadeHeights[animationStepNum-1] + this.HeaderHeight - 1;
}
if (this.TaskPane != null)
{
this.TaskPane.DoLayout();
}
else
{
// draw the next frame
this.Invalidate();
}
}
/// <summary>
/// Gets the Expando to stop its animation
/// </summary>
protected void StopFadeAnimation()
{
//
this.animatingFade = false;
//
this.SuspendLayout();
// get rid of the image used for the animation
this.animationImage.Dispose();
this.animationImage = null;
// set the final height of the group, depending on
// whether we are collapsed or expanded
if (this.collapsed)
{
this.Height = this.HeaderHeight;
}
else
{
this.Height = this.ExpandedHeight;
}
// set each control visible again
foreach (Control control in this.Controls)
{
control.Visible = !this.hiddenControls.Contains(control);
}
//
this.ResumeLayout(true);
if (this.TaskPane != null)
{
this.TaskPane.DoLayout();
}
}
/// <summary>
/// Returns an image of the group's display area to be used
/// in the fade animation
/// </summary>
/// <returns>The Image to use during the fade animation</returns>
protected Image GetFadeAnimationImage()
{
if (this.Height == this.ExpandedHeight)
{
return this.GetExpandedImage();
}
else
{
return this.GetCollapsedImage();
}
}
/// <summary>
/// Gets the image to be used in the animation while the
/// Expando is in its expanded state
/// </summary>
/// <returns>The Image to use during the fade animation</returns>
protected Image GetExpandedImage()
{
// create a new image to draw into
Image image = new Bitmap(this.Width, this.Height);
// get a graphics object we can draw into
Graphics g = Graphics.FromImage(image);
IntPtr hDC = g.GetHdc();
// some flags to tell the control how to draw itself
IntPtr flags = (IntPtr) (WmPrintFlags.PRF_CLIENT | WmPrintFlags.PRF_CHILDREN | WmPrintFlags.PRF_ERASEBKGND);
// tell the control to draw itself
NativeMethods.SendMessage(this.Handle, WindowMessageFlags.WM_PRINT, hDC, flags);
// clean up resources
g.ReleaseHdc(hDC);
g.Dispose();
// return the completed animation image
return image;
}
/// <summary>
/// Gets the image to be used in the animation while the
/// Expando is in its collapsed state
/// </summary>
/// <returns>The Image to use during the fade animation</returns>
protected Image GetCollapsedImage()
{
// this is pretty nasty. after much experimentation,
// this is the least preferred way to get the image as
// it is a pain in the backside, but it stops any
// flickering and it gets xp themed controls to draw
// their borders properly.
// we have to do this in two stages:
// 1) pretend we're expanded and draw our background,
// borders and "client area" into a bitmap
// 2) set the bitmap as our dummyPanel's background,
// move all our controls onto the dummyPanel and
// get the dummyPanel to print itself
int width = this.Width;
int height = this.ExpandedHeight;
// create a new image to draw that is the same
// size we would be if we were expanded
Image backImage = new Bitmap(width, height);
// get a graphics object we can draw into
Graphics g = Graphics.FromImage(backImage);
// draw our parents background
this.PaintTransparentBackground(g, new Rectangle(0, 0, width, height));
// don't need to draw the titlebar as it is ignored
// when we paint with the animation image, but we do
// need to draw the borders and "client area"
this.OnPaintTitleBarBackground(g);
this.OnPaintTitleBar(g);
// borders
using (SolidBrush brush = new SolidBrush(this.BorderColor))
{
// top border
g.FillRectangle(brush,
this.Border.Left,
this.HeaderHeight,
width - this.Border.Left - this.Border.Right,
this.Border.Top);
// left border
g.FillRectangle(brush,
0,
this.HeaderHeight,
this.Border.Left,
height - this.HeaderHeight);
// right border
g.FillRectangle(brush,
width - this.Border.Right,
this.HeaderHeight,
this.Border.Right,
height - this.HeaderHeight);
// bottom border
g.FillRectangle(brush,
this.Border.Left,
height - this.Border.Bottom,
width - this.Border.Left - this.Border.Right,
this.Border.Bottom);
}
// "client area"
using (SolidBrush brush = new SolidBrush(this.BackColor))
{
g.FillRectangle(brush,
this.Border.Left,
this.HeaderHeight,
width - this.Border.Left - this.Border.Right,
height - this.HeaderHeight - this.Border.Bottom - this.Border.Top);
}
// check if we have a background image
if (this.BackImage != null)
{
// tile the backImage
using (TextureBrush brush = new TextureBrush(this.BackImage, WrapMode.Tile))
{
g.FillRectangle(brush,
this.Border.Left,
this.HeaderHeight,
width - this.Border.Left - this.Border.Right,
height - this.HeaderHeight - this.Border.Bottom - this.Border.Top);
}
}
// watermark
if (this.Watermark != null)
{
// work out a rough location of where the watermark should go
Rectangle rect = new Rectangle(0, 0, this.Watermark.Width, this.Watermark.Height);
rect.X = width - this.Border.Right - this.Watermark.Width;
rect.Y = height - this.Border.Bottom - this.Watermark.Height;
// shrink the destination rect if necesary so that we
// can see all of the image
if (rect.X < 0)
{
rect.X = 0;
}
if (rect.Width > this.ClientRectangle.Width)
{
rect.Width = this.ClientRectangle.Width;
}
if (rect.Y < this.DisplayRectangle.Top)
{
rect.Y = this.DisplayRectangle.Top;
}
if (rect.Height > this.DisplayRectangle.Height)
{
rect.Height = this.DisplayRectangle.Height;
}
// draw the watermark
g.DrawImage(this.Watermark, rect);
}
// cleanup resources;
g.Dispose();
// make sure the dummyPanel is the same size as our image
// (we don't want any tiling of the image)
this.dummyPanel.Size = new Size(width, height);
this.dummyPanel.HeaderHeight = this.HeaderHeight;
this.dummyPanel.Border = this.Border;
// set the image as the dummyPanels background
this.dummyPanel.BackImage = backImage;
// move all our controls to the dummyPanel, and then add
// the dummyPanel to us
while (this.Controls.Count > 0)
{
Control control = this.Controls[0];
this.Controls.RemoveAt(0);
this.dummyPanel.Controls.Add(control);
control.Visible = !this.hiddenControls.Contains(control);
}
this.Controls.Add(this.dummyPanel);
// create a new image for the dummyPanel to draw itself into
Image image = new Bitmap(width, height);
// get a graphics object we can draw into
g = Graphics.FromImage(image);
IntPtr hDC = g.GetHdc();
// some flags to tell the control how to draw itself
IntPtr flags = (IntPtr) (WmPrintFlags.PRF_CLIENT | WmPrintFlags.PRF_CHILDREN);
// tell the control to draw itself
NativeMethods.SendMessage(this.dummyPanel.Handle, WindowMessageFlags.WM_PRINT, hDC, flags);
// clean up resources
g.ReleaseHdc(hDC);
g.Dispose();
this.Controls.Remove(this.dummyPanel);
// get our controls back
while (this.dummyPanel.Controls.Count > 0)
{
Control control = this.dummyPanel.Controls[0];
control.Visible = false;
this.dummyPanel.Controls.RemoveAt(0);
this.Controls.Add(control);
}
// dispose of the background image
this.dummyPanel.BackImage = null;
backImage.Dispose();
return image;
}
// Added: CalcAnimationHeights()
// David Nissimoff (dudi_001@yahoo.com.br)
// 22/10/2004
// v3.0
/// <summary>
/// Caches the heights that the Expando should be for each frame
/// of a fade animation
/// </summary>
internal void CalcAnimationHeights()
{
// Windows XP uses a Bezier curve to calculate the height of
// an Expando during a fade animation, so here we precalculate
// the height of the "client area" for each frame.
//
// I can't describe what's happening better than David Nissimoff,
// so here's David's description of what goes on:
//
// "The only thing that I've noticed is that the animation routine
// doesn't completely simulate the one used in Windows. After 2 days
// of endless tests I have finally discovered what should've been written
// to accurately simulate Windows XP behaviour.
// I first created a simple application in VB that would copy an
// area of the screen (set to one of the Windows' expandos) every time
// it changed. Having that information, analyzing every frame of the
// animation I could see that it would always be formed of 23 steps.
// Once having all of the animation, frame by frame, I could see
// that the expando's height obeyed to a bézier curve. For testing
// purposes, I have created an application that draws the bézier curve
// on top of the frames put side by side, and it matches 100%.
// The height of the expando in each step would be the vertical
// position of the bézier in the horizontal position(i.e. the step).
// A bézier should be drawn into a Graphics object, with x1 set to
// 0 (initial step = 0) and y1 to the initial height of the expando to
// be animated. The first control point (x2,y2) is defined by:
// x2 = (numAnimationSteps / 4) * 3
// y2 = (HeightVariation / 4) * 3
// The second control point (x3,y3) is defined as follows:
// x3 = numAnimationSteps / 4
// y3 = HeightVariation / 4
// The end point (x3,y3) would be:
// x4 = 22 --> 23 steps = 0 to 22
// y4 = FinalAnimationHeight
// Then, to get the height of the expando on any desired step, you
// should call the Bitmap used to create the Graphics and look pixel by
// pixel in the column of the step number until you find the curve."
//
// I hope that helps ;)
if (this.ExpandedHeight - this.HeaderHeight <= 0)
{
//this.Animate = false;
this.TaskPane.UseClassicTheme();
}
if (!this.animate)
return;
using (Bitmap bitmap = new Bitmap(this.fadeHeights.Length, this.ExpandedHeight - this.HeaderHeight > 0 ? this.ExpandedHeight - this.HeaderHeight : 1 ))
{
// draw the bezier curve
using (Graphics g = Graphics.FromImage(bitmap))
{
g.Clear(Color.White);
g.DrawBezier(new Pen(Color.Black),
0,
bitmap.Height - 1,
bitmap.Width / 4 * 3,
bitmap.Height / 4 * 3,
bitmap.Width / 4,
bitmap.Height / 4,
bitmap.Width - 1,
0);
}
// extract heights
for (int i=0; i<bitmap.Width; i++)
{
int j = bitmap.Height - 1;
for (; j>0; j--)
{
if (bitmap.GetPixel(i, j).R == 0)
{
break;
}
}
this.fadeHeights[i] = j;
}
}
}
#endregion
#region Slide Show/Hide
/// <summary>
/// Gets the Expando ready to start its show/hide animation
/// </summary>
protected internal void StartSlideAnimation()
{
this.animatingSlide = true;
this.slideEndHeight = this.CalcHeightAndLayout();
}
/// <summary>
/// Updates the next "frame" of a slide animation
/// </summary>
/// <param name="animationStepNum">The current step in the animation</param>
/// <param name="numAnimationSteps">The total number of steps in the animation</param>
protected internal void UpdateSlideAnimation(int animationStepNum, int numAnimationSteps)
{
// the percentage we need to adjust our height by
// double step = (1 / (double) numAnimationSteps) * animationStepNum;
// replacement by: Joel Holdsworth (joel@airwebreathe.org.uk)
// Paolo Messina (ppescher@hotmail.com)
// 05/06/2004
// v1.1
double step = (1.0 - Math.Cos(Math.PI * (double) animationStepNum / (double) numAnimationSteps)) / 2.0;
// set the height of the group
this.Height = this.expandedHeight + (int) ((this.slideEndHeight - this.expandedHeight) * step);
if (this.TaskPane != null)
{
this.TaskPane.DoLayout();
}
else
{
// draw the next frame
this.Invalidate();
}
}
/// <summary>
/// Gets the Expando to stop its animation
/// </summary>
protected internal void StopSlideAnimation()
{
this.animatingSlide = false;
// make sure we're the right height
this.Height = this.slideEndHeight;
this.slideEndHeight = -1;
this.DoLayout();
}
#endregion
#endregion
#region Controls
/// <summary>
/// Hides the specified Control
/// </summary>
/// <param name="control">The Control to hide</param>
public void HideControl(Control control)
{
this.HideControl(new Control[] {control});
}
#region modified by Lucas
/// <summary>
/// Checks wether the specified COntrol is hidden or not
/// </summary>
/// <param name="control">The Control to check</param>
public bool ControlHidden(Control control)
{
return (hiddenControls.Contains(control));
}
#endregion
/// <summary>
/// Hides the Controls contained in the specified array
/// </summary>
/// <param name="controls">The array Controls to hide</param>
public void HideControl(Control[] controls)
{
// don't bother if we are animating
//modified by Lucas to allow enabling then collapsed
if (this.Animating || this.Collapsed)
{
//return;
}
this.SuspendLayout();
// flag to check if we actually hid any controls
bool anyHidden = false;
foreach (Control control in controls)
{
// hide the control if we own it and it is not already hidden
if (this.Controls.Contains(control) && !this.hiddenControls.Contains(control))
{
//if (control.Visible)
//{
this.hiddenControls.Add(control);
if (!this.Collapsed)
anyHidden = true;
//}
control.Visible = false;
}
}
this.ResumeLayout(false);
// if we didn't hide any, get out of here
if (!anyHidden)
{
return;
}
//
if (this.beginUpdateCount > 0)
{
this.slideAnimationBatched = true;
return;
}
// are we able to animate?
if (!this.AutoLayout || !this.Animate)
{
// guess not
this.DoLayout();
}
else
{
if (this.animationHelper != null)
{
this.animationHelper.Dispose();
this.animationHelper = null;
}
this.animationHelper = new AnimationHelper(this, AnimationHelper.SlideAnimation);
this.animationHelper.StartAnimation();
}
}
/// <summary>
/// Shows the specified Control
/// </summary>
/// <param name="control">The Control to show</param>
public void ShowControl(Control control)
{
this.ShowControl(new Control[] {control});
}
/// <summary>
/// Shows the Controls contained in the specified array
/// </summary>
/// <param name="controls">The array Controls to show</param>
public void ShowControl(Control[] controls)
{
// don't bother if we are animating
//modified by Lucas to allow enabling then collapsed
if (this.Animating || this.Collapsed)
{
//return;
}
this.SuspendLayout();
// flag to check if any controls were shown
bool anyHidden = false;
foreach (Control control in controls)
{
// show the control if we own it and it is not already shown
if (this.Controls.Contains(control) && this.hiddenControls.Contains(control))
{
//if added by Lucas to allow enabling then collapsed
if(!this.Collapsed)
anyHidden = true;
control.Visible = true;
this.hiddenControls.Remove(control);
}
}
this.ResumeLayout(false);
// if we didn't show any, get out of here
if (!anyHidden)
{
return;
}
//
if (this.beginUpdateCount > 0)
{
this.slideAnimationBatched = true;
return;
}
// are we able to animate?
if (!this.AutoLayout || !this.Animate)
{
// guess not
this.DoLayout();
}
else
{
if (this.animationHelper != null)
{
this.animationHelper.Dispose();
this.animationHelper = null;
}
this.animationHelper = new AnimationHelper(this, AnimationHelper.SlideAnimation);
this.animationHelper.StartAnimation();
}
}
#endregion
#region Dispose
/// <summary>
/// Releases the unmanaged resources used by the Expando and
/// optionally releases the managed resources
/// </summary>
/// <param name="disposing">True to release both managed and unmanaged
/// resources; false to release only unmanaged resources</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
if (this.systemSettings != null)
{
this.systemSettings.Dispose();
this.systemSettings = null;
}
if (this.animationHelper != null)
{
this.animationHelper.Dispose();
this.animationHelper = null;
}
}
base.Dispose(disposing);
}
#endregion
#region Invalidation
/// <summary>
/// Invalidates the titlebar area
/// </summary>
protected void InvalidateTitleBar()
{
this.Invalidate(new Rectangle(0, 0, this.Width, this.headerHeight), false);
}
#endregion
#region ISupportInitialize Members
/// <summary>
/// Signals the object that initialization is starting
/// </summary>
public void BeginInit()
{
this.initialising = true;
}
/// <summary>
/// Signals the object that initialization is complete
/// </summary>
public void EndInit()
{
this.initialising = false;
this.DoLayout();
this.CalcAnimationHeights();
}
/// <summary>
/// Gets whether the Expando is currently initializing
/// </summary>
[Browsable(false)]
public bool Initialising
{
get
{
return this.initialising;
}
}
#endregion
#region Keys
/// <summary>
/// Processes a dialog key
/// </summary>
/// <param name="keyData">One of the Keys values that represents
/// the key to process</param>
/// <returns>true if the key was processed by the control;
/// otherwise, false</returns>
protected override bool ProcessDialogKey(Keys keyData)
{
if (this.UseDefaultTabHandling || this.Parent == null || !(this.Parent is TaskPane))
{
return base.ProcessDialogKey(keyData);
}
Keys key = keyData & Keys.KeyCode;
if (key != Keys.Tab)
{
switch (key)
{
case Keys.Left:
case Keys.Up:
case Keys.Right:
case Keys.Down:
{
if (this.ProcessArrowKey(((key == Keys.Right) ? true : (key == Keys.Down))))
{
return true;
}
break;
}
}
return base.ProcessDialogKey(keyData);
}
if (key == Keys.Tab)
{
if (this.ProcessTabKey(((keyData & Keys.Shift) == Keys.None)))
{
return true;
}
}
return base.ProcessDialogKey(keyData);
}
/// <summary>
/// Selects the next available control and makes it the active control
/// </summary>
/// <param name="forward">true to cycle forward through the controls in
/// the Expando; otherwise, false</param>
/// <returns>true if a control is selected; otherwise, false</returns>
protected virtual bool ProcessTabKey(bool forward)
{
if (forward)
{
if ((this.Focused && !this.Collapsed) || this.Items.Count == 0)
{
return base.SelectNextControl(this, forward, true, true, false);
}
else
{
return this.Parent.SelectNextControl(this.Items[this.Items.Count-1], forward, true, true, false);
}
}
else
{
if (this.Focused || this.Items.Count == 0 || this.Collapsed)
{
return this.Parent.SelectNextControl(this, forward, true, true, false);
}
else
{
this.Select();
return this.Focused;
}
}
}
/// <summary>
/// Selects the next available control and makes it the active control
/// </summary>
/// <param name="forward">true to cycle forward through the controls in
/// the Expando; otherwise, false</param>
/// <returns>true if a control is selected; otherwise, false</returns>
protected virtual bool ProcessArrowKey(bool forward)
{
if (forward)
{
if (this.Focused && !this.Collapsed)
{
return base.SelectNextControl(this, forward, true, true, false);
}
else if ((this.Items.Count > 0 && this.Items[this.Items.Count-1].Focused) || this.Collapsed)
{
int index = this.TaskPane.Expandos.IndexOf(this);
if (index < this.TaskPane.Expandos.Count-1)
{
this.TaskPane.Expandos[index+1].Select();
return this.TaskPane.Expandos[index+1].Focused;
}
else
{
return true;
}
}
}
else
{
if (this.Focused)
{
int index = this.TaskPane.Expandos.IndexOf(this);
if (index > 0)
{
return this.Parent.SelectNextControl(this, forward, true, true, false);
}
else
{
return true;
}
}
else if (this.Items.Count > 0)
{
if (this.Items[0].Focused)
{
this.Select();
return this.Focused;
}
else
{
return this.Parent.SelectNextControl(this.FindFocusedChild(), forward, true, true, false);
}
}
}
return false;
}
/// <summary>
/// Gets the control contained in the Expando that currently has focus
/// </summary>
/// <returns>The control contained in the Expando that currently has focus,
/// or null if no child controls have focus</returns>
protected Control FindFocusedChild()
{
if (this.Controls.Count == 0)
{
return null;
}
foreach (Control control in this.Controls)
{
if (control.ContainsFocus)
{
return control;
}
}
return null;
}
#endregion
#region Layout
/// <summary>
/// Prevents the Expando from drawing until the EndUpdate method is called
/// </summary>
public void BeginUpdate()
{
this.beginUpdateCount++;
}
/// <summary>
/// Resumes drawing of the Expando after drawing is suspended by the
/// BeginUpdate method
/// </summary>
public void EndUpdate()
{
this.beginUpdateCount = Math.Max(--this.beginUpdateCount, 0);
if (beginUpdateCount == 0)
{
if (this.slideAnimationBatched)
{
this.slideAnimationBatched = false;
if (this.Animate && this.AutoLayout)
{
if (this.animationHelper != null)
{
this.animationHelper.Dispose();
this.animationHelper = null;
}
this.animationHelper = new AnimationHelper(this, AnimationHelper.SlideAnimation);
this.animationHelper.StartAnimation();
}
else
{
this.DoLayout(true);
}
}
else
{
this.DoLayout(true);
}
}
}
/// <summary>
/// Forces the control to apply layout logic to child controls,
/// and adjusts the height of the Expando if necessary
/// </summary>
public void DoLayout()
{
this.DoLayout(true);
}
/// <summary>
/// Forces the control to apply layout logic to child controls,
/// and adjusts the height of the Expando if necessary
/// </summary>
public virtual void DoLayout(bool performRealLayout)
{
if (this.layout)
{
return;
}
this.layout = true;
// stop the layout engine
this.SuspendLayout();
// work out the height of the header section
// is there an image to display on the titlebar
if (this.titleImage != null)
{
// is the image bigger than the height of the titlebar
if (this.titleImage.Height > this.titleBarHeight)
{
this.headerHeight = this.titleImage.Height;
}
// is the image smaller than the height of the titlebar
else if (this.titleImage.Height < this.titleBarHeight)
{
this.headerHeight = this.titleBarHeight;
}
// is the image smaller than the current header height
else if (this.titleImage.Height < this.headerHeight)
{
this.headerHeight = this.titleImage.Height;
}
}
else
{
this.headerHeight = this.titleBarHeight;
}
// do we need to layout our items
if (this.AutoLayout)
{
Control c;
TaskItem ti;
Point p;
// work out how wide to make the controls, and where
// the top of the first control should be
int y = this.DisplayRectangle.Y + this.Padding.Top;
int width = this.PseudoClientRect.Width - this.Padding.Left - this.Padding.Right;
// for each control in our list...
for (int i=0; i<this.itemList.Count; i++)
{
c = (Control) this.itemList[i];
if (this.hiddenControls.Contains(c))
{
continue;
}
// set the starting point
p = new Point(this.Padding.Left, y);
// is the control a TaskItem? if so, we may
// need to take into account the margins
if (c is TaskItem)
{
ti = (TaskItem) c;
// only adjust the y co-ord if this isn't the first item
if (i > 0)
{
y += ti.Margin.Top;
p.Y = y;
}
// adjust and set the width and height
ti.Width = width;
ti.Height = ti.PreferredHeight;
}
else
{
y += this.systemSettings.TaskItem.Margin.Top;
p.Y = y;
}
// set the location of the control
c.Location = p;
// update the next starting point.
y += c.Height;
// is the control a TaskItem? if so, we may
// need to take into account the bottom margin
if (i < this.itemList.Count-1)
{
if (c is TaskItem)
{
ti = (TaskItem) c;
y += ti.Margin.Bottom;
}
else
{
y += this.systemSettings.TaskItem.Margin.Bottom;
}
}
}
// workout where the bottom of the Expando should be
y += this.Padding.Bottom + this.Border.Bottom;
// adjust the ExpandedHeight if they're not the same
if (y != this.ExpandedHeight)
{
this.ExpandedHeight = y;
// if we're not collapsed then we had better change
// our height as well
if (!this.Collapsed)
{
this.Height = this.ExpandedHeight;
// if we belong to a TaskPane then it needs to
// re-layout its Expandos
if (this.TaskPane != null)
{
this.TaskPane.DoLayout(true);
}
}
}
}
if (this.Collapsed)
{
this.Height = this.HeaderHeight;
}
// restart the layout engine
this.ResumeLayout(performRealLayout);
this.layout = false;
}
/// <summary>
/// Calculates the height that the Expando would be if a
/// call to DoLayout() were made
/// </summary>
/// <returns>The height that the Expando would be if a
/// call to DoLayout() were made</returns>
internal int CalcHeightAndLayout()
{
// stop the layout engine
this.SuspendLayout();
// work out the height of the header section
// is there an image to display on the titlebar
if (this.titleImage != null)
{
// is the image bigger than the height of the titlebar
if (this.titleImage.Height > this.titleBarHeight)
{
this.headerHeight = this.titleImage.Height;
}
// is the image smaller than the height of the titlebar
else if (this.titleImage.Height < this.titleBarHeight)
{
this.headerHeight = this.titleBarHeight;
}
// is the image smaller than the current header height
else if (this.titleImage.Height < this.headerHeight)
{
this.headerHeight = this.titleImage.Height;
}
}
else
{
this.headerHeight = this.titleBarHeight;
}
int y = -1;
// do we need to layout our items
if (this.AutoLayout)
{
Control c;
TaskItem ti;
Point p;
// work out how wide to make the controls, and where
// the top of the first control should be
y = this.DisplayRectangle.Y + this.Padding.Top;
int width = this.PseudoClientRect.Width - this.Padding.Left - this.Padding.Right;
// for each control in our list...
for (int i=0; i<this.itemList.Count; i++)
{
c = (Control) this.itemList[i];
if (this.hiddenControls.Contains(c))
{
continue;
}
// set the starting point
p = new Point(this.Padding.Left, y);
// is the control a TaskItem? if so, we may
// need to take into account the margins
if (c is TaskItem)
{
ti = (TaskItem) c;
// only adjust the y co-ord if this isn't the first item
if (i > 0)
{
y += ti.Margin.Top;
p.Y = y;
}
// adjust and set the width and height
ti.Width = width;
ti.Height = ti.PreferredHeight;
}
else
{
y += this.systemSettings.TaskItem.Margin.Top;
p.Y = y;
}
// set the location of the control
c.Location = p;
// update the next starting point.
y += c.Height;
// is the control a TaskItem? if so, we may
// need to take into account the bottom margin
if (i < this.itemList.Count-1)
{
if (c is TaskItem)
{
ti = (TaskItem) c;
y += ti.Margin.Bottom;
}
else
{
y += this.systemSettings.TaskItem.Margin.Bottom;
}
}
}
// workout where the bottom of the Expando should be
y += this.Padding.Bottom + this.Border.Bottom;
}
// restart the layout engine
this.ResumeLayout(true);
return y;
}
/// <summary>
/// Updates the layout of the Expandos items while in design mode, and
/// adds/removes itemss from the ControlCollection as necessary
/// </summary>
internal void UpdateItems()
{
if (this.Items.Count == this.Controls.Count)
{
// make sure the the items index in the ControlCollection
// are the same as in the ItemCollection (indexes in the
// ItemCollection may have changed due to the user moving
// them around in the editor)
this.MatchControlCollToItemColl();
return;
}
// were any items added
if (this.Items.Count > this.Controls.Count)
{
// add any extra items in the ItemCollection to the
// ControlCollection
for (int i=0; i<this.Items.Count; i++)
{
if (!this.Controls.Contains(this.Items[i]))
{
this.OnItemAdded(new ControlEventArgs(this.Items[i]));
}
}
}
else
{
// items were removed
int i = 0;
Control control;
// remove any extra items from the ControlCollection
while (i < this.Controls.Count)
{
control = (Control) this.Controls[i];
if (!this.Items.Contains(control))
{
this.OnItemRemoved(new ControlEventArgs(control));
}
else
{
i++;
}
}
}
this.Invalidate(true);
}
/// <summary>
/// Make sure the controls index in the ControlCollection
/// are the same as in the ItemCollection (indexes in the
/// ItemCollection may have changed due to the user moving
/// them around in the editor or calling ItemCollection.Move())
/// </summary>
internal void MatchControlCollToItemColl()
{
this.SuspendLayout();
for (int i=0; i<this.Items.Count; i++)
{
this.Controls.SetChildIndex(this.Items[i], i);
}
this.ResumeLayout(false);
this.DoLayout();
this.Invalidate(true);
}
/// <summary>
/// Performs the work of scaling the entire control and any child controls
/// </summary>
/// <param name="dx">The ratio by which to scale the control horizontally</param>
/// <param name="dy">The ratio by which to scale the control vertically</param>
[Obsolete]
protected override void ScaleCore(float dx, float dy)
{
// fix: need to adjust expanded height when scaling
// AndrewEames (andrew@cognex.com)
// 14/09/2005
// v3.3
base.ScaleCore(dx, dy);
this.expandedHeight = (int)(expandedHeight * dy);
}
#endregion
#endregion
#region Properties
#region Alignment
/// <summary>
/// Gets the alignment of the text in the title bar.
/// </summary>
[Browsable(false)]
public ContentAlignment TitleAlignment
{
get
{
if (this.SpecialGroup)
{
if (this.CustomHeaderSettings.SpecialAlignment != ContentAlignment.MiddleLeft)
{
return this.CustomHeaderSettings.SpecialAlignment;
}
return this.SystemSettings.Header.SpecialAlignment;
}
if (this.CustomHeaderSettings.NormalAlignment != ContentAlignment.MiddleLeft)
{
return this.CustomHeaderSettings.NormalAlignment;
}
return this.SystemSettings.Header.NormalAlignment;
}
}
#endregion
#region Animation
/// <summary>
/// Gets or sets whether the Expando is allowed to animate
/// </summary>
[Category("Appearance"),
DefaultValue(false),
Description("Specifies whether the Expando is allowed to animate")]
public bool Animate
{
get
{
return this.animate;
}
set
{
if (this.animate != value)
{
this.animate = value;
}
}
}
/// <summary>
/// Gets whether the Expando is currently animating
/// </summary>
[Browsable(false)]
public bool Animating
{
get
{
return (this.animatingFade || this.animatingSlide);
}
}
/// <summary>
/// Gets the Image used by the Expando while it is animating
/// </summary>
protected Image AnimationImage
{
get
{
return this.animationImage;
}
}
/// <summary>
/// Gets the height that the Expando should be at the end of its
/// slide animation
/// </summary>
protected int SlideEndHeight
{
get
{
return this.slideEndHeight;
}
}
#endregion
#region Border
/// <summary>
/// Gets the width of the border along each side of the Expando's pane.
/// </summary>
[Browsable(false)]
public Border Border
{
get
{
if (this.SpecialGroup)
{
if (this.CustomSettings.SpecialBorder != Border.Empty)
{
return this.CustomSettings.SpecialBorder;
}
return this.SystemSettings.Expando.SpecialBorder;
}
if (this.CustomSettings.NormalBorder != Border.Empty)
{
return this.CustomSettings.NormalBorder;
}
return this.SystemSettings.Expando.NormalBorder;
}
}
/// <summary>
/// Gets the color of the border along each side of the Expando's pane.
/// </summary>
[Browsable(false)]
public Color BorderColor
{
get
{
if (this.SpecialGroup)
{
if (this.CustomSettings.SpecialBorderColor != Color.Empty)
{
return this.CustomSettings.SpecialBorderColor;
}
return this.SystemSettings.Expando.SpecialBorderColor;
}
if (this.CustomSettings.NormalBorderColor != Color.Empty)
{
return this.CustomSettings.NormalBorderColor;
}
return this.SystemSettings.Expando.NormalBorderColor;
}
}
/// <summary>
/// Gets the width of the border along each side of the Expando's Title Bar.
/// </summary>
[Browsable(false)]
public Border TitleBorder
{
get
{
if (this.SpecialGroup)
{
if (this.CustomHeaderSettings.SpecialBorder != Border.Empty)
{
return this.CustomHeaderSettings.SpecialBorder;
}
return this.SystemSettings.Header.SpecialBorder;
}
if (this.CustomHeaderSettings.NormalBorder != Border.Empty)
{
return this.CustomHeaderSettings.NormalBorder;
}
return this.SystemSettings.Header.NormalBorder;
}
}
#endregion
#region Color
/// <summary>
/// Gets the background color of the titlebar
/// </summary>
[Browsable(false)]
public Color TitleBackColor
{
get
{
if (this.SpecialGroup)
{
if (this.CustomHeaderSettings.SpecialBackColor != Color.Empty &&
this.CustomHeaderSettings.SpecialBackColor != Color.Transparent)
{
return this.CustomHeaderSettings.SpecialBackColor;
}
else if (this.CustomHeaderSettings.SpecialBorderColor != Color.Empty)
{
return this.CustomHeaderSettings.SpecialBorderColor;
}
if (this.SystemSettings.Header.SpecialBackColor != Color.Transparent)
{
return this.systemSettings.Header.SpecialBackColor;
}
return this.SystemSettings.Header.SpecialBorderColor;
}
if (this.CustomHeaderSettings.NormalBackColor != Color.Empty &&
this.CustomHeaderSettings.NormalBackColor != Color.Transparent)
{
return this.CustomHeaderSettings.NormalBackColor;
}
else if (this.CustomHeaderSettings.NormalBorderColor != Color.Empty)
{
return this.CustomHeaderSettings.NormalBorderColor;
}
if (this.SystemSettings.Header.NormalBackColor != Color.Transparent)
{
return this.systemSettings.Header.NormalBackColor;
}
return this.SystemSettings.Header.NormalBorderColor;
}
}
/// <summary>
/// Gets whether any of the title bar's gradient colors are empty colors
/// </summary>
protected bool AnyCustomTitleGradientsEmpty
{
get
{
if (this.SpecialGroup)
{
if (this.CustomHeaderSettings.SpecialGradientStartColor == Color.Empty)
{
return true;
}
else if (this.CustomHeaderSettings.SpecialGradientEndColor == Color.Empty)
{
return true;
}
}
else
{
if (this.CustomHeaderSettings.NormalGradientStartColor == Color.Empty)
{
return true;
}
else if (this.CustomHeaderSettings.NormalGradientEndColor == Color.Empty)
{
return true;
}
}
return false;
}
}
#endregion
#region Client Rectangle
/// <summary>
/// Returns a fake Client Rectangle.
/// The rectangle takes into account the size of the titlebar
/// and borders (these are actually parts of the real
/// ClientRectangle)
/// </summary>
protected Rectangle PseudoClientRect
{
get
{
return new Rectangle(this.Border.Left,
this.HeaderHeight + this.Border.Top,
this.Width - this.Border.Left - this.Border.Right,
this.Height - this.HeaderHeight - this.Border.Top - this.Border.Bottom);
}
}
/// <summary>
/// Returns the height of the fake client rectangle
/// </summary>
protected int PseudoClientHeight
{
get
{
return this.Height - this.HeaderHeight - this.Border.Top - this.Border.Bottom;
}
}
#endregion
#region Display Rectangle
/// <summary>
/// Overrides DisplayRectangle so that docked controls
/// don't cover the titlebar or borders
/// </summary>
[Browsable(false)]
public override Rectangle DisplayRectangle
{
get
{
return new Rectangle(this.Border.Left,
this.HeaderHeight + this.Border.Top,
this.Width - this.Border.Left - this.Border.Right,
this.ExpandedHeight - this.HeaderHeight - this.Border.Top - this.Border.Bottom);
}
}
/// <summary>
/// Gets a rectangle that contains the titlebar area
/// </summary>
protected Rectangle TitleBarRectangle
{
get
{
return new Rectangle(0,
this.HeaderHeight - this.TitleBarHeight,
this.Width,
this.TitleBarHeight);
}
}
#endregion
#region Focus
/// <summary>
/// Gets or sets a value indicating whether the Expando should display
/// focus rectangles
/// </summary>
[Category("Appearance"),
DefaultValue(false),
Description("Determines whether the Expando should display a focus rectangle.")]
public new bool ShowFocusCues
{
get
{
return this.showFocusCues;
}
set
{
if (this.showFocusCues != value)
{
this.showFocusCues = value;
if (this.Focused)
{
this.InvalidateTitleBar();
}
}
}
}
/// <summary>
/// Gets or sets whether the Expando should use Windows
/// default Tab handling mechanism
/// </summary>
[Category("Appearance"),
DefaultValue(true),
Description("Specifies whether the Expando should use Windows default Tab handling mechanism")]
public bool UseDefaultTabHandling
{
get
{
return this.useDefaultTabHandling;
}
set
{
this.useDefaultTabHandling = value;
}
}
#endregion
#region Fonts
/// <summary>
/// Gets the color of the Title Bar's text.
/// </summary>
[Browsable(false)]
public Color TitleForeColor
{
get
{
if (this.SpecialGroup)
{
if (this.CustomHeaderSettings.SpecialTitleColor != Color.Empty)
{
return this.CustomHeaderSettings.SpecialTitleColor;
}
return this.SystemSettings.Header.SpecialTitleColor;
}
if (this.CustomHeaderSettings.NormalTitleColor != Color.Empty)
{
return this.CustomHeaderSettings.NormalTitleColor;
}
return this.SystemSettings.Header.NormalTitleColor;
}
}
/// <summary>
/// Gets the color of the Title Bar's text when highlighted.
/// </summary>
[Browsable(false)]
public Color TitleHotForeColor
{
get
{
if (this.SpecialGroup)
{
if (this.CustomHeaderSettings.SpecialTitleHotColor != Color.Empty)
{
return this.CustomHeaderSettings.SpecialTitleHotColor;
}
return this.SystemSettings.Header.SpecialTitleHotColor;
}
if (this.CustomHeaderSettings.NormalTitleHotColor != Color.Empty)
{
return this.CustomHeaderSettings.NormalTitleHotColor;
}
return this.SystemSettings.Header.NormalTitleHotColor;
}
}
/// <summary>
/// Gets the current color of the Title Bar's text, depending
/// on the current state of the Expando
/// </summary>
[Browsable(false)]
public Color TitleColor
{
get
{
if (this.FocusState == FocusStates.Mouse)
{
return this.TitleHotForeColor;
}
return this.TitleForeColor;
}
}
/// <summary>
/// Gets the font used to render the Title Bar's text.
/// </summary>
[Browsable(false)]
public Font TitleFont
{
get
{
if (this.CustomHeaderSettings.TitleFont != null)
{
return this.CustomHeaderSettings.TitleFont;
}
return this.SystemSettings.Header.TitleFont;
}
}
#endregion
#region Images
/// <summary>
/// Gets the expand/collapse arrow image currently displayed
/// in the title bar, depending on the current state of the Expando
/// </summary>
[Browsable(false)]
public Image ArrowImage
{
get
{
// fix: return null if the Expando isn't allowed to
// collapse (this will stop an expand/collapse
// arrow appearing on the titlebar
// dani kenan (dani_k@netvision.net.il)
// 11/10/2004
// v2.1
if(!this.CanCollapse)
{
return null;
}
if (this.SpecialGroup)
{
if (this.collapsed)
{
if (this.FocusState == FocusStates.None)
{
if (this.CustomHeaderSettings.SpecialArrowDown != null)
{
return this.CustomHeaderSettings.SpecialArrowDown;
}
return this.SystemSettings.Header.SpecialArrowDown;
}
else
{
if (this.CustomHeaderSettings.SpecialArrowDownHot != null)
{
return this.CustomHeaderSettings.SpecialArrowDownHot;
}
return this.SystemSettings.Header.SpecialArrowDownHot;
}
}
else
{
if (this.FocusState == FocusStates.None)
{
if (this.CustomHeaderSettings.SpecialArrowUp != null)
{
return this.CustomHeaderSettings.SpecialArrowUp;
}
return this.SystemSettings.Header.SpecialArrowUp;
}
else
{
if (this.CustomHeaderSettings.SpecialArrowUpHot != null)
{
return this.CustomHeaderSettings.SpecialArrowUpHot;
}
return this.SystemSettings.Header.SpecialArrowUpHot;
}
}
}
else
{
if (this.collapsed)
{
if (this.FocusState == FocusStates.None)
{
if (this.CustomHeaderSettings.NormalArrowDown != null)
{
return this.CustomHeaderSettings.NormalArrowDown;
}
return this.SystemSettings.Header.NormalArrowDown;
}
else
{
if (this.CustomHeaderSettings.NormalArrowDownHot != null)
{
return this.CustomHeaderSettings.NormalArrowDownHot;
}
return this.SystemSettings.Header.NormalArrowDownHot;
}
}
else
{
if (this.FocusState == FocusStates.None)
{
if (this.CustomHeaderSettings.NormalArrowUp != null)
{
return this.CustomHeaderSettings.NormalArrowUp;
}
return this.SystemSettings.Header.NormalArrowUp;
}
else
{
if (this.CustomHeaderSettings.NormalArrowUpHot != null)
{
return this.CustomHeaderSettings.NormalArrowUpHot;
}
return this.SystemSettings.Header.NormalArrowUpHot;
}
}
}
}
}
/// <summary>
/// Gets the width of the expand/collapse arrow image
/// currently displayed in the title bar
/// </summary>
protected int ArrowImageWidth
{
get
{
if (this.ArrowImage == null)
{
return 0;
}
return this.ArrowImage.Width;
}
}
/// <summary>
/// Gets the height of the expand/collapse arrow image
/// currently displayed in the title bar
/// </summary>
protected int ArrowImageHeight
{
get
{
if (this.ArrowImage == null)
{
return 0;
}
return this.ArrowImage.Height;
}
}
/// <summary>
/// The background image used for the Title Bar.
/// </summary>
[Browsable(false)]
public Image TitleBackImage
{
get
{
if (this.SpecialGroup)
{
if (this.CustomHeaderSettings.SpecialBackImage != null)
{
return this.CustomHeaderSettings.SpecialBackImage;
}
return this.SystemSettings.Header.SpecialBackImage;
}
if (this.CustomHeaderSettings.NormalBackImage != null)
{
return this.CustomHeaderSettings.NormalBackImage;
}
return this.SystemSettings.Header.NormalBackImage;
}
}
/// <summary>
/// Gets the height of the background image used for the Title Bar.
/// </summary>
protected int TitleBackImageHeight
{
get
{
return this.SystemSettings.Header.BackImageHeight;
}
}
/// <summary>
/// The image used on the left side of the Title Bar.
/// </summary>
[Category("Appearance"),
DefaultValue(null),
Description("The image used on the left side of the Title Bar.")]
public Image TitleImage
{
get
{
return this.titleImage;
}
set
{
this.titleImage = value;
this.DoLayout();
this.InvalidateTitleBar();
OnTitleImageChanged(new ExpandoEventArgs(this));
}
}
/// <summary>
/// The width of the image used on the left side of the Title Bar.
/// </summary>
protected int TitleImageWidth
{
get
{
if (this.TitleImage == null)
{
return 0;
}
return this.TitleImage.Width;
}
}
/// <summary>
/// The height of the image used on the left side of the Title Bar.
/// </summary>
protected int TitleImageHeight
{
get
{
if (this.TitleImage == null)
{
return 0;
}
return this.TitleImage.Height;
}
}
/// <summary>
/// Gets the Image that is used as a watermark in the Expando's
/// client area
/// </summary>
[Category("Appearance"),
DefaultValue(null),
Description("The Image used as a watermark in the client area of the Expando.")]
public Image Watermark
{
get
{
return this.watermark;
}
set
{
if (this.watermark != value)
{
this.watermark = value;
this.Invalidate();
OnWatermarkChanged(new ExpandoEventArgs(this));
}
}
}
/// <summary>
/// The background image used for the Expandos content area.
/// </summary>
[Browsable(false)]
public Image BackImage
{
get
{
if (this.SpecialGroup)
{
if (this.CustomSettings.SpecialBackImage != null)
{
return this.CustomSettings.SpecialBackImage;
}
return this.SystemSettings.Expando.SpecialBackImage;
}
if (this.CustomSettings.NormalBackImage != null)
{
return this.CustomSettings.NormalBackImage;
}
return this.SystemSettings.Expando.NormalBackImage;
}
}
#endregion
#region Items
/// <summary>
/// An Expando.ItemCollection representing the collection of
/// Controls contained within the Expando
/// </summary>
[Category("Behavior"),
DefaultValue(null),
Description("The Controls contained in the Expando"),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
Editor(typeof(ItemCollectionEditor), typeof(UITypeEditor))]
public Expando.ItemCollection Items
{
get
{
return this.itemList;
}
}
/// <summary>
/// A Control.ControlCollection representing the collection of
/// controls contained within the control
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new Control.ControlCollection Controls
{
get
{
return base.Controls;
}
}
#endregion
#region Layout
/// <summary>
/// Gets or sets whether the Expando will automagically layout its items
/// </summary>
[Bindable(true),
Category("Layout"),
DefaultValue(false),
Description("The AutoLayout property determines whether the Expando will automagically layout its items.")]
public bool AutoLayout
{
get
{
return this.autoLayout;
}
set
{
this.autoLayout = value;
if (this.autoLayout)
{
this.DoLayout();
}
}
}
#endregion
#region Padding
/// <summary>
/// Gets the amount of space between the border and items along
/// each side of the Expando.
/// </summary>
[Browsable(false)]
public new Padding Padding
{
get
{
if (this.SpecialGroup)
{
if (this.CustomSettings.SpecialPadding != Padding.Empty)
{
return this.CustomSettings.SpecialPadding;
}
return this.SystemSettings.Expando.SpecialPadding;
}
if (this.CustomSettings.NormalPadding != Padding.Empty)
{
return this.CustomSettings.NormalPadding;
}
return this.SystemSettings.Expando.NormalPadding;
}
}
/// <summary>
/// Gets the amount of space between the border and items along
/// each side of the Title Bar.
/// </summary>
[Browsable(false)]
public Padding TitlePadding
{
get
{
if (this.SpecialGroup)
{
if (this.CustomHeaderSettings.SpecialPadding != Padding.Empty)
{
return this.CustomHeaderSettings.SpecialPadding;
}
return this.SystemSettings.Header.SpecialPadding;
}
if (this.CustomHeaderSettings.NormalPadding != Padding.Empty)
{
return this.CustomHeaderSettings.NormalPadding;
}
return this.SystemSettings.Header.NormalPadding;
}
}
#endregion
#region Size
/// <summary>
/// Gets or sets the height and width of the control
/// </summary>
public new Size Size
{
get
{
return base.Size;
}
set
{
if (!this.Size.Equals(value))
{
if (!this.Animating)
{
this.Width = value.Width;
if (!this.Initialising)
{
this.ExpandedHeight = value.Height;
}
}
}
}
}
/// <summary>
/// Specifies whether the Size property should be
/// serialized at design time
/// </summary>
/// <returns>true if the Size property should be
/// serialized, false otherwise</returns>
private bool ShouldSerializeSize()
{
return this.TaskPane != null;
}
/// <summary>
/// Gets the height of the Expando in its expanded state
/// </summary>
[Bindable(true),
Category("Layout"),
DefaultValue(100),
Description("The height of the Expando in its expanded state.")]
public int ExpandedHeight
{
get
{
return this.expandedHeight;
}
set
{
this.expandedHeight = value;
this.CalcAnimationHeights();
if (!this.Collapsed && !this.Animating)
{
this.Height = this.expandedHeight;
if (this.TaskPane != null)
{
this.TaskPane.DoLayout();
}
}
}
}
/// <summary>
/// Gets the height of the header section of the Expando
/// </summary>
protected int HeaderHeight
{
get
{
return this.headerHeight;
}
}
/// <summary>
/// Gets the height of the titlebar
/// </summary>
protected int TitleBarHeight
{
get
{
return this.titleBarHeight;
}
}
#endregion
#region Special Groups
/// <summary>
/// Gets or sets whether the Expando should be rendered as a Special Group.
/// </summary>
[Bindable(true),
Category("Appearance"),
DefaultValue(false),
Description("The SpecialGroup property determines whether the Expando will be rendered as a SpecialGroup.")]
public bool SpecialGroup
{
get
{
return this.specialGroup;
}
set
{
this.specialGroup = value;
this.DoLayout();
if (this.specialGroup)
{
if (this.CustomSettings.SpecialBackColor != Color.Empty)
{
this.BackColor = this.CustomSettings.SpecialBackColor;
}
else
{
this.BackColor = this.SystemSettings.Expando.SpecialBackColor;
}
}
else
{
if (this.CustomSettings.NormalBackColor != Color.Empty)
{
this.BackColor = this.CustomSettings.NormalBackColor;
}
else
{
this.BackColor = this.SystemSettings.Expando.NormalBackColor;
}
}
this.Invalidate();
OnSpecialGroupChanged(new ExpandoEventArgs(this));
}
}
#endregion
#region State
/// <summary>
/// Gets or sets whether the Expando is collapsed.
/// </summary>
[Bindable(true),
Category("Appearance"),
DefaultValue(false),
Description("The Collapsed property determines whether the Expando is collapsed.")]
public bool Collapsed
{
get
{
return this.collapsed;
}
set
{
if (this.collapsed != value)
{
// if we're supposed to collapse, check if we can
if (value && !this.CanCollapse)
{
// looks like we can't so time to bail
return;
}
this.collapsed = value;
// only animate if we're allowed to, we're not in
// design mode and we're not initialising
if (this.Animate && !this.DesignMode && !this.Initialising)
{
if (this.animationHelper != null)
{
this.animationHelper.Dispose();
this.animationHelper = null;
}
this.animationHelper = new AnimationHelper(this, AnimationHelper.FadeAnimation);
this.OnStateChanged(new ExpandoEventArgs(this));
this.animationHelper.StartAnimation();
}
else
{
if (this.collapsed)
{
this.Collapse();
}
else
{
this.Expand();
}
// don't need to raise OnStateChanged as
// Collapse() or Expand() will do it for us
}
}
}
}
/* private bool m_Disabled = false;
/// <summary>
/// Gets or sets whether the Expando is able disabled
/// </summary>
[Category("Appearance"),
DefaultValue(false),
Description("The Disabled property determines whether the Expando is disabled.")]
public bool Disabled
{
get
{
return m_Disabled;
}
set
{
Disabled = value;
this.Visible = !value;
}
}*/
/// <summary>
/// Gets or sets whether the title bar is in a highlighted state.
/// </summary>
[Browsable(false)]
protected internal FocusStates FocusState
{
get
{
return this.focusState;
}
set
{
// fix: if the Expando isn't allowed to collapse,
// don't update the titlebar highlight
// dani kenan (dani_k@netvision.net.il)
// 11/10/2004
// v2.1
if (!this.CanCollapse)
{
value = FocusStates.None;
}
if (this.focusState != value)
{
this.focusState = value;
this.InvalidateTitleBar();
if (this.focusState == FocusStates.Mouse)
{
this.Cursor = Cursors.Hand;
}
else
{
this.Cursor = Cursors.Default;
}
}
}
}
/// <summary>
/// Gets or sets whether the Expando is able to collapse
/// </summary>
[Bindable(true),
Category("Behavior"),
DefaultValue(true),
Description("The CanCollapse property determines whether the Expando is able to collapse.")]
public bool CanCollapse
{
get
{
return this.canCollapse;
}
set
{
if (this.canCollapse != value)
{
this.canCollapse = value;
// if the Expando is collapsed and it's not allowed
// to collapse, then we had better expand it
if (!this.canCollapse && this.Collapsed)
{
this.Collapsed = false;
}
this.InvalidateTitleBar();
}
}
}
#endregion
#region System Settings
/// <summary>
/// Gets or sets the system settings for the Expando
/// </summary>
[Browsable(false)]
protected internal ExplorerBarInfo SystemSettings
{
get
{
return this.systemSettings;
}
set
{
// make sure we have a new value
if (this.systemSettings != value)
{
this.SuspendLayout();
// get rid of the old settings
if (this.systemSettings != null)
{
this.systemSettings.Dispose();
this.systemSettings = null;
}
// set the new settings
this.systemSettings = value;
this.titleBarHeight = this.systemSettings.Header.BackImageHeight;
// is there an image to display on the titlebar
if (this.titleImage != null)
{
// is the image bigger than the height of the titlebar
if (this.titleImage.Height > this.titleBarHeight)
{
this.headerHeight = this.titleImage.Height;
}
// is the image smaller than the height of the titlebar
else if (this.titleImage.Height < this.titleBarHeight)
{
this.headerHeight = this.titleBarHeight;
}
// is the image smaller than the current header height
else if (this.titleImage.Height < this.headerHeight)
{
this.headerHeight = this.titleImage.Height;
}
}
else
{
this.headerHeight = this.titleBarHeight;
}
if (this.SpecialGroup)
{
if (this.CustomSettings.SpecialBackColor != Color.Empty)
{
this.BackColor = this.CustomSettings.SpecialBackColor;
}
else
{
this.BackColor = this.SystemSettings.Expando.SpecialBackColor;
}
}
else
{
if (this.CustomSettings.NormalBackColor != Color.Empty)
{
this.BackColor = this.CustomSettings.NormalBackColor;
}
else
{
this.BackColor = this.SystemSettings.Expando.NormalBackColor;
}
}
// update the system settings for each TaskItem
for (int i=0; i<this.itemList.Count; i++)
{
Control control = (Control) this.itemList[i];
if (control is TaskItem)
{
((TaskItem) control).SystemSettings = this.systemSettings;
}
}
this.ResumeLayout(false);
// if our parent is not an TaskPane then re-layout the
// Expando (don't need to do this if our parent is a
// TaskPane as it will tell us when to do it)
if (this.TaskPane == null)
{
this.DoLayout();
}
}
}
}
/// <summary>
/// Gets the custom settings for the Expando
/// </summary>
[Category("Appearance"),
Description(""),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
TypeConverter(typeof(ExpandoInfoConverter))]
public ExpandoInfo CustomSettings
{
get
{
return this.customSettings;
}
}
/// <summary>
/// Gets the custom header settings for the Expando
/// </summary>
[Category("Appearance"),
Description(""),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
TypeConverter(typeof(HeaderInfoConverter))]
public HeaderInfo CustomHeaderSettings
{
get
{
return this.customHeaderSettings;
}
}
/// <summary>
/// Resets the custom settings to their default values
/// </summary>
public void ResetCustomSettings()
{
this.CustomSettings.SetDefaultEmptyValues();
this.CustomHeaderSettings.SetDefaultEmptyValues();
this.FireCustomSettingsChanged(EventArgs.Empty);
}
#endregion
#region TaskPane
/// <summary>
/// Gets or sets the TaskPane the Expando belongs to
/// </summary>
protected internal TaskPane TaskPane
{
get
{
return this.taskpane;
}
set
{
this.taskpane = value;
if (value != null)
{
this.SystemSettings = this.TaskPane.SystemSettings;
}
}
}
#endregion
#region Text
/// <summary>
/// Gets or sets the text displayed on the titlebar
/// </summary>
public override string Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
this.InvalidateTitleBar();
}
}
#endregion
#region Visible
/// <summary>
/// Gets or sets a value indicating whether the Expando is displayed
/// </summary>
public new bool Visible
{
get
{
return base.Visible;
}
set
{
// fix: TaskPane will now perform a layout if the
// Expando is to become invisible and the TaskPane
// is currently invisible
// Brian Nottingham (nottinbe@slu.edu)
// 22/12/2004
// v3.0
//if (base.Visible != value)
if (base.Visible != value || (!value && this.Parent != null && !this.Parent.Visible))
{
base.Visible = value;
if (this.TaskPane != null)
{
this.TaskPane.DoLayout();
}
}
}
}
#endregion
#endregion
#region Events
#region Controls
/// <summary>
/// Raises the ControlAdded event
/// </summary>
/// <param name="e">A ControlEventArgs that contains the event data</param>
protected override void OnControlAdded(ControlEventArgs e)
{
// don't do anything if we are animating
// (as we're probably the ones who added the control)
if (this.Animating)
{
return;
}
base.OnControlAdded(e);
// add the control to the ItemCollection if necessary
if (!this.Items.Contains(e.Control))
{
this.Items.Add(e.Control);
}
}
/// <summary>
/// Raises the ControlRemoved event
/// </summary>
/// <param name="e">A ControlEventArgs that contains the event data</param>
protected override void OnControlRemoved(ControlEventArgs e)
{
// don't do anything if we are animating
// (as we're probably the ones who removed the control)
if (this.Animating)
{
return;
}
base.OnControlRemoved(e);
// remove the control from the itemList
if (this.Items.Contains(e.Control))
{
this.Items.Remove(e.Control);
}
// update the layout of the controls
this.DoLayout();
}
#endregion
#region Custom Settings
/// <summary>
/// Raises the CustomSettingsChanged event
/// </summary>
/// <param name="e">An EventArgs that contains the event data</param>
internal void FireCustomSettingsChanged(EventArgs e)
{
this.titleBarHeight = this.TitleBackImageHeight;
// is there an image to display on the titlebar
if (this.titleImage != null)
{
// is the image bigger than the height of the titlebar
if (this.titleImage.Height > this.titleBarHeight)
{
this.headerHeight = this.titleImage.Height;
}
// is the image smaller than the height of the titlebar
else if (this.titleImage.Height < this.titleBarHeight)
{
this.headerHeight = this.titleBarHeight;
}
// is the image smaller than the current header height
else if (this.titleImage.Height < this.headerHeight)
{
this.headerHeight = this.titleImage.Height;
}
}
else
{
this.headerHeight = this.titleBarHeight;
}
if (this.SpecialGroup)
{
if (this.CustomSettings.SpecialBackColor != Color.Empty)
{
this.BackColor = this.CustomSettings.SpecialBackColor;
}
else
{
this.BackColor = this.SystemSettings.Expando.SpecialBackColor;
}
}
else
{
if (this.CustomSettings.NormalBackColor != Color.Empty)
{
this.BackColor = this.CustomSettings.NormalBackColor;
}
else
{
this.BackColor = this.SystemSettings.Expando.NormalBackColor;
}
}
this.DoLayout();
this.Invalidate(true);
this.OnCustomSettingsChanged(e);
}
/// <summary>
/// Raises the CustomSettingsChanged event
/// </summary>
/// <param name="e">An EventArgs that contains the event data</param>
protected virtual void OnCustomSettingsChanged(EventArgs e)
{
if (CustomSettingsChanged != null)
{
CustomSettingsChanged(this, e);
}
}
#endregion
#region Expando
/// <summary>
/// Raises the StateChanged event
/// </summary>
/// <param name="e">An ExpandoStateChangedEventArgs that contains the event data</param>
protected virtual void OnStateChanged(ExpandoEventArgs e)
{
if (StateChanged != null)
{
StateChanged(this, e);
}
}
/// <summary>
/// Raises the TitleImageChanged event
/// </summary>
/// <param name="e">An ExpandoEventArgs that contains the event data</param>
protected virtual void OnTitleImageChanged(ExpandoEventArgs e)
{
if (TitleImageChanged != null)
{
TitleImageChanged(this, e);
}
}
/// <summary>
/// Raises the SpecialGroupChanged event
/// </summary>
/// <param name="e">An ExpandoEventArgs that contains the event data</param>
protected virtual void OnSpecialGroupChanged(ExpandoEventArgs e)
{
if (SpecialGroupChanged != null)
{
SpecialGroupChanged(this, e);
}
}
/// <summary>
/// Raises the WatermarkChanged event
/// </summary>
/// <param name="e">An ExpandoEventArgs that contains the event data</param>
protected virtual void OnWatermarkChanged(ExpandoEventArgs e)
{
if (WatermarkChanged != null)
{
WatermarkChanged(this, e);
}
}
#endregion
#region Focus
/// <summary>
/// Raises the GotFocus event
/// </summary>
/// <param name="e">An EventArgs that contains the event data</param>
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
this.InvalidateTitleBar();
}
/// <summary>
/// Raises the LostFocus event
/// </summary>
/// <param name="e">An EventArgs that contains the event data</param>
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
this.InvalidateTitleBar();
}
#endregion
#region Items
/// <summary>
/// Raises the ItemAdded event
/// </summary>
/// <param name="e">A ControlEventArgs that contains the event data</param>
protected virtual void OnItemAdded(ControlEventArgs e)
{
// add the expando to the ControlCollection if it hasn't already
if (!this.Controls.Contains(e.Control))
{
this.Controls.Add(e.Control);
}
// check if the control is a TaskItem
if (e.Control is TaskItem)
{
TaskItem item = (TaskItem) e.Control;
// set anchor styles
item.Anchor = (AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right);
// tell the TaskItem who's its daddy...
item.Expando = this;
item.SystemSettings = this.systemSettings;
}
// update the layout of the controls
this.DoLayout();
//
if (ItemAdded != null)
{
ItemAdded(this, e);
}
}
/// <summary>
/// Raises the ItemRemoved event
/// </summary>
/// <param name="e">A ControlEventArgs that contains the event data</param>
protected virtual void OnItemRemoved(ControlEventArgs e)
{
// remove the control from the ControlCollection if it hasn't already
if (this.Controls.Contains(e.Control))
{
this.Controls.Remove(e.Control);
}
// update the layout of the controls
this.DoLayout();
//
if (ItemRemoved != null)
{
ItemRemoved(this, e);
}
}
#endregion
#region Keys
/// <summary>
/// Raises the KeyUp event
/// </summary>
/// <param name="e">A KeyEventArgs that contains the event data</param>
protected override void OnKeyUp(KeyEventArgs e)
{
// fix: should call OnKeyUp instead of OnKeyDown
// Simon Cropp (simonc@avanade.com)
// 14/09/2005
// v3.3
base.OnKeyUp(e);
if (e.KeyCode == Keys.Space || e.KeyCode == Keys.Enter)
{
this.Collapsed = !this.Collapsed;
}
}
#endregion
#region Location
/// <summary>
/// Raises the LocationChanged event
/// </summary>
/// <param name="e">An EventArgs that contains the event data</param>
protected override void OnLocationChanged(EventArgs e)
{
base.OnLocationChanged(e);
// sometimes the title image gets cropped (why???) if the
// expando is scrolled from off-screen to on-screen so we'll
// repaint the titlebar if the expando has a titlebar image
// and it is taller then the titlebar
if (this.TitleImage != null && this.TitleImageHeight > this.TitleBarHeight)
{
this.InvalidateTitleBar();
}
}
#endregion
#region Mouse
/// <summary>
/// Raises the MouseUp event
/// </summary>
/// <param name="e">A MouseEventArgs that contains the event data</param>
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
// was it the left mouse button
if (e.Button == MouseButtons.Left)
{
if (this.dragging)
{
this.Cursor = Cursors.Default;
this.dragging = false;
this.TaskPane.DropExpando(this);
}
else
{
// was it in the titlebar area
if (e.Y < this.HeaderHeight && e.Y > (this.HeaderHeight - this.TitleBarHeight))
{
// make sure that our taskPane (if we have one) is not animating
if (!this.Animating)
{
// collapse/expand the group
this.Collapsed = !this.Collapsed;
}
if (this.CanCollapse)
{
this.Select();
}
}
}
this.dragStart = Point.Empty;
}
}
/// <summary>
/// Raises the MouseDown event
/// </summary>
/// <param name="e">A MouseEventArgs that contains the event data</param>
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
// we're not doing anything here yet...
// but we might later :)
if (e.Button == MouseButtons.Left)
{
if (this.TaskPane != null && this.TaskPane.AllowExpandoDragging && !this.Animating)
{
this.dragStart = this.PointToScreen(new Point(e.X, e.Y));
}
}
}
/// <summary>
/// Raises the MouseMove event
/// </summary>
/// <param name="e">A MouseEventArgs that contains the event data</param>
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (e.Button == MouseButtons.Left && this.dragStart != Point.Empty)
{
Point p = this.PointToScreen(new Point(e.X, e.Y));
if (!this.dragging)
{
if (Math.Abs(this.dragStart.X - p.X) > 8 || Math.Abs(this.dragStart.Y - p.Y) > 8)
{
this.dragging = true;
this.FocusState = FocusStates.None;
}
}
if (this.dragging)
{
if (this.TaskPane.ClientRectangle.Contains(this.TaskPane.PointToClient(p)))
{
this.Cursor = Cursors.Default;
}
else
{
this.Cursor = Cursors.No;
}
this.TaskPane.UpdateDropPoint(p);
return;
}
}
// check if the mouse is moving in the titlebar area
if (e.Y < this.HeaderHeight && e.Y > (this.HeaderHeight - this.TitleBarHeight))
{
// change the cursor to a hand and highlight the titlebar
this.FocusState = FocusStates.Mouse;
}
else
{
// reset the titlebar highlight and cursor if they haven't already
this.FocusState = FocusStates.None;
}
}
/// <summary>
/// Raises the MouseLeave event
/// </summary>
/// <param name="e">An EventArgs that contains the event data</param>
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
// reset the titlebar highlight if it hasn't already
this.FocusState = FocusStates.None;
}
#endregion
#region Paint
/// <summary>
/// Raises the PaintBackground event
/// </summary>
/// <param name="e">A PaintEventArgs that contains the event data</param>
protected override void OnPaintBackground(PaintEventArgs e)
{
// we may have a solid background color, but the titlebar back image
// might have treansparent bits, so instead we draw our own
// transparent background (rather than getting windows to draw
// a solid background)
this.PaintTransparentBackground(e.Graphics, e.ClipRectangle);
// paint the titlebar background
if (this.TitleBarRectangle.IntersectsWith(e.ClipRectangle))
{
this.OnPaintTitleBarBackground(e.Graphics);
}
// only paint the border and "display rect" if we are not collapsed
if (this.Height != this.headerHeight)
{
if (this.PseudoClientRect.IntersectsWith(e.ClipRectangle))
{
this.OnPaintBorder(e.Graphics);
this.OnPaintDisplayRect(e.Graphics);
}
}
}
/// <summary>
/// Raises the Paint event
/// </summary>
/// <param name="e">A PaintEventArgs that contains the event data</param>
protected override void OnPaint(PaintEventArgs e)
{
// paint the titlebar
if (this.TitleBarRectangle.IntersectsWith(e.ClipRectangle))
{
this.OnPaintTitleBar(e.Graphics);
}
}
#region TitleBar
/// <summary>
/// Paints the title bar background
/// </summary>
/// <param name="g">The Graphics used to paint the titlebar</param>
protected void OnPaintTitleBarBackground(Graphics g)
{
// fix: draw grayscale titlebar when disabled
// Brad Jones (brad@bradjones.com)
// 20/08/2004
// v1.21
int y = 0;
// work out where the top of the titleBar actually is
if (this.HeaderHeight > this.TitleBarHeight)
{
y = this.HeaderHeight - this.TitleBarHeight;
}
if (this.CustomHeaderSettings.TitleGradient && !this.AnyCustomTitleGradientsEmpty)
{
// gradient titlebar
Color start = this.CustomHeaderSettings.NormalGradientStartColor;
if (this.SpecialGroup)
{
start = this.CustomHeaderSettings.SpecialGradientStartColor;
}
Color end = this.CustomHeaderSettings.NormalGradientEndColor;
if (this.SpecialGroup)
{
end = this.CustomHeaderSettings.SpecialGradientEndColor;
}
if (!this.Enabled)
{
// simulate saturation of 0
start = Color.FromArgb((int) (start.GetBrightness() * 255),
(int) (start.GetBrightness() * 255),
(int) (start.GetBrightness() * 255));
end = Color.FromArgb((int) (end.GetBrightness() * 255),
(int) (end.GetBrightness() * 255),
(int) (end.GetBrightness() * 255));
}
using (LinearGradientBrush brush = new LinearGradientBrush(this.TitleBarRectangle, start, end, LinearGradientMode.Horizontal))
{
// work out where the gradient starts
if (this.CustomHeaderSettings.GradientOffset > 0f && this.CustomHeaderSettings.GradientOffset < 1f)
{
ColorBlend colorBlend = new ColorBlend() ;
colorBlend.Colors = new Color [] {brush.LinearColors[0], brush.LinearColors[0], brush.LinearColors[1]} ;
colorBlend.Positions = new float [] {0f, this.CustomHeaderSettings.GradientOffset, 1f} ;
brush.InterpolationColors = colorBlend ;
}
// check if we need round corners
if (this.CustomHeaderSettings.TitleRadius > 0)
{
GraphicsPath path = new GraphicsPath();
// top
path.AddLine(this.TitleBarRectangle.Left + this.CustomHeaderSettings.TitleRadius,
this.TitleBarRectangle.Top,
this.TitleBarRectangle.Right - (this.CustomHeaderSettings.TitleRadius * 2) - 1,
this.TitleBarRectangle.Top);
// right corner
path.AddArc(this.TitleBarRectangle.Right - (this.CustomHeaderSettings.TitleRadius * 2) - 1,
this.TitleBarRectangle.Top,
this.CustomHeaderSettings.TitleRadius * 2,
this.CustomHeaderSettings.TitleRadius * 2,
270,
90);
// right
path.AddLine(this.TitleBarRectangle.Right,
this.TitleBarRectangle.Top + this.CustomHeaderSettings.TitleRadius,
this.TitleBarRectangle.Right,
this.TitleBarRectangle.Bottom);
// bottom
path.AddLine(this.TitleBarRectangle.Right,
this.TitleBarRectangle.Bottom,
this.TitleBarRectangle.Left - 1,
this.TitleBarRectangle.Bottom);
// left corner
path.AddArc(this.TitleBarRectangle.Left,
this.TitleBarRectangle.Top,
this.CustomHeaderSettings.TitleRadius * 2,
this.CustomHeaderSettings.TitleRadius * 2,
180,
90);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.FillPath(brush, path);
g.SmoothingMode = SmoothingMode.Default;
}
else
{
g.FillRectangle(brush, this.TitleBarRectangle);
}
}
}
else if (this.TitleBackImage != null)
{
// check if the system header background images have different
// RightToLeft values compared to what we do. if they are different,
// then we had better mirror them
if ((this.RightToLeft == RightToLeft.Yes && !this.SystemSettings.Header.RightToLeft) ||
(this.RightToLeft == RightToLeft.No && this.SystemSettings.Header.RightToLeft))
{
if (this.SystemSettings.Header.NormalBackImage != null)
{
this.SystemSettings.Header.NormalBackImage.RotateFlip(RotateFlipType.RotateNoneFlipX);
}
if (this.SystemSettings.Header.SpecialBackImage != null)
{
this.SystemSettings.Header.SpecialBackImage.RotateFlip(RotateFlipType.RotateNoneFlipX);
}
this.SystemSettings.Header.RightToLeft = (this.RightToLeft == RightToLeft.Yes);
}
if (this.Enabled)
{
if (this.SystemSettings.OfficialTheme)
{
// left edge
g.DrawImage(this.TitleBackImage,
new Rectangle(0, y, 5, this.TitleBarHeight),
new Rectangle(0, 0, 5, this.TitleBackImage.Height),
GraphicsUnit.Pixel);
// right edge
g.DrawImage(this.TitleBackImage,
new Rectangle(this.Width-5, y, 5, this.TitleBarHeight),
new Rectangle(this.TitleBackImage.Width-5, 0, 5, this.TitleBackImage.Height),
GraphicsUnit.Pixel);
// middle
g.DrawImage(this.TitleBackImage,
new Rectangle(5, y, this.Width-10, this.TitleBarHeight),
new Rectangle(5, 0, this.TitleBackImage.Width-10, this.TitleBackImage.Height),
GraphicsUnit.Pixel);
}
else
{
g.DrawImage(this.TitleBackImage, 0, y, this.Width, this.TitleBarHeight);
}
}
else
{
if (this.SystemSettings.OfficialTheme)
{
using (Image image = new Bitmap(this.Width, this.TitleBarHeight))
{
using (Graphics g2 = Graphics.FromImage(image))
{
// left edge
g2.DrawImage(this.TitleBackImage,
new Rectangle(0, y, 5, this.TitleBarHeight),
new Rectangle(0, 0, 5, this.TitleBackImage.Height),
GraphicsUnit.Pixel);
// right edge
g2.DrawImage(this.TitleBackImage,
new Rectangle(this.Width-5, y, 5, this.TitleBarHeight),
new Rectangle(this.TitleBackImage.Width-5, 0, 5, this.TitleBackImage.Height),
GraphicsUnit.Pixel);
// middle
g2.DrawImage(this.TitleBackImage,
new Rectangle(5, y, this.Width-10, this.TitleBarHeight),
new Rectangle(5, 0, this.TitleBackImage.Width-10, this.TitleBackImage.Height),
GraphicsUnit.Pixel);
}
ControlPaint.DrawImageDisabled(g, image, 0, y, this.TitleBackColor);
}
}
else
{
// first stretch the background image for ControlPaint.
using (Image image = new Bitmap(this.TitleBackImage, this.Width, this.TitleBarHeight))
{
ControlPaint.DrawImageDisabled(g, image, 0, y, this.TitleBackColor);
}
}
}
}
else
{
// single color titlebar
using (SolidBrush brush = new SolidBrush(this.TitleBackColor))
{
g.FillRectangle(brush, 0, y, this.Width, this.TitleBarHeight);
}
}
}
/// <summary>
/// Paints the title bar
/// </summary>
/// <param name="g">The Graphics used to paint the titlebar</param>
protected void OnPaintTitleBar(Graphics g)
{
int y = 0;
// work out where the top of the titleBar actually is
if (this.HeaderHeight > this.TitleBarHeight)
{
y = this.HeaderHeight - this.TitleBarHeight;
}
// draw the titlebar image if we have one
if (this.TitleImage != null)
{
int x = 0;
//int y = 0;
if (this.RightToLeft == RightToLeft.Yes)
{
x = this.Width - this.TitleImage.Width;
}
if (this.Enabled)
{
g.DrawImage(this.TitleImage, x, 0);
}
else
{
ControlPaint.DrawImageDisabled(g, TitleImage, x, 0, this.TitleBackColor);
}
}
// get which collapse/expand arrow we should draw
Image arrowImage = this.ArrowImage;
// get the titlebar's border and padding
Border border = this.TitleBorder;
Padding padding = this.TitlePadding;
// draw the arrow if we have one
if (arrowImage != null)
{
// work out where to position the arrow
int x = this.Width - arrowImage.Width - border.Right - padding.Right;
y += border.Top + padding.Top;
if (this.RightToLeft == RightToLeft.Yes)
{
x = border.Right + padding.Right;
}
// draw it...
if (this.Enabled)
{
g.DrawImage(arrowImage, x, y);
}
else
{
ControlPaint.DrawImageDisabled(g, arrowImage, x, y, this.TitleBackColor);
}
}
// check if we have any text to draw in the titlebar
if (this.Text.Length > 0)
{
// a rectangle that will contain our text
Rectangle rect = new Rectangle();
// work out the x coordinate
if (this.TitleImage == null)
{
rect.X = border.Left + padding.Left;
}
else
{
rect.X = this.TitleImage.Width + border.Left;
}
// work out the y coordinate
ContentAlignment alignment = this.TitleAlignment;
switch (alignment)
{
case ContentAlignment.MiddleLeft:
case ContentAlignment.MiddleCenter:
case ContentAlignment.MiddleRight: rect.Y = ((this.HeaderHeight - this.TitleFont.Height) / 2) + ((this.HeaderHeight - this.TitleBarHeight) / 2) + border.Top + padding.Top;
break;
case ContentAlignment.TopLeft:
case ContentAlignment.TopCenter:
case ContentAlignment.TopRight: rect.Y = (this.HeaderHeight - this.TitleBarHeight) + border.Top + padding.Top;
break;
case ContentAlignment.BottomLeft:
case ContentAlignment.BottomCenter:
case ContentAlignment.BottomRight: rect.Y = this.HeaderHeight - this.TitleFont.Height;
break;
}
// the height of the rectangle
rect.Height = this.TitleFont.Height;
// make sure the text stays inside the header
if (rect.Bottom > this.HeaderHeight)
{
rect.Y -= rect.Bottom - this.HeaderHeight;
}
// work out how wide the rectangle should be
if (arrowImage != null)
{
rect.Width = this.Width - arrowImage.Width - border.Right - padding.Right - rect.X;
}
else
{
rect.Width = this.Width - border.Right - padding.Right - rect.X;
}
// don't wrap the string, and use an ellipsis if
// the string is too big to fit the rectangle
StringFormat sf = new StringFormat();
sf.FormatFlags = StringFormatFlags.NoWrap;
sf.Trimming = StringTrimming.EllipsisCharacter;
// should the string be aligned to the left/center/right
switch (alignment)
{
case ContentAlignment.MiddleLeft:
case ContentAlignment.TopLeft:
case ContentAlignment.BottomLeft: sf.Alignment = StringAlignment.Near;
break;
case ContentAlignment.MiddleCenter:
case ContentAlignment.TopCenter:
case ContentAlignment.BottomCenter: sf.Alignment = StringAlignment.Center;
break;
case ContentAlignment.MiddleRight:
case ContentAlignment.TopRight:
case ContentAlignment.BottomRight: sf.Alignment = StringAlignment.Far;
break;
}
if (this.RightToLeft == RightToLeft.Yes)
{
sf.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
if (this.TitleImage == null)
{
rect.X = this.Width - rect.Width - border.Left - padding.Left;
}
else
{
rect.X = this.Width - rect.Width - this.TitleImage.Width - border.Left;
}
}
// draw the text
using (SolidBrush brush = new SolidBrush(this.TitleColor))
{
//g.DrawString(this.Text, this.TitleFont, brush, rect, sf);
if (this.Enabled)
{
g.DrawString(this.Text, this.TitleFont, brush, rect, sf);
}
else
{
ControlPaint.DrawStringDisabled(g, this.Text, this.TitleFont, SystemColors.ControlLightLight, rect, sf);
}
}
}
// check if windows will let us show a focus rectangle
// if we have focus
if (this.Focused && base.ShowFocusCues)
{
if (this.ShowFocusCues)
{
// for some reason, if CanCollapse is false the focus rectangle
// will be drawn 2 pixels higher than it should be, so move it down
if (!this.CanCollapse)
{
y += 2;
}
ControlPaint.DrawFocusRectangle(g, new Rectangle(2, y, this.Width - 4, this.TitleBarHeight - 3));
}
}
}
#endregion
#region DisplayRect
/// <summary>
/// Paints the "Display Rectangle". This is the dockable
/// area of the control (ie non-titlebar/border area). This is
/// also the same as the PseudoClientRect.
/// </summary>
/// <param name="g">The Graphics used to paint the DisplayRectangle</param>
protected void OnPaintDisplayRect(Graphics g)
{
// are we animating a fade
if (this.animatingFade && this.AnimationImage != null)
{
// calculate the transparency value for the animation image
float alpha = (((float) (this.Height - this.HeaderHeight)) / ((float) (this.ExpandedHeight - this.HeaderHeight)));
float[][] ptsArray = {new float[] {1, 0, 0, 0, 0},
new float[] {0, 1, 0, 0, 0},
new float[] {0, 0, 1, 0, 0},
new float[] {0, 0, 0, alpha, 0},
new float[] {0, 0, 0, 0, 1}};
ColorMatrix colorMatrix = new ColorMatrix(ptsArray);
ImageAttributes imageAttributes = new ImageAttributes();
imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
// work out how far up the animation image we need to start
int y = this.AnimationImage.Height - this.PseudoClientHeight - this.Border.Bottom;
// draw the image
g.DrawImage(this.AnimationImage,
new Rectangle(0, this.HeaderHeight, this.Width, this.Height - this.HeaderHeight),
0,
y,
this.AnimationImage.Width,
this.AnimationImage.Height - y,
GraphicsUnit.Pixel,
imageAttributes);
}
// are we animating a slide
else if (this.animatingSlide)
{
// check if we have a background image
if (this.BackImage != null)
{
// tile the backImage
using (TextureBrush brush = new TextureBrush(this.BackImage, WrapMode.Tile))
{
g.FillRectangle(brush, this.DisplayRectangle);
}
}
else
{
// just paint the area with a solid brush
using (SolidBrush brush = new SolidBrush(this.BackColor))
{
g.FillRectangle(brush,
this.Border.Left,
this.HeaderHeight + this.Border.Top,
this.Width - this.Border.Left - this.Border.Right,
this.Height - this.HeaderHeight - this.Border.Top - this.Border.Bottom);
}
}
}
else
{
// check if we have a background image
if (this.BackImage != null)
{
// tile the backImage
using (TextureBrush brush = new TextureBrush(this.BackImage, WrapMode.Tile))
{
g.FillRectangle(brush, this.DisplayRectangle);
}
}
else
{
// just paint the area with a solid brush
using (SolidBrush brush = new SolidBrush(this.BackColor))
{
g.FillRectangle(brush, this.DisplayRectangle);
}
}
if (this.Watermark != null)
{
// work out a rough location of where the watermark should go
Rectangle rect = new Rectangle(0, 0, this.Watermark.Width, this.Watermark.Height);
rect.X = this.PseudoClientRect.Right - this.Watermark.Width;
rect.Y = this.DisplayRectangle.Bottom - this.Watermark.Height;
// shrink the destination rect if necesary so that we
// can see all of the image
if (rect.X < 0)
{
rect.X = 0;
}
if (rect.Width > this.ClientRectangle.Width)
{
rect.Width = this.ClientRectangle.Width;
}
if (rect.Y < this.DisplayRectangle.Top)
{
rect.Y = this.DisplayRectangle.Top;
}
if (rect.Height > this.DisplayRectangle.Height)
{
rect.Height = this.DisplayRectangle.Height;
}
// draw the watermark
g.DrawImage(this.Watermark, rect);
}
}
}
#endregion
#region Borders
/// <summary>
/// Paints the borders
/// </summary>
/// <param name="g">The Graphics used to paint the border</param>
protected void OnPaintBorder(Graphics g)
{
// get the current border and border colors
Border border = this.Border;
Color c = this.BorderColor;
// check if we are currently animating a fade
if (this.animatingFade)
{
// calculate the alpha value for the color
int alpha = (int) (255 * (((float) (this.Height - this.HeaderHeight)) / ((float) (this.ExpandedHeight - this.HeaderHeight))));
// make sure it doesn't go past 0 or 255
if (alpha < 0)
{
alpha = 0;
}
else if (alpha > 255)
{
alpha = 255;
}
// update the color with the alpha value
c = Color.FromArgb(alpha, c.R, c.G, c.B);
}
// draw the borders
using (SolidBrush brush = new SolidBrush(c))
{
g.FillRectangle(brush, border.Left, this.HeaderHeight, this.Width-border.Left-border.Right, border.Top); // top border
g.FillRectangle(brush, 0, this.HeaderHeight, border.Left, this.Height-this.HeaderHeight); // left border
g.FillRectangle(brush, this.Width-border.Right, this.HeaderHeight, border.Right, this.Height-this.HeaderHeight); // right border
g.FillRectangle(brush, border.Left, this.Height-border.Bottom, this.Width-border.Left-border.Right, border.Bottom); // bottom border
}
}
#endregion
#region TransparentBackground
/// <summary>
/// Simulates a transparent background by getting the Expandos parent
/// to paint its background and foreground into the specified Graphics
/// at the specified location
/// </summary>
/// <param name="g">The Graphics used to paint the background</param>
/// <param name="clipRect">The Rectangle that represents the rectangle
/// in which to paint</param>
protected void PaintTransparentBackground(Graphics g, Rectangle clipRect)
{
// check if we have a parent
if (this.Parent != null)
{
// convert the clipRects coordinates from ours to our parents
clipRect.Offset(this.Location);
PaintEventArgs e = new PaintEventArgs(g, clipRect);
// save the graphics state so that if anything goes wrong
// we're not fubar
GraphicsState state = g.Save();
try
{
// move the graphics object so that we are drawing in
// the correct place
g.TranslateTransform((float) -this.Location.X, (float) -this.Location.Y);
// draw the parents background and foreground
this.InvokePaintBackground(this.Parent, e);
this.InvokePaint(this.Parent, e);
return;
}
finally
{
// reset everything back to where they were before
g.Restore(state);
clipRect.Offset(-this.Location.X, -this.Location.Y);
}
}
// we don't have a parent, so fill the rect with
// the default control color
g.FillRectangle(SystemBrushes.Control, clipRect);
}
#endregion
#endregion
#region Parent
/// <summary>
/// Raises the ParentChanged event
/// </summary>
/// <param name="e">An EventArgs that contains the event data</param>
protected override void OnParentChanged(EventArgs e)
{
if (this.Parent == null)
{
this.TaskPane = null;
}
else if (this.Parent is TaskPane)
{
this.TaskPane = (TaskPane) this.Parent;
this.Location = this.TaskPane.CalcExpandoLocation(this);
}
base.OnParentChanged(e);
}
#endregion
#region Size
/// <summary>
/// Raises the SizeChanged event
/// </summary>
/// <param name="e">An EventArgs that contains the event data</param>
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
// if we are currently animating and the width of the
// group has changed (eg. due to a scrollbar on the
// TaskPane appearing/disappearing), get a new image
// to use for the animation. (if we were to continue to
// use the old image it would be shrunk or stretched making
// the animation look wierd)
if (this.Animating && this.Width != this.oldWidth)
{
// if the width or height of the group is zero it probably
// means that our parent form has been minimized so we should
// immediately stop animating
if (this.Width == 0)
{
this.animationHelper.StopAnimation();
}
else
{
this.oldWidth = this.Width;
if (this.AnimationImage != null)
{
// get the new animationImage
this.animationImage = this.GetFadeAnimationImage();
}
}
}
// check if the width has changed. if it has re-layout
// the group so that the TaskItems can resize themselves
// if neccessary
else if (this.Width != this.oldWidth)
{
this.oldWidth = this.Width;
this.DoLayout();
}
}
#endregion
#endregion
#region ItemCollection
/// <summary>
/// Represents a collection of Control objects
/// </summary>
public class ItemCollection : CollectionBase
{
#region Class Data
/// <summary>
/// The Expando that owns this ControlCollection
/// </summary>
private Expando owner;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the Expando.ItemCollection class
/// </summary>
/// <param name="owner">An Expando representing the expando that owns
/// the Control collection</param>
public ItemCollection(Expando owner) : base()
{
if (owner == null)
{
throw new ArgumentNullException("owner");
}
this.owner = owner;
}
#endregion
#region Methods
/// <summary>
/// Adds the specified control to the control collection
/// </summary>
/// <param name="value">The Control to add to the control collection</param>
public void Add(Control value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
this.List.Add(value);
this.owner.Controls.Add(value);
this.owner.OnItemAdded(new ControlEventArgs(value));
}
/// <summary>
/// Adds an array of control objects to the collection
/// </summary>
/// <param name="controls">An array of Control objects to add
/// to the collection</param>
public void AddRange(Control[] controls)
{
if (controls == null)
{
throw new ArgumentNullException("controls");
}
for (int i=0; i<controls.Length; i++)
{
this.Add(controls[i]);
}
}
/// <summary>
/// Removes all controls from the collection
/// </summary>
public new void Clear()
{
while (this.Count > 0)
{
this.RemoveAt(0);
}
}
/// <summary>
/// Determines whether the specified control is a member of the
/// collection
/// </summary>
/// <param name="control">The Control to locate in the collection</param>
/// <returns>true if the Control is a member of the collection;
/// otherwise, false</returns>
public bool Contains(Control control)
{
if (control == null)
{
throw new ArgumentNullException("control");
}
return (this.IndexOf(control) != -1);
}
/// <summary>
/// Retrieves the index of the specified control in the control
/// collection
/// </summary>
/// <param name="control">The Control to locate in the collection</param>
/// <returns>A zero-based index value that represents the position
/// of the specified Control in the Expando.ItemCollection</returns>
public int IndexOf(Control control)
{
if (control == null)
{
throw new ArgumentNullException("control");
}
for (int i=0; i<this.Count; i++)
{
if (this[i] == control)
{
return i;
}
}
return -1;
}
/// <summary>
/// Removes the specified control from the control collection
/// </summary>
/// <param name="value">The Control to remove from the
/// Expando.ItemCollection</param>
public void Remove(Control value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
this.List.Remove(value);
this.owner.Controls.Remove(value);
this.owner.OnItemRemoved(new ControlEventArgs(value));
}
/// <summary>
/// Removes a control from the control collection at the
/// specified indexed location
/// </summary>
/// <param name="index">The index value of the Control to
/// remove</param>
public new void RemoveAt(int index)
{
this.Remove(this[index]);
}
/// <summary>
/// Moves the specified control to the specified indexed location
/// in the control collection
/// </summary>
/// <param name="value">The control to be moved</param>
/// <param name="index">The indexed location in the control collection
/// that the specified control will be moved to</param>
public void Move(Control value, int index)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
// make sure the index is within range
if (index < 0)
{
index = 0;
}
else if (index > this.Count)
{
index = this.Count;
}
// don't go any further if the expando is already
// in the desired position or we don't contain it
if (!this.Contains(value) || this.IndexOf(value) == index)
{
return;
}
this.List.Remove(value);
// if the index we're supposed to move the expando to
// is now greater to the number of expandos contained,
// add it to the end of the list, otherwise insert it at
// the specified index
if (index > this.Count)
{
this.List.Add(value);
}
else
{
this.List.Insert(index, value);
}
// re-layout the controls
this.owner.MatchControlCollToItemColl();
}
/// <summary>
/// Moves the specified control to the top of the control collection
/// </summary>
/// <param name="value">The control to be moved</param>
public void MoveToTop(Control value)
{
this.Move(value, 0);
}
/// <summary>
/// Moves the specified control to the bottom of the control collection
/// </summary>
/// <param name="value">The control to be moved</param>
public void MoveToBottom(Control value)
{
this.Move(value, this.Count);
}
#endregion
#region Properties
/// <summary>
/// The Control located at the specified index location within
/// the control collection
/// </summary>
/// <param name="index">The index of the control to retrieve
/// from the control collection</param>
public virtual Control this[int index]
{
get
{
return this.List[index] as Control;
}
}
#endregion
}
#endregion
#region ItemCollectionEditor
/// <summary>
/// A custom CollectionEditor for editing ItemCollections
/// </summary>
internal class ItemCollectionEditor : CollectionEditor
{
/// <summary>
/// Initializes a new instance of the CollectionEditor class
/// using the specified collection type
/// </summary>
/// <param name="type"></param>
public ItemCollectionEditor(Type type) : base(type)
{
}
/// <summary>
/// Edits the value of the specified object using the specified
/// service provider and context
/// </summary>
/// <param name="context">An ITypeDescriptorContext that can be
/// used to gain additional context information</param>
/// <param name="isp">A service provider object through which
/// editing services can be obtained</param>
/// <param name="value">The object to edit the value of</param>
/// <returns>The new value of the object. If the value of the
/// object has not changed, this should return the same object
/// it was passed</returns>
public override object EditValue(ITypeDescriptorContext context, IServiceProvider isp, object value)
{
Expando originalControl = (Expando) context.Instance;
object returnObject = base.EditValue(context, isp, value);
originalControl.UpdateItems();
return returnObject;
}
/// <summary>
/// Gets the data types that this collection editor can contain
/// </summary>
/// <returns>An array of data types that this collection can contain</returns>
protected override Type[] CreateNewItemTypes()
{
return new Type[] {typeof(TaskItem),
typeof(Button),
typeof(CheckBox),
typeof(CheckedListBox),
typeof(ComboBox),
typeof(DateTimePicker),
typeof(Label),
typeof(LinkLabel),
typeof(ListBox),
typeof(ListView),
typeof(Panel),
typeof(ProgressBar),
typeof(RadioButton),
typeof(TabControl),
typeof(TextBox),
typeof(TreeView)};
}
/// <summary>
/// Creates a new instance of the specified collection item type
/// </summary>
/// <param name="itemType">The type of item to create</param>
/// <returns>A new instance of the specified object</returns>
protected override object CreateInstance(Type itemType)
{
// if the item we're supposed to create is one of the
// types that doesn't correctly draw themed borders
// during animation, substitute it for our customised
// versions which will.
if (itemType == typeof(TextBox))
{
itemType = typeof(XPTextBox);
}
else if (itemType == typeof(CheckedListBox))
{
itemType = typeof(XPCheckedListBox);
}
else if (itemType == typeof(ListBox))
{
itemType = typeof(XPListBox);
}
else if (itemType == typeof(ListView))
{
itemType = typeof(XPListView);
}
else if (itemType == typeof(TreeView))
{
itemType = typeof(XPTreeView);
}
else if (itemType == typeof(DateTimePicker))
{
itemType = typeof(XPDateTimePicker);
}
return base.CreateInstance(itemType);
}
}
#endregion
#region AnimationPanel
/// <summary>
/// An extremely stripped down version of an Expando that an
/// Expando can use instead of itself to get an image of its
/// "client area" and child controls
/// </summary>
internal class AnimationPanel : Panel
{
#region Class Data
/// <summary>
/// The height of the header section
/// (includes titlebar and title image)
/// </summary>
protected int headerHeight;
/// <summary>
/// The border around the "client area"
/// </summary>
protected Border border;
/// <summary>
/// The background image displayed in the control
/// </summary>
protected Image backImage;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the AnimationPanel class with default settings
/// </summary>
public AnimationPanel() : base()
{
this.headerHeight = 0;
this.border = new Border();
this.backImage = null;
}
#endregion
#region Properties
/// <summary>
/// Overrides AutoScroll to disable scrolling
/// </summary>
public new bool AutoScroll
{
get
{
return false;
}
set
{
}
}
/// <summary>
/// Gets or sets the height of the header section of the Expando
/// </summary>
public int HeaderHeight
{
get
{
return this.headerHeight;
}
set
{
this.headerHeight = value;
}
}
/// <summary>
/// Gets or sets the border around the "client area"
/// </summary>
public Border Border
{
get
{
return this.border;
}
set
{
this.border = value;
}
}
/// <summary>
/// Gets or sets the background image displayed in the control
/// </summary>
public Image BackImage
{
get
{
return this.backImage;
}
set
{
this.backImage = value;
}
}
/// <summary>
/// Overrides DisplayRectangle so that docked controls
/// don't cover the titlebar or borders
/// </summary>
public override Rectangle DisplayRectangle
{
get
{
return new Rectangle(this.Border.Left,
this.HeaderHeight + this.Border.Top,
this.Width - this.Border.Left - this.Border.Right,
this.Height - this.HeaderHeight - this.Border.Top - this.Border.Bottom);
}
}
#endregion
#region Events
/// <summary>
/// Raises the Paint event
/// </summary>
/// <param name="e">A PaintEventArgs that contains the event data</param>
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (this.BackImage != null)
{
e.Graphics.DrawImageUnscaled(this.BackImage, 0, 0);
}
}
#endregion
}
#endregion
#region AnimationHelper
/// <summary>
/// A class that helps Expandos animate
/// </summary>
public class AnimationHelper : IDisposable
{
#region Class Data
/// <summary>
/// The number of frames in an animation
/// </summary>
public static readonly int NumAnimationFrames = 23;
/// <summary>
/// Specifes that a fade animation is to be performed
/// </summary>
public static int FadeAnimation = 1;
/// <summary>
/// Specifes that a slide animation is to be performed
/// </summary>
public static int SlideAnimation = 2;
/// <summary>
/// The type of animation to perform
/// </summary>
private int animationType;
/// <summary>
/// The Expando to animate
/// </summary>
private Expando expando;
/// <summary>
/// The current frame in animation
/// </summary>
private int animationStepNum;
/// <summary>
/// The number of frames in the animation
/// </summary>
private int numAnimationSteps;
/// <summary>
/// The amount of time each frame is shown (in milliseconds)
/// </summary>
private int animationFrameInterval;
/// <summary>
/// Specifies whether an animation is being performed
/// </summary>
private bool animating;
/// <summary>
/// A timer that notifies the helper when the next frame is due
/// </summary>
private System.Windows.Forms.Timer animationTimer;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the AnimationHelper class with the specified settings
/// </summary>
/// <param name="expando">The Expando to be animated</param>
/// <param name="animationType">The type of animation to perform</param>
public AnimationHelper(Expando expando, int animationType)
{
this.expando = expando;
this.animationType = animationType;
this.animating = false;
this.numAnimationSteps = NumAnimationFrames;
this.animationFrameInterval = 10;
// I know that this isn't the best way to do this, but I
// haven't quite worked out how to do it with threads so
// this will have to do for the moment
this.animationTimer = new System.Windows.Forms.Timer();
this.animationTimer.Tick += new EventHandler(this.animationTimer_Tick);
this.animationTimer.Interval = this.animationFrameInterval;
}
#endregion
#region Methods
/// <summary>
/// Releases all resources used by the AnimationHelper
/// </summary>
public void Dispose()
{
if (this.animationTimer != null)
{
this.animationTimer.Stop();
this.animationTimer.Dispose();
this.animationTimer = null;
}
this.expando = null;
}
/// <summary>
/// Starts the Expando collapse/expand animation
/// </summary>
public void StartAnimation()
{
// don't bother going any further if we are already animating
if (this.Animating)
{
return;
}
this.animationStepNum = 0;
// tell the expando to get ready to animate
if (this.AnimationType == FadeAnimation)
{
this.expando.StartFadeAnimation();
}
else
{
this.expando.StartSlideAnimation();
}
// start the animation timer
this.animationTimer.Start();
}
/// <summary>
/// Updates the animation for the Expando
/// </summary>
protected void PerformAnimation()
{
// if we have more animation steps to perform
if (this.animationStepNum < this.numAnimationSteps)
{
// update the animation step number
this.animationStepNum++;
// tell the animating expando to update the animation
if (this.AnimationType == FadeAnimation)
{
this.expando.UpdateFadeAnimation(this.animationStepNum, this.numAnimationSteps);
}
else
{
this.expando.UpdateSlideAnimation(this.animationStepNum, this.numAnimationSteps);
}
}
else
{
this.StopAnimation();
}
}
/// <summary>
/// Stops the Expando collapse/expand animation
/// </summary>
public void StopAnimation()
{
// stop the animation
this.animationTimer.Stop();
this.animationTimer.Dispose();
if (this.AnimationType == FadeAnimation)
{
this.expando.StopFadeAnimation();
}
else
{
this.expando.StopSlideAnimation();
}
}
#endregion
#region Properties
/// <summary>
/// Gets the Expando that is te be animated
/// </summary>
public Expando Expando
{
get
{
return this.expando;
}
}
/// <summary>
/// Gets or sets the number of steps that are needed for the Expando
/// to get from fully expanded to fully collapsed, or visa versa
/// </summary>
public int NumAnimationSteps
{
get
{
return this.numAnimationSteps;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("value", "NumAnimationSteps must be at least 0");
}
// only change this if we are not currently animating
// (if we are animating, changing this could cause things
// to screw up big time)
if (!this.animating)
{
this.numAnimationSteps = value;
}
}
}
/// <summary>
/// Gets or sets the number of milliseconds that each "frame"
/// of the animation stays on the screen
/// </summary>
public int AnimationFrameInterval
{
get
{
return this.animationFrameInterval;
}
set
{
this.animationFrameInterval = value;
}
}
/// <summary>
/// Gets whether the Expando is currently animating
/// </summary>
public bool Animating
{
get
{
return this.animating;
}
}
/// <summary>
/// Gets the type of animation to perform
/// </summary>
public int AnimationType
{
get
{
return this.animationType;
}
}
#endregion
#region Events
/// <summary>
/// Event handler for the animation timer tick event
/// </summary>
/// <param name="sender">The object that fired the event</param>
/// <param name="e">An EventArgs that contains the event data</param>
private void animationTimer_Tick(object sender, EventArgs e)
{
// do the next bit of the aniation
this.PerformAnimation();
}
#endregion
}
#endregion
#region ExpandoSurrogate
/// <summary>
/// A class that is serialized instead of an Expando (as
/// Expandos contain objects that cause serialization problems)
/// </summary>
[Serializable()]
public class ExpandoSurrogate : ISerializable
{
#region Class Data
/// <summary>
/// See Expando.Name. This member is not intended to be used
/// directly from your code.
/// </summary>
public string Name;
/// <summary>
/// See Expando.Text. This member is not intended to be used
/// directly from your code.
/// </summary>
public string Text;
/// <summary>
/// See Expando.Size. This member is not intended to be used
/// directly from your code.
/// </summary>
public Size Size;
/// <summary>
/// See Expando.Location. This member is not intended to be used
/// directly from your code.
/// </summary>
public Point Location;
/// <summary>
/// See Expando.BackColor. This member is not intended to be used
/// directly from your code.
/// </summary>
public string BackColor;
/// <summary>
/// See Expando.ExpandedHeight. This member is not intended to be used
/// directly from your code.
/// </summary>
public int ExpandedHeight;
/// <summary>
/// See Expando.CustomSettings. This member is not intended to be used
/// directly from your code.
/// </summary>
public ExpandoInfo.ExpandoInfoSurrogate CustomSettings;
/// <summary>
/// See Expando.CustomHeaderSettings. This member is not intended to be used
/// directly from your code.
/// </summary>
public HeaderInfo.HeaderInfoSurrogate CustomHeaderSettings;
/// <summary>
/// See Expando.Animate. This member is not intended to be used
/// directly from your code.
/// </summary>
public bool Animate;
/// <summary>
/// See Expando.ShowFocusCues. This member is not intended to be used
/// directly from your code.
/// </summary>
public bool ShowFocusCues;
/// <summary>
/// See Expando.Collapsed. This member is not intended to be used
/// directly from your code.
/// </summary>
public bool Collapsed;
/// <summary>
/// See Expando.CanCollapse. This member is not intended to be used
/// directly from your code.
/// </summary>
public bool CanCollapse;
/// <summary>
/// See Expando.SpecialGroup. This member is not intended to be used
/// directly from your code.
/// </summary>
public bool SpecialGroup;
/// <summary>
/// See Expando.TitleImage. This member is not intended to be used
/// directly from your code.
/// </summary>
[XmlElement("TitleImage", typeof(Byte[]), DataType="base64Binary")]
public byte[] TitleImage;
/// <summary>
/// See Expando.Watermark. This member is not intended to be used
/// directly from your code.
/// </summary>
[XmlElement("Watermark", typeof(Byte[]), DataType="base64Binary")]
public byte[] Watermark;
/// <summary>
/// See Expando.Enabled. This member is not intended to be used
/// directly from your code.
/// </summary>
public bool Enabled;
/// <summary>
/// See Expando.Visible. This member is not intended to be used
/// directly from your code.
/// </summary>
public bool Visible;
/// <summary>
/// See Expando.AutoLayout. This member is not intended to be used
/// directly from your code.
/// </summary>
public bool AutoLayout;
/// <summary>
/// See Expando.Anchor. This member is not intended to be used
/// directly from your code.
/// </summary>
public AnchorStyles Anchor;
/// <summary>
/// See Expando.Dock. This member is not intended to be used
/// directly from your code.
/// </summary>
public DockStyle Dock;
/// <summary>
/// See Font.Name. This member is not intended to be used
/// directly from your code.
/// </summary>
public string FontName;
/// <summary>
/// See Font.Size. This member is not intended to be used
/// directly from your code.
/// </summary>
public float FontSize;
/// <summary>
/// See Font.Style. This member is not intended to be used
/// directly from your code.
/// </summary>
public FontStyle FontDecoration;
/// <summary>
/// See Expando.Items. This member is not intended to be used
/// directly from your code.
/// </summary>
[XmlArray("Items"), XmlArrayItem("TaskItemSurrogate", typeof(TaskItem.TaskItemSurrogate))]
public ArrayList Items;
/// <summary>
/// See Control.Tag. This member is not intended to be used
/// directly from your code.
/// </summary>
[XmlElementAttribute("Tag", typeof(Byte[]), DataType="base64Binary")]
public byte[] Tag;
/// <summary>
/// Version number of the surrogate. This member is not intended
/// to be used directly from your code.
/// </summary>
public int Version = 3300;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the ExpandoSurrogate class with default settings
/// </summary>
public ExpandoSurrogate()
{
this.Name = null;
this.Text = null;
this.Size = Size.Empty;
this.Location = Point.Empty;
this.BackColor = ThemeManager.ConvertColorToString(SystemColors.Control);
this.ExpandedHeight = -1;
this.CustomSettings = null;
this.CustomHeaderSettings = null;
this.Animate = false;
this.ShowFocusCues = false;
this.Collapsed = false;
this.CanCollapse = true;
this.SpecialGroup = false;
this.TitleImage = new byte[0];
this.Watermark = new byte[0];
this.Enabled = true;
this.Visible = true;
this.AutoLayout = false;
this.Anchor = AnchorStyles.None;
this.Dock = DockStyle.None;
this.FontName = "Tahoma";
this.FontSize = 8.25f;
this.FontDecoration = FontStyle.Regular;
this.Items = new ArrayList();
this.Tag = new byte[0];
}
#endregion
#region Methods
/// <summary>
/// Populates the ExpandoSurrogate with data that is to be
/// serialized from the specified Expando
/// </summary>
/// <param name="expando">The Expando that contains the data
/// to be serialized</param>
public void Load(Expando expando)
{
this.Name = expando.Name;
this.Text = expando.Text;
this.Size = expando.Size;
this.Location = expando.Location;
this.BackColor = ThemeManager.ConvertColorToString(expando.BackColor);
this.ExpandedHeight = expando.ExpandedHeight;
this.CustomSettings = new ExpandoInfo.ExpandoInfoSurrogate();
this.CustomSettings.Load(expando.CustomSettings);
this.CustomHeaderSettings = new HeaderInfo.HeaderInfoSurrogate();
this.CustomHeaderSettings.Load(expando.CustomHeaderSettings);
this.Animate = expando.Animate;
this.ShowFocusCues = expando.ShowFocusCues;
this.Collapsed = expando.Collapsed;
this.CanCollapse = expando.CanCollapse;
this.SpecialGroup = expando.SpecialGroup;
this.TitleImage = ThemeManager.ConvertImageToByteArray(expando.TitleImage);
this.Watermark = ThemeManager.ConvertImageToByteArray(expando.Watermark);
this.Enabled = expando.Enabled;
this.Visible = expando.Visible;
this.AutoLayout = expando.AutoLayout;
this.Anchor = expando.Anchor;
this.Dock = expando.Dock;
this.FontName = expando.Font.FontFamily.Name;
this.FontSize = expando.Font.SizeInPoints;
this.FontDecoration = expando.Font.Style;
this.Tag = ThemeManager.ConvertObjectToByteArray(expando.Tag);
for (int i=0; i<expando.Items.Count; i++)
{
if (expando.Items[i] is TaskItem)
{
TaskItem.TaskItemSurrogate tis = new TaskItem.TaskItemSurrogate();
tis.Load((TaskItem) expando.Items[i]);
this.Items.Add(tis);
}
}
}
/// <summary>
/// Returns an Expando that contains the deserialized ExpandoSurrogate data
/// </summary>
/// <returns>An Expando that contains the deserialized ExpandoSurrogate data</returns>
public Expando Save()
{
Expando expando = new Expando();
((ISupportInitialize) expando).BeginInit();
expando.SuspendLayout();
expando.Name = this.Name;
expando.Text = this.Text;
expando.Size = this.Size;
expando.Location = this.Location;
expando.BackColor = ThemeManager.ConvertStringToColor(this.BackColor);
expando.ExpandedHeight = this.ExpandedHeight;
expando.customSettings = this.CustomSettings.Save();
expando.customSettings.Expando = expando;
expando.customHeaderSettings = this.CustomHeaderSettings.Save();
expando.customHeaderSettings.Expando = expando;
expando.TitleImage = ThemeManager.ConvertByteArrayToImage(this.TitleImage);
expando.Watermark = ThemeManager.ConvertByteArrayToImage(this.Watermark);
expando.Animate = this.Animate;
expando.ShowFocusCues = this.ShowFocusCues;
expando.Collapsed = this.Collapsed;
expando.CanCollapse = this.CanCollapse;
expando.SpecialGroup = this.SpecialGroup;
expando.Enabled = this.Enabled;
expando.Visible = this.Visible;
expando.AutoLayout = this.AutoLayout;
expando.Anchor = this.Anchor;
expando.Dock = this.Dock;
expando.Font = new Font(this.FontName, this.FontSize, this.FontDecoration);
expando.Tag = ThemeManager.ConvertByteArrayToObject(this.Tag);
foreach (Object o in this.Items)
{
TaskItem ti = ((TaskItem.TaskItemSurrogate) o).Save();
expando.Items.Add(ti);
}
((ISupportInitialize) expando).EndInit();
expando.ResumeLayout(false);
return expando;
}
/// <summary>
/// Populates a SerializationInfo with the data needed to serialize the ExpandoSurrogate
/// </summary>
/// <param name="info">The SerializationInfo to populate with data</param>
/// <param name="context">The destination for this serialization</param>
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Version", this.Version);
info.AddValue("Name", this.Name);
info.AddValue("Text", this.Text);
info.AddValue("Size", this.Size);
info.AddValue("Location", this.Location);
info.AddValue("BackColor", this.BackColor);
info.AddValue("ExpandedHeight", this.ExpandedHeight);
info.AddValue("CustomSettings", this.CustomSettings);
info.AddValue("CustomHeaderSettings", this.CustomHeaderSettings);
info.AddValue("Animate", this.Animate);
info.AddValue("ShowFocusCues", this.ShowFocusCues);
info.AddValue("Collapsed", this.Collapsed);
info.AddValue("CanCollapse", this.CanCollapse);
info.AddValue("SpecialGroup", this.SpecialGroup);
info.AddValue("TitleImage", this.TitleImage);
info.AddValue("Watermark", this.Watermark);
info.AddValue("Enabled", this.Enabled);
info.AddValue("Visible", this.Visible);
info.AddValue("AutoLayout", this.AutoLayout);
info.AddValue("Anchor", this.Anchor);
info.AddValue("Dock", this.Dock);
info.AddValue("FontName", this.FontName);
info.AddValue("FontSize", this.FontSize);
info.AddValue("FontDecoration", this.FontDecoration);
info.AddValue("Tag", this.Tag);
info.AddValue("Items", this.Items);
}
/// <summary>
/// Initializes a new instance of the ExpandoSurrogate class using the information
/// in the SerializationInfo
/// </summary>
/// <param name="info">The information to populate the ExpandoSurrogate</param>
/// <param name="context">The source from which the ExpandoSurrogate is deserialized</param>
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)]
protected ExpandoSurrogate(SerializationInfo info, StreamingContext context) : base()
{
int version = info.GetInt32("Version");
this.Name = info.GetString("Name");
this.Text = info.GetString("Text");
this.Size = (Size) info.GetValue("Size", typeof(Size));
this.Location = (Point) info.GetValue("Location", typeof(Point));
this.BackColor = info.GetString("BackColor");
this.ExpandedHeight = info.GetInt32("ExpandedHeight");
this.CustomSettings = (ExpandoInfo.ExpandoInfoSurrogate) info.GetValue("CustomSettings", typeof(ExpandoInfo.ExpandoInfoSurrogate));
this.CustomHeaderSettings = (HeaderInfo.HeaderInfoSurrogate) info.GetValue("CustomHeaderSettings", typeof(HeaderInfo.HeaderInfoSurrogate));
this.Animate = info.GetBoolean("Animate");
this.ShowFocusCues = info.GetBoolean("ShowFocusCues");
this.Collapsed = info.GetBoolean("Collapsed");
this.CanCollapse = info.GetBoolean("CanCollapse");
this.SpecialGroup = info.GetBoolean("SpecialGroup");
this.TitleImage = (byte[]) info.GetValue("TitleImage", typeof(byte[]));
this.Watermark = (byte[]) info.GetValue("Watermark", typeof(byte[]));
this.Enabled = info.GetBoolean("Enabled");
this.Visible = info.GetBoolean("Visible");
this.AutoLayout = info.GetBoolean("AutoLayout");
this.Anchor = (AnchorStyles) info.GetValue("Anchor", typeof(AnchorStyles));
this.Dock = (DockStyle) info.GetValue("Dock", typeof(DockStyle));
this.FontName = info.GetString("FontName");
this.FontSize = info.GetSingle("FontSize");
this.FontDecoration = (FontStyle) info.GetValue("FontDecoration", typeof(FontStyle));
this.Tag = (byte[]) info.GetValue("Tag", typeof(byte[]));
this.Items = (ArrayList) info.GetValue("Items", typeof(ArrayList));
}
#endregion
}
#endregion
}
#endregion
#region ExpandoEventArgs
/// <summary>
/// Provides data for the StateChanged, ExpandoAdded and
/// ExpandoRemoved events
/// </summary>
public class ExpandoEventArgs : EventArgs
{
#region Class Data
/// <summary>
/// The Expando that generated the event
/// </summary>
private Expando expando;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the ExpandoEventArgs class with default settings
/// </summary>
public ExpandoEventArgs()
{
expando = null;
}
/// <summary>
/// Initializes a new instance of the ExpandoEventArgs class with specific Expando
/// </summary>
/// <param name="expando">The Expando that generated the event</param>
public ExpandoEventArgs(Expando expando)
{
this.expando = expando;
}
#endregion
#region Properties
/// <summary>
/// Gets the Expando that generated the event
/// </summary>
public Expando Expando
{
get
{
return this.expando;
}
}
/// <summary>
/// Gets whether the Expando is collapsed
/// </summary>
public bool Collapsed
{
get
{
return this.expando.Collapsed;
}
}
#endregion
}
#endregion
#region ExpandoConverter
/// <summary>
/// A custom TypeConverter used to help convert Expandos from
/// one Type to another
/// </summary>
internal class ExpandoConverter : TypeConverter
{
/// <summary>
/// Returns whether this converter can convert the object to the
/// specified type, using the specified context
/// </summary>
/// <param name="context">An ITypeDescriptorContext that provides a
/// format context</param>
/// <param name="destinationType">A Type that represents the type
/// you want to convert to</param>
/// <returns>true if this converter can perform the conversion; o
/// therwise, false</returns>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(InstanceDescriptor))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
/// <summary>
/// Converts the given value object to the specified type, using
/// the specified context and culture information
/// </summary>
/// <param name="context">An ITypeDescriptorContext that provides
/// a format context</param>
/// <param name="culture">A CultureInfo object. If a null reference
/// is passed, the current culture is assumed</param>
/// <param name="value">The Object to convert</param>
/// <param name="destinationType">The Type to convert the value
/// parameter to</param>
/// <returns>An Object that represents the converted value</returns>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(InstanceDescriptor) && value is Expando)
{
ConstructorInfo ci = typeof(Expando).GetConstructor(new Type[] {});
if (ci != null)
{
return new InstanceDescriptor(ci, null, false);
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
#endregion
#region ExpandoDesigner
/// <summary>
/// A custom designer used by Expandos to remove unwanted
/// properties from the Property window in the designer
/// </summary>
internal class ExpandoDesigner : ParentControlDesigner
{
/// <summary>
/// Initializes a new instance of the ExpandoDesigner class
/// </summary>
public ExpandoDesigner() : base()
{
}
/// <summary>
/// Adjusts the set of properties the component exposes through
/// a TypeDescriptor
/// </summary>
/// <param name="properties">An IDictionary containing the properties
/// for the class of the component</param>
protected override void PreFilterProperties(IDictionary properties)
{
base.PreFilterProperties(properties);
properties.Remove("BackColor");
properties.Remove("BackgroundImage");
properties.Remove("BorderStyle");
properties.Remove("Cursor");
properties.Remove("BackgroundImage");
}
}
#endregion
#region FocusStates
/// <summary>
/// Defines the state of an Expandos title bar
/// </summary>
public enum FocusStates
{
/// <summary>
/// Normal state
/// </summary>
None = 0,
/// <summary>
/// The mouse is over the title bar
/// </summary>
Mouse = 1
}
#endregion
}
| gpl-3.0 |
kempj/OpenFOAM-win | src/meshTools/AMIInterpolation/patches/cyclic/cyclicAMIPointPatchField/cyclicAMIPointPatchField.H | 7317 | /*---------------------------------------------------------------------------*\
========= |
\\ / 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/>.
Class
Foam::cyclicAMIPointPatchField
Description
Cyclic AMI front and back plane patch field
SourceFiles
cyclicAMIPointPatchField.C
\*---------------------------------------------------------------------------*/
#ifndef cyclicAMIPointPatchField_H
#define cyclicAMIPointPatchField_H
#include "OpenFOAM-2.1.x/src/OpenFOAM/fields/pointPatchFields/basic/coupled/coupledPointPatchField.H"
#include "OpenFOAM-2.1.x/src/meshTools/AMIInterpolation/patches/cyclic/cyclicAMIPointPatch/cyclicAMIPointPatch.H"
#include "OpenFOAM-2.1.x/src/OpenFOAM/interpolations/primitivePatchInterpolation/PrimitivePatchInterpolationUC.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class cyclicAMIPointPatchField Declaration
\*---------------------------------------------------------------------------*/
template<class Type>
class cyclicAMIPointPatchField
:
public coupledPointPatchField<Type>
{
// Private data
//- Local reference cast into the cyclicAMI patch
const cyclicAMIPointPatch& cyclicAMIPatch_;
//- Owner side patch interpolation pointer
mutable autoPtr<PrimitivePatchInterpolation<primitivePatch> > ppiPtr_;
//- Neighbour side patch interpolation pointer
mutable autoPtr<PrimitivePatchInterpolation<primitivePatch> >
nbrPpiPtr_;
// Private Member Functions
//- Owner side patch interpolation
const PrimitivePatchInterpolation<primitivePatch>& ppi() const
{
if (!ppiPtr_.valid())
{
ppiPtr_.reset
(
new PrimitivePatchInterpolation<primitivePatch>
(
cyclicAMIPatch_.cyclicAMIPatch()
)
);
}
return ppiPtr_();
}
//- Neighbour side patch interpolation
const PrimitivePatchInterpolation<primitivePatch>& nbrPpi() const
{
if (!nbrPpiPtr_.valid())
{
nbrPpiPtr_.reset
(
new PrimitivePatchInterpolation<primitivePatch>
(
cyclicAMIPatch_.cyclicAMIPatch().neighbPatch()
)
);
}
return nbrPpiPtr_();
}
public:
//- Runtime type information
TypeName(cyclicAMIPointPatch::typeName_());
// Constructors
//- Construct from patch and internal field
cyclicAMIPointPatchField
(
const pointPatch&,
const DimensionedField<Type, pointMesh>&
);
//- Construct from patch, internal field and dictionary
cyclicAMIPointPatchField
(
const pointPatch&,
const DimensionedField<Type, pointMesh>&,
const dictionary&
);
//- Construct by mapping given patchField<Type> onto a new patch
cyclicAMIPointPatchField
(
const cyclicAMIPointPatchField<Type>&,
const pointPatch&,
const DimensionedField<Type, pointMesh>&,
const pointPatchFieldMapper&
);
//- Construct and return a clone
virtual autoPtr<pointPatchField<Type> > clone() const
{
return autoPtr<pointPatchField<Type> >
(
new cyclicAMIPointPatchField<Type>
(
*this
)
);
}
//- Construct as copy setting internal field reference
cyclicAMIPointPatchField
(
const cyclicAMIPointPatchField<Type>&,
const DimensionedField<Type, pointMesh>&
);
//- Construct and return a clone setting internal field reference
virtual autoPtr<pointPatchField<Type> > clone
(
const DimensionedField<Type, pointMesh>& iF
) const
{
return autoPtr<pointPatchField<Type> >
(
new cyclicAMIPointPatchField<Type>
(
*this, iF
)
);
}
// Member functions
// Constraint handling
//- Return the constraint type this pointPatchField implements
virtual const word& constraintType() const
{
return cyclicAMIPointPatch::typeName;
}
// Cyclic AMI coupled interface functions
//- Does the patch field perform the transfromation
virtual bool doTransform() const
{
return
!(
cyclicAMIPatch_.parallel()
|| pTraits<Type>::rank == 0
);
}
//- Return face transformation tensor
virtual const tensorField& forwardT() const
{
return cyclicAMIPatch_.forwardT();
}
//- Return neighbour-cell transformation tensor
virtual const tensorField& reverseT() const
{
return cyclicAMIPatch_.reverseT();
}
// Evaluation functions
//- Evaluate the patch field
virtual void evaluate
(
const Pstream::commsTypes commsType=Pstream::blocking
)
{}
//- Complete swap of patch point values and add to local values
virtual void swapAddSeparated
(
const Pstream::commsTypes commsType,
Field<Type>&
) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#ifdef NoRepository
#include "OpenFOAM-2.1.x/src/meshTools/AMIInterpolation/patches/cyclic/cyclicAMIPointPatchField/cyclicAMIPointPatchField.C"
#endif
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| gpl-3.0 |
kempj/OpenFOAM-win | src/OpenFOAM/db/Time/Time.H | 17518 | /*---------------------------------------------------------------------------*\
========= |
\\ / 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/>.
Class
Foam::Time
Description
Class to control time during OpenFOAM simulations that is also the
top-level objectRegistry.
SourceFiles
Time.C
TimeIO.C
findInstance.C
\*---------------------------------------------------------------------------*/
#ifndef Time_H
#define Time_H
#include "OpenFOAM-2.1.x/src/OpenFOAM/db/Time/TimePaths.H"
#include "OpenFOAM-2.1.x/src/OpenFOAM/db/objectRegistry/objectRegistry.H"
#include "OpenFOAM-2.1.x/src/OpenFOAM/db/IOobjects/IOdictionary/IOdictionary.H"
#include "OpenFOAM-2.1.x/src/OpenFOAM/containers/LinkedLists/user/FIFOStack.H"
#include "OpenFOAM-2.1.x/src/OpenFOAM/global/clock/clock.H"
#include "OpenFOAM-2.1.x/src/OSspecific/MSwindows/cpuTime/cpuTime.H"
#include "OpenFOAM-2.1.x/src/OpenFOAM/db/Time/TimeState.H"
#include "OpenFOAM-2.1.x/src/OpenFOAM/primitives/bools/Switch/Switch.H"
#include "OpenFOAM-2.1.x/src/OpenFOAM/db/Time/instant/instantList.H"
#include "OpenFOAM-2.1.x/src/OpenFOAM/containers/NamedEnum/NamedEnum.H"
#include "OpenFOAM-2.1.x/src/OpenFOAM/db/typeInfo/typeInfo.H"
#include "OpenFOAM-2.1.x/src/OpenFOAM/db/dynamicLibrary/dlLibraryTable/dlLibraryTable.H"
#include "OpenFOAM-2.1.x/src/OpenFOAM/db/functionObjects/functionObjectList/functionObjectList.H"
#include "OpenFOAM-2.1.x/src/OSspecific/MSwindows/fileMonitor.H"
#include "OpenFOAM-2.1.x/src/OSspecific/MSwindows/signals/sigWriteNow.H"
#include "OpenFOAM-2.1.x/src/OSspecific/MSwindows/signals/sigStopAtWriteNow.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// Forward declaration of classes
class argList;
/*---------------------------------------------------------------------------*\
Class Time Declaration
\*---------------------------------------------------------------------------*/
class Time
:
public clock,
public cpuTime,
public TimePaths,
public objectRegistry,
public TimeState
{
// Private data
//- file-change monitor for all registered files
mutable autoPtr<fileMonitor> monitorPtr_;
//- Any loaded dynamic libraries. Make sure to construct before
// reading controlDict.
dlLibraryTable libs_;
//- The controlDict
IOdictionary controlDict_;
public:
//- Write control options
enum writeControls
{
wcTimeStep,
wcRunTime,
wcAdjustableRunTime,
wcClockTime,
wcCpuTime
};
//- Stop-run control options
enum stopAtControls
{
saEndTime, /*!< stop when Time reaches the prescribed endTime */
saNoWriteNow, /*!< set endTime to stop immediately w/o writing */
saWriteNow, /*!< set endTime to stop immediately w/ writing */
saNextWrite /*!< stop the next time data are written */
};
//- Supported time directory name formats
enum fmtflags
{
general = 0,
fixed = ios_base::fixed,
scientific = ios_base::scientific
};
protected:
// Protected data
label startTimeIndex_;
scalar startTime_;
mutable scalar endTime_;
static const NamedEnum<stopAtControls, 4> stopAtControlNames_;
mutable stopAtControls stopAt_;
static const NamedEnum<writeControls, 5> writeControlNames_;
writeControls writeControl_;
scalar writeInterval_;
// Additional writing
writeControls secondaryWriteControl_;
scalar secondaryWriteInterval_;
label purgeWrite_;
mutable FIFOStack<word> previousOutputTimes_;
// One-shot writing
bool writeOnce_;
//- Is the time currently being sub-cycled?
bool subCycling_;
//- If time is being sub-cycled this is the previous TimeState
autoPtr<TimeState> prevTimeState_;
// Signal handlers for secondary writing
//- Enable one-shot writing upon signal
sigWriteNow sigWriteNow_;
//- Enable write and clean exit upon signal
sigStopAtWriteNow sigStopAtWriteNow_;
//- Time directory name format
static fmtflags format_;
//- Time directory name precision
static int precision_;
//- Adjust the time step so that writing occurs at the specified time
void adjustDeltaT();
//- Set the controls from the current controlDict
void setControls();
//- Read the control dictionary and set the write controls etc.
virtual void readDict();
private:
//- Default write option
IOstream::streamFormat writeFormat_;
//- Default output file format version number
IOstream::versionNumber writeVersion_;
//- Default output compression
IOstream::compressionType writeCompression_;
//- Default graph format
word graphFormat_;
//- Is runtime modification of dictionaries allowed?
Switch runTimeModifiable_;
//- Function objects executed at start and on ++, +=
mutable functionObjectList functionObjects_;
public:
TypeName("time");
//- The default control dictionary name (normally "controlDict")
static word controlDictName;
// Constructors
//- Construct given name of dictionary to read and argument list
Time
(
const word& name,
const argList& args,
const word& systemName = "system",
const word& constantName = "constant"
);
//- Construct given name of dictionary to read, rootPath and casePath
Time
(
const word& name,
const fileName& rootPath,
const fileName& caseName,
const word& systemName = "system",
const word& constantName = "constant",
const bool enableFunctionObjects = true
);
//- Construct given dictionary, rootPath and casePath
Time
(
const dictionary& dict,
const fileName& rootPath,
const fileName& caseName,
const word& systemName = "system",
const word& constantName = "constant",
const bool enableFunctionObjects = true
);
//- Construct given endTime, rootPath and casePath
Time
(
const fileName& rootPath,
const fileName& caseName,
const word& systemName = "system",
const word& constantName = "constant",
const bool enableFunctionObjects = true
);
//- Destructor
virtual ~Time();
// Member functions
// Database functions
//- Return root path
const fileName& rootPath() const
{
return TimePaths::rootPath();
}
//- Return case name
const fileName& caseName() const
{
return TimePaths::caseName();
}
//- Return path
fileName path() const
{
return rootPath()/caseName();
}
const dictionary& controlDict() const
{
return controlDict_;
}
virtual const fileName& dbDir() const
{
return fileName::null;
}
//- Return current time path
fileName timePath() const
{
return path()/timeName();
}
//- Default write format
IOstream::streamFormat writeFormat() const
{
return writeFormat_;
}
//- Default write version number
IOstream::versionNumber writeVersion() const
{
return writeVersion_;
}
//- Default write compression
IOstream::compressionType writeCompression() const
{
return writeCompression_;
}
//- Default graph format
const word& graphFormat() const
{
return graphFormat_;
}
//- Supports re-reading
const Switch& runTimeModifiable() const
{
return runTimeModifiable_;
}
//- Read control dictionary, update controls and time
virtual bool read();
// Automatic rereading
//- Read the objects that have been modified
void readModifiedObjects();
//- Add watching of a file. Returns handle
label addWatch(const fileName&) const;
//- Remove watch on a file (using handle)
bool removeWatch(const label) const;
//- Get name of file being watched (using handle)
const fileName& getFile(const label) const;
//- Get current state of file (using handle)
fileMonitor::fileState getState(const label) const;
//- Set current state of file (using handle) to unmodified
void setUnmodified(const label) const;
//- Return the location of "dir" containing the file "name".
// (eg, used in reading mesh data)
// If name is null, search for the directory "dir" only.
// Does not search beyond stopInstance (if set) or constant.
word findInstance
(
const fileName& dir,
const word& name = word::null,
const IOobject::readOption rOpt = IOobject::MUST_READ,
const word& stopInstance = word::null
) const;
//- Search the case for valid time directories
instantList times() const;
//- Search the case for the time directory path
// corresponding to the given instance
word findInstancePath(const instant&) const;
//- Search the case for the time closest to the given time
instant findClosestTime(const scalar) const;
//- Search instantList for the time index closest to the given time
static label findClosestTimeIndex(const instantList&, const scalar);
//- Write using given format, version and compression
virtual bool writeObject
(
IOstream::streamFormat,
IOstream::versionNumber,
IOstream::compressionType
) const;
//- Write the objects now (not at end of iteration) and continue
// the run
bool writeNow();
//- Write the objects now (not at end of iteration) and end the run
bool writeAndEnd();
//- Write the objects once (one shot) and continue the run
void writeOnce();
// Access
//- Return time name of given scalar time
static word timeName(const scalar);
//- Return current time name
virtual word timeName() const;
//- Search a given directory for valid time directories
static instantList findTimes(const fileName&);
//- Return start time index
virtual label startTimeIndex() const;
//- Return start time
virtual dimensionedScalar startTime() const;
//- Return end time
virtual dimensionedScalar endTime() const;
//- Return the list of function objects
const functionObjectList& functionObjects() const
{
return functionObjects_;
}
//- External access to the loaded libraries
const dlLibraryTable& libs() const
{
return libs_;
}
//- External access to the loaded libraries
dlLibraryTable& libs()
{
return libs_;
}
//- Return true if time currently being sub-cycled, otherwise false
bool subCycling() const
{
return subCycling_;
}
//- Return previous TimeState if time is being sub-cycled
const TimeState& prevTimeState() const
{
return prevTimeState_();
}
// Check
//- Return true if run should continue,
// also invokes the functionObjectList::end() method
// when the time goes out of range
// \note
// For correct behaviour, the following style of time-loop
// is recommended:
// \code
// while (runTime.run())
// {
// runTime++;
// solve;
// runTime.write();
// }
// \endcode
virtual bool run() const;
//- Return true if run should continue and if so increment time
// also invokes the functionObjectList::end() method
// when the time goes out of range
// \note
// For correct behaviour, the following style of time-loop
// is recommended:
// \code
// while (runTime.loop())
// {
// solve;
// runTime.write();
// }
// \endcode
virtual bool loop();
//- Return true if end of run,
// does not invoke any functionObject methods
// \note
// The rounding heuristics near endTime mean that
// \code run() \endcode and \code !end() \endcode may
// not yield the same result
virtual bool end() const;
// Edit
//- Adjust the current stopAtControl. Note that this value
// only persists until the next time the dictionary is read.
// Return true if the stopAtControl changed.
virtual bool stopAt(const stopAtControls) const;
//- Reset the time and time-index to those of the given time
virtual void setTime(const Time&);
//- Reset the time and time-index
virtual void setTime(const instant&, const label newIndex);
//- Reset the time and time-index
virtual void setTime
(
const dimensionedScalar&,
const label newIndex
);
//- Reset the time and time-index
virtual void setTime(const scalar, const label newIndex);
//- Reset end time
virtual void setEndTime(const dimensionedScalar&);
//- Reset end time
virtual void setEndTime(const scalar);
//- Reset time step
virtual void setDeltaT(const dimensionedScalar&);
//- Reset time step
virtual void setDeltaT(const scalar);
//- Set time to sub-cycle for the given number of steps
virtual TimeState subCycle(const label nSubCycles);
//- Reset time after sub-cycling back to previous TimeState
virtual void endSubCycle();
//- Return non-const access to the list of function objects
functionObjectList& functionObjects()
{
return functionObjects_;
}
// Member operators
//- Set deltaT to that specified and increment time via operator++()
virtual Time& operator+=(const dimensionedScalar&);
//- Set deltaT to that specified and increment time via operator++()
virtual Time& operator+=(const scalar);
//- Prefix increment,
// also invokes the functionObjectList::start() or
// functionObjectList::execute() method, depending on the time-index
virtual Time& operator++();
//- Postfix increment, this is identical to the prefix increment
virtual Time& operator++(int);
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| gpl-3.0 |
dedefajriansyah/jibas | akademik/presensi/lap_kelas_cetak.php | 7652 | <?
/**[N]**
* JIBAS Education Community
* Jaringan Informasi Bersama Antar Sekolah
*
* @version: 3.8 (January 25, 2016)
* @notes: JIBAS Education Community will be managed by Yayasan Indonesia Membaca (http://www.indonesiamembaca.net)
*
* Copyright (C) 2009 Yayasan Indonesia Membaca (http://www.indonesiamembaca.net)
*
* 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
**[N]**/ ?>
<?
require_once('../include/errorhandler.php');
require_once('../include/sessioninfo.php');
require_once('../include/common.php');
require_once('../include/config.php');
require_once('../include/db_functions.php');
require_once('../include/getheader.php');
$pelajaran = $_REQUEST['pelajaran'];
$kelas = $_REQUEST['kelas'];
$semester = $_REQUEST['semester'];
$tglawal = $_REQUEST['tglawal'];
$tglakhir = $_REQUEST['tglakhir'];
$urut = $_REQUEST['urut'];
$urutan = $_REQUEST['urutan'];
OpenDb();
if ($pelajaran == -1) {
$filter = "";
} else {
$filter = "AND p.replid = '$pelajaran' ";
}
$sql = "SELECT p.departemen, p.nama, k.kelas, t.tahunajaran, s.semester, g.tingkat FROM pelajaran p, kelas k, tahunajaran t, semester s, tingkat g WHERE k.replid = '$kelas' AND k.idtahunajaran = t.replid AND s.replid = '$semester' AND k.idtingkat = g.replid $filter";
$result = QueryDB($sql);
$row = mysql_fetch_array($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="../style/style.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JIBAS SIMAKA [Cetak Laporan Presensi Pelajaran Per Kelas]</title>
</head>
<body>
<table border="0" cellpadding="10" cellpadding="5" width="780" align="left">
<tr>
<td align="left" valign="top" colspan="2">
<?=getHeader($row[departemen])?>
<center>
<font size="4"><strong>LAPORAN PRESENSI PELAJARAN PER KELAS</strong></font><br />
</center><br /><br />
<table>
<tr>
<td width="25%"><strong>Departemen</strong></td>
<td><strong>: <?=$row['departemen']?></strong></td>
</tr>
<tr>
<td><strong>Tahun Ajaran</strong></td>
<td><strong>: <?=$row['tahunajaran']?></strong></td>
</tr>
<tr>
<td><strong>Kelas</strong></td>
<td><strong>: <?=$row['tingkat'].' - '.$row['kelas']?></strong></td>
</tr>
<tr>
<td><strong>Pelajaran</strong></td>
<td><strong>: <?=$row['nama']?></strong></td>
</tr>
<tr>
<td><strong>Periode Presensi</strong></td>
<td><strong>: <?=format_tgl($tglawal).' s/d '. format_tgl($tglakhir) ?></strong></td>
</tr>
</table>
<br />
<?
OpenDb();
if ($pelajaran == -1) {
$pel = "Semua Pelajaran";
$sql = "SELECT DISTINCT s.nis, s.nama, s.telponsiswa, s.hpsiswa, s.namaayah, s.telponortu, s.hportu, s.aktif FROM siswa s, presensipelajaran p, ppsiswa pp, kelas k WHERE pp.idpp = p.replid AND pp.nis = s.nis AND s.idkelas = '$kelas' AND p.idsemester = '$semester' AND p.tanggal BETWEEN '$tglawal' AND '$tglakhir' ORDER BY $urut $urutan";
} else {
$pel = $row ['pelajaran'];
$sql = "SELECT DISTINCT s.nis, s.nama, s.telponsiswa, s.hpsiswa, s.namaayah, s.telponortu, s.hportu, s.aktif FROM siswa s, presensipelajaran p, ppsiswa pp, kelas k WHERE pp.idpp = p.replid AND pp.nis = s.nis AND s.idkelas = '$kelas' AND p.idsemester = '$semester' AND p.tanggal BETWEEN '$tglawal' AND '$tglakhir' AND p.idpelajaran = '$pelajaran' ORDER BY $urut $urutan";
}
//echo $sql;
$result = QueryDb($sql);
$jum_hadir = mysql_num_rows($result);
if ($jum_hadir > 0) {
?>
<table class="tab" id="table" border="1" style="border-collapse:collapse" width="100%" align="left" bordercolor="#000000">
<tr height="30">
<td class="header" align="center" width="5%">No</td>
<td class="header" align="center" width="8%">N I S</td>
<td class="header" align="center" width="15%">Nama</td>
<td class="header" align="center" width="5%">Jml Hadir</td>
<td class="header" align="center" width="8%">Jml Tak Hadir</td>
<td class="header" align="center" width="5%">Jml Total</td>
<td class="header" align="center" width="7%">%</td>
<td class="header" align="center" width="7%">Tlp Siswa</td>
<td class="header" align="center" width="10%">HP Siswa</td>
<td class="header" align="center" width="13%">Orang Tua</td>
<td class="header" align="center" width="7%">Tlp Ortu</td>
<td class="header" align="center" width="10%">HP Ortu</td>
</tr>
<?
$cnt = 0;
while ($row = mysql_fetch_row($result)) {
$tanda = "";
if ($row[7] == 0)
$tanda = "*";
?>
<tr height="25">
<td align="center"><?=++$cnt?></td>
<td align="center"><?=$row[0]?><?=$tanda?></td>
<td><?=$row[1]?></td>
<td align="center">
<? if ($pelajaran == -1) {
$sql1 = "SELECT COUNT(*) FROM ppsiswa pp, presensipelajaran p WHERE pp.nis = '$row[0]' AND pp.statushadir = 0 AND pp.idpp = p.replid AND p.idkelas = '$kelas' AND p.idsemester = '$semester' AND p.tanggal BETWEEN '$tglawal' AND '$tglakhir' " ;
} else {
$sql1 = "SELECT COUNT(*) FROM ppsiswa pp, presensipelajaran p WHERE pp.nis = '$row[0]' AND pp.statushadir = 0 AND pp.idpp = p.replid AND p.idkelas = '$kelas' AND p.idsemester = '$semester' AND p.tanggal BETWEEN '$tglawal' AND '$tglakhir' AND p.idpelajaran = '$pelajaran'" ;
}
//echo $sql1;
$result1 = QueryDb($sql1);
$row1 = @mysql_fetch_array($result1);
$hadir = $row1[0];
echo $row1[0]; ?></td>
<td align="center">
<? if ($pelajaran == -1) {
$sql2 = "SELECT COUNT(*) FROM ppsiswa pp, presensipelajaran p WHERE pp.nis = '$row[0]' AND pp.statushadir <> 0 AND pp.idpp = p.replid AND p.idkelas = '$kelas' AND p.idsemester = '$semester' AND p.tanggal BETWEEN '$tglawal' AND '$tglakhir' " ;
} else {
$sql2 = "SELECT COUNT(*) FROM ppsiswa pp, presensipelajaran p WHERE pp.nis = '$row[0]' AND pp.statushadir <> 0 AND pp.idpp = p.replid AND p.idkelas = '$kelas' AND p.idsemester = '$semester' AND p.tanggal BETWEEN '$tglawal' AND '$tglakhir' AND p.idpelajaran = '$pelajaran'" ;
}
$result2 = QueryDb($sql2);
$row2 = @mysql_fetch_array($result2);
$absen = $row2[0];
echo $row2[0]; ?></td>
<td align="center">
<? $tot = $hadir + $absen;
echo $tot; ?></td>
<td align="center">
<? if ($tot == 0)
$tot = 1;
$prs = (( $hadir/$tot)*100);
echo round($prs,2).'%'; ?></td>
<td><?=$row[2]?></td>
<td><?=$row[3]?></td>
<td><?=$row[4]?></td>
<td><?=$row[5]?></td>
<td><?=$row[6]?></td>
</tr>
<? }
CloseDb() ?>
<!-- END TABLE CONTENT -->
</table>
<? } ?>
</td>
</tr>
<tr>
<td><? if ($row[7] == 0)
$tanda = "*";
echo "Ket: *Status siswa tidak aktif lagi";
?>
</td>
</tr>
</table>
</body>
<script language="javascript">
window.print();
</script>
</html> | gpl-3.0 |
DarkXipher/WoWCombatParser | test/src/CombatParser/beans/event/swing/SwingEvent.java | 133 | package CombatParser.beans.event.swing;
import CombatParser.beans.event.Event;
public abstract class SwingEvent extends Event {
}
| gpl-3.0 |
c0c0n3/omero-ms-queue | components/util/src/test/java/util/io/StreamOpsReadLinesIntoStringTest.java | 1430 | package util.io;
import static java.util.stream.Collectors.joining;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static util.sequence.Arrayz.array;
import static util.io.StreamOps.readLinesIntoString;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.stream.Stream;
@RunWith(Theories.class)
public class StreamOpsReadLinesIntoStringTest {
@DataPoints
public static String[][] linesSupply = new String[][]{
array(""), array("x"), array("", "x"),
array(" "), array("x "), array(" ", "x "), array("x ", " "),
array(" x", "y ", " z ")
};
private static String buildTextInput(String[] lines) {
String sep = System.lineSeparator();
return Stream.of(lines).collect(joining(sep));
}
private static InputStream toInputStream(String text) {
return new ByteArrayInputStream(text.getBytes());
}
@Theory
public void joiningLinesThenReadingIsTheIdentity(String[] lines) {
String expected = buildTextInput(lines);
InputStream input = toInputStream(expected);
String actual = readLinesIntoString(input);
assertThat(actual, is(expected));
}
}
| gpl-3.0 |
Demorde/openmw-android | apps/openmw/mwgui/mapwindow.cpp | 24257 | #include "mapwindow.hpp"
#include <boost/lexical_cast.hpp>
#include <OgreSceneNode.h>
#include <OgreVector2.h>
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwbase/environment.hpp"
#include "../mwworld/player.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwrender/globalmap.hpp"
#include "../components/esm/globalmap.hpp"
#include "widgets.hpp"
namespace MWGui
{
LocalMapBase::LocalMapBase()
: mCurX(0)
, mCurY(0)
, mInterior(false)
, mFogOfWar(true)
, mLocalMap(NULL)
, mMapDragAndDrop(false)
, mPrefix()
, mChanged(true)
, mLayout(NULL)
, mLastPositionX(0.0f)
, mLastPositionY(0.0f)
, mLastDirectionX(0.0f)
, mLastDirectionY(0.0f)
, mCompass(NULL)
, mMarkerUpdateTimer(0.0f)
{
}
LocalMapBase::~LocalMapBase()
{
// Clear our "lost focus" delegate for marker widgets first, otherwise it will
// fire when the widget is about to be destroyed and the mouse cursor is over it.
// At that point, other widgets may already be destroyed, so applyFogOfWar (which is called by the delegate) would crash.
for (std::vector<MyGUI::Widget*>::iterator it = mDoorMarkerWidgets.begin(); it != mDoorMarkerWidgets.end(); ++it)
(*it)->eventMouseLostFocus.clear();
for (std::vector<MyGUI::Widget*>::iterator it = mMarkerWidgets.begin(); it != mMarkerWidgets.end(); ++it)
(*it)->eventMouseLostFocus.clear();
}
void LocalMapBase::init(MyGUI::ScrollView* widget, MyGUI::ImageBox* compass, OEngine::GUI::Layout* layout, bool mapDragAndDrop)
{
mLocalMap = widget;
mLayout = layout;
mMapDragAndDrop = mapDragAndDrop;
mCompass = compass;
// create 3x3 map widgets, 512x512 each, holding a 1024x1024 texture each
const int widgetSize = 512;
for (int mx=0; mx<3; ++mx)
{
for (int my=0; my<3; ++my)
{
MyGUI::ImageBox* map = mLocalMap->createWidget<MyGUI::ImageBox>("ImageBox",
MyGUI::IntCoord(mx*widgetSize, my*widgetSize, widgetSize, widgetSize),
MyGUI::Align::Top | MyGUI::Align::Left);
MyGUI::ImageBox* fog = map->createWidget<MyGUI::ImageBox>("ImageBox",
MyGUI::IntCoord(0, 0, widgetSize, widgetSize),
MyGUI::Align::Top | MyGUI::Align::Left);
if (!mMapDragAndDrop)
{
map->setNeedMouseFocus(false);
fog->setNeedMouseFocus(false);
}
mMapWidgets.push_back(map);
mFogWidgets.push_back(fog);
}
}
}
void LocalMapBase::setCellPrefix(const std::string& prefix)
{
mPrefix = prefix;
mChanged = true;
}
bool LocalMapBase::toggleFogOfWar()
{
mFogOfWar = !mFogOfWar;
applyFogOfWar();
return mFogOfWar;
}
void LocalMapBase::applyFogOfWar()
{
for (int mx=0; mx<3; ++mx)
{
for (int my=0; my<3; ++my)
{
std::string image = mPrefix+"_"+ boost::lexical_cast<std::string>(mCurX + (mx-1)) + "_"
+ boost::lexical_cast<std::string>(mCurY + (-1*(my-1)));
MyGUI::ImageBox* fog = mFogWidgets[my + 3*mx];
fog->setImageTexture(mFogOfWar ?
((MyGUI::RenderManager::getInstance().getTexture(image+"_fog") != 0) ? image+"_fog"
: "black.png" )
: "");
}
}
notifyMapChanged ();
}
void LocalMapBase::onMarkerFocused (MyGUI::Widget* w1, MyGUI::Widget* w2)
{
// Workaround to not make the marker visible if it's under fog of war
applyFogOfWar ();
}
void LocalMapBase::onMarkerUnfocused (MyGUI::Widget* w1, MyGUI::Widget* w2)
{
// Workaround to not make the marker visible if it's under fog of war
applyFogOfWar ();
}
MyGUI::IntPoint LocalMapBase::getMarkerPosition(float worldX, float worldY, MarkerPosition& markerPos)
{
MyGUI::IntPoint widgetPos;
// normalized cell coordinates
float nX,nY;
markerPos.interior = mInterior;
if (!mInterior)
{
int cellX, cellY;
MWBase::Environment::get().getWorld()->positionToIndex(worldX, worldY, cellX, cellY);
const int cellSize = 8192;
nX = (worldX - cellSize * cellX) / cellSize;
// Image space is -Y up, cells are Y up
nY = 1 - (worldY - cellSize * cellY) / cellSize;
float cellDx = cellX - mCurX;
float cellDy = cellY - mCurY;
markerPos.cellX = cellX;
markerPos.cellY = cellY;
widgetPos = MyGUI::IntPoint(nX * 512 + (1+cellDx) * 512,
nY * 512 - (cellDy-1) * 512);
}
else
{
int cellX, cellY;
Ogre::Vector2 worldPos (worldX, worldY);
MWBase::Environment::get().getWorld ()->getInteriorMapPosition (worldPos, nX, nY, cellX, cellY);
markerPos.cellX = cellX;
markerPos.cellY = cellY;
// Image space is -Y up, cells are Y up
widgetPos = MyGUI::IntPoint(nX * 512 + (1+(cellX-mCurX)) * 512,
nY * 512 + (1-(cellY-mCurY)) * 512);
}
markerPos.nX = nX;
markerPos.nY = nY;
return widgetPos;
}
void LocalMapBase::setActiveCell(const int x, const int y, bool interior)
{
if (x==mCurX && y==mCurY && mInterior==interior && !mChanged)
return; // don't do anything if we're still in the same cell
mCurX = x;
mCurY = y;
mInterior = interior;
mChanged = false;
// clear all previous door markers
for (std::vector<MyGUI::Widget*>::iterator it = mDoorMarkerWidgets.begin(); it != mDoorMarkerWidgets.end(); ++it)
MyGUI::Gui::getInstance().destroyWidget(*it);
mDoorMarkerWidgets.clear();
// Update the map textures
for (int mx=0; mx<3; ++mx)
{
for (int my=0; my<3; ++my)
{
// map
std::string image = mPrefix+"_"+ boost::lexical_cast<std::string>(x + (mx-1)) + "_"
+ boost::lexical_cast<std::string>(y + (-1*(my-1)));
MyGUI::ImageBox* box = mMapWidgets[my + 3*mx];
if (MyGUI::RenderManager::getInstance().getTexture(image) != 0)
box->setImageTexture(image);
else
box->setImageTexture("black.png");
}
}
MWBase::World* world = MWBase::Environment::get().getWorld();
// Retrieve the door markers we want to show
std::vector<MWBase::World::DoorMarker> doors;
if (interior)
{
MWWorld::CellStore* cell = world->getInterior (mPrefix);
world->getDoorMarkers(cell, doors);
}
else
{
for (int dX=-1; dX<2; ++dX)
{
for (int dY=-1; dY<2; ++dY)
{
MWWorld::CellStore* cell = world->getExterior (mCurX+dX, mCurY+dY);
world->getDoorMarkers(cell, doors);
}
}
}
// Create a widget for each marker
int counter = 0;
for (std::vector<MWBase::World::DoorMarker>::iterator it = doors.begin(); it != doors.end(); ++it)
{
MWBase::World::DoorMarker marker = *it;
MarkerPosition markerPos;
MyGUI::IntPoint widgetPos = getMarkerPosition(marker.x, marker.y, markerPos);
MyGUI::IntCoord widgetCoord(widgetPos.left - 4,
widgetPos.top - 4,
8, 8);
++counter;
MyGUI::Button* markerWidget = mLocalMap->createWidget<MyGUI::Button>("ButtonImage",
widgetCoord, MyGUI::Align::Default);
markerWidget->setImageResource("DoorMarker");
markerWidget->setUserString("ToolTipType", "Layout");
markerWidget->setUserString("ToolTipLayout", "TextToolTipOneLine");
markerWidget->setUserString("Caption_TextOneLine", marker.name);
markerWidget->eventMouseSetFocus += MyGUI::newDelegate(this, &LocalMapBase::onMarkerFocused);
markerWidget->eventMouseLostFocus += MyGUI::newDelegate(this, &LocalMapBase::onMarkerUnfocused);
// Used by tooltips to not show the tooltip if marker is hidden by fog of war
markerWidget->setUserString("IsMarker", "true");
markerWidget->setUserData(markerPos);
mDoorMarkerWidgets.push_back(markerWidget);
}
updateMarkers();
applyFogOfWar();
// set the compass texture again, because MyGUI determines sorting of ImageBox widgets
// based on the last setImageTexture call
std::string tex = "textures\\compass.dds";
mCompass->setImageTexture("");
mCompass->setImageTexture(tex);
}
void LocalMapBase::setPlayerPos(const float x, const float y)
{
updateMarkers();
if (x == mLastPositionX && y == mLastPositionY)
return;
notifyPlayerUpdate ();
MyGUI::IntSize size = mLocalMap->getCanvasSize();
MyGUI::IntPoint middle = MyGUI::IntPoint((1/3.f + x/3.f)*size.width,(1/3.f + y/3.f)*size.height);
MyGUI::IntCoord viewsize = mLocalMap->getCoord();
MyGUI::IntPoint pos(0.5*viewsize.width - middle.left, 0.5*viewsize.height - middle.top);
mLocalMap->setViewOffset(pos);
mCompass->setPosition(MyGUI::IntPoint(512+x*512-16, 512+y*512-16));
mLastPositionX = x;
mLastPositionY = y;
}
void LocalMapBase::setPlayerDir(const float x, const float y)
{
if (x == mLastDirectionX && y == mLastDirectionY)
return;
notifyPlayerUpdate ();
MyGUI::ISubWidget* main = mCompass->getSubWidgetMain();
MyGUI::RotatingSkin* rotatingSubskin = main->castType<MyGUI::RotatingSkin>();
rotatingSubskin->setCenter(MyGUI::IntPoint(16,16));
float angle = std::atan2(x,y);
rotatingSubskin->setAngle(angle);
mLastDirectionX = x;
mLastDirectionY = y;
}
void LocalMapBase::addDetectionMarkers(int type)
{
std::vector<MWWorld::Ptr> markers;
MWBase::World* world = MWBase::Environment::get().getWorld();
world->listDetectedReferences(
world->getPlayerPtr(),
markers, MWBase::World::DetectionType(type));
if (markers.empty())
return;
std::string markerTexture;
MyGUI::Colour markerColour;
if (type == MWBase::World::Detect_Creature)
{
markerTexture = "textures\\menu_map_dcreature.dds";
markerColour = MyGUI::Colour(1,0,0,1);
}
if (type == MWBase::World::Detect_Key)
{
markerTexture = "textures\\menu_map_dkey.dds";
markerColour = MyGUI::Colour(0,1,0,1);
}
if (type == MWBase::World::Detect_Enchantment)
{
markerTexture = "textures\\menu_map_dmagic.dds";
markerColour = MyGUI::Colour(0,0,1,1);
}
int counter = 0;
for (std::vector<MWWorld::Ptr>::iterator it = markers.begin(); it != markers.end(); ++it)
{
const ESM::Position& worldPos = it->getRefData().getPosition();
MarkerPosition markerPos;
MyGUI::IntPoint widgetPos = getMarkerPosition(worldPos.pos[0], worldPos.pos[1], markerPos);
MyGUI::IntCoord widgetCoord(widgetPos.left - 4,
widgetPos.top - 4,
8, 8);
++counter;
MyGUI::ImageBox* markerWidget = mLocalMap->createWidget<MyGUI::ImageBox>("ImageBox",
widgetCoord, MyGUI::Align::Default);
markerWidget->setImageTexture(markerTexture);
markerWidget->setUserString("IsMarker", "true");
markerWidget->setUserData(markerPos);
markerWidget->setColour(markerColour);
mMarkerWidgets.push_back(markerWidget);
}
}
void LocalMapBase::onFrame(float dt)
{
mMarkerUpdateTimer += dt;
if (mMarkerUpdateTimer >= 0.25)
{
mMarkerUpdateTimer = 0;
updateMarkers();
}
}
void LocalMapBase::updateMarkers()
{
// clear all previous markers
for (std::vector<MyGUI::Widget*>::iterator it = mMarkerWidgets.begin(); it != mMarkerWidgets.end(); ++it)
MyGUI::Gui::getInstance().destroyWidget(*it);
mMarkerWidgets.clear();
addDetectionMarkers(MWBase::World::Detect_Creature);
addDetectionMarkers(MWBase::World::Detect_Key);
addDetectionMarkers(MWBase::World::Detect_Enchantment);
// Add marker for the spot marked with Mark magic effect
MWWorld::CellStore* markedCell = NULL;
ESM::Position markedPosition;
MWBase::Environment::get().getWorld()->getPlayer().getMarkedPosition(markedCell, markedPosition);
if (markedCell && markedCell->isExterior() == !mInterior
&& (!mInterior || Misc::StringUtils::ciEqual(markedCell->getCell()->mName, mPrefix)))
{
MarkerPosition markerPos;
MyGUI::IntPoint widgetPos = getMarkerPosition(markedPosition.pos[0], markedPosition.pos[1], markerPos);
MyGUI::IntCoord widgetCoord(widgetPos.left - 4,
widgetPos.top - 4,
8, 8);
MyGUI::ImageBox* markerWidget = mLocalMap->createWidget<MyGUI::ImageBox>("ImageBox",
widgetCoord, MyGUI::Align::Default);
markerWidget->setImageTexture("textures\\menu_map_smark.dds");
markerWidget->setUserString("IsMarker", "true");
markerWidget->setUserData(markerPos);
mMarkerWidgets.push_back(markerWidget);
}
}
// ------------------------------------------------------------------------------------------
MapWindow::MapWindow(DragAndDrop* drag, const std::string& cacheDir)
: WindowPinnableBase("openmw_map_window.layout")
, NoDrop(drag, mMainWidget)
, mGlobal(false)
, mGlobalMap(0)
, mGlobalMapRender(0)
{
setCoord(500,0,320,300);
getWidget(mLocalMap, "LocalMap");
getWidget(mGlobalMap, "GlobalMap");
getWidget(mGlobalMapImage, "GlobalMapImage");
getWidget(mGlobalMapOverlay, "GlobalMapOverlay");
getWidget(mPlayerArrowLocal, "CompassLocal");
getWidget(mPlayerArrowGlobal, "CompassGlobal");
mGlobalMap->setVisible (false);
getWidget(mButton, "WorldButton");
mButton->eventMouseButtonClick += MyGUI::newDelegate(this, &MapWindow::onWorldButtonClicked);
mButton->setCaptionWithReplacing("#{sWorld}");
getWidget(mEventBoxGlobal, "EventBoxGlobal");
mEventBoxGlobal->eventMouseDrag += MyGUI::newDelegate(this, &MapWindow::onMouseDrag);
mEventBoxGlobal->eventMouseButtonPressed += MyGUI::newDelegate(this, &MapWindow::onDragStart);
getWidget(mEventBoxLocal, "EventBoxLocal");
mEventBoxLocal->eventMouseDrag += MyGUI::newDelegate(this, &MapWindow::onMouseDrag);
mEventBoxLocal->eventMouseButtonPressed += MyGUI::newDelegate(this, &MapWindow::onDragStart);
LocalMapBase::init(mLocalMap, mPlayerArrowLocal, this);
}
void MapWindow::renderGlobalMap(Loading::Listener* loadingListener)
{
mGlobalMapRender = new MWRender::GlobalMap("");
mGlobalMapRender->render(loadingListener);
mGlobalMap->setCanvasSize (mGlobalMapRender->getWidth(), mGlobalMapRender->getHeight());
mGlobalMapImage->setSize(mGlobalMapRender->getWidth(), mGlobalMapRender->getHeight());
mGlobalMapImage->setImageTexture("GlobalMap.png");
mGlobalMapOverlay->setImageTexture("GlobalMapOverlay");
}
MapWindow::~MapWindow()
{
delete mGlobalMapRender;
}
void MapWindow::setCellName(const std::string& cellName)
{
setTitle("#{sCell=" + cellName + "}");
}
void MapWindow::addVisitedLocation(const std::string& name, int x, int y)
{
float worldX, worldY;
mGlobalMapRender->cellTopLeftCornerToImageSpace (x, y, worldX, worldY);
MyGUI::IntCoord widgetCoord(
worldX * mGlobalMapRender->getWidth()+6,
worldY * mGlobalMapRender->getHeight()+6,
12, 12);
static int _counter=0;
MyGUI::Button* markerWidget = mGlobalMapOverlay->createWidget<MyGUI::Button>("ButtonImage",
widgetCoord, MyGUI::Align::Default);
markerWidget->setImageResource("DoorMarker");
markerWidget->setUserString("ToolTipType", "Layout");
markerWidget->setUserString("ToolTipLayout", "TextToolTipOneLine");
markerWidget->setUserString("Caption_TextOneLine", name);
++_counter;
markerWidget = mEventBoxGlobal->createWidget<MyGUI::Button>("",
widgetCoord, MyGUI::Align::Default);
markerWidget->setNeedMouseFocus (true);
markerWidget->setUserString("ToolTipType", "Layout");
markerWidget->setUserString("ToolTipLayout", "TextToolTipOneLine");
markerWidget->setUserString("Caption_TextOneLine", name);
CellId cell;
cell.first = x;
cell.second = y;
mMarkers.push_back(cell);
}
void MapWindow::cellExplored(int x, int y)
{
mQueuedToExplore.push_back(std::make_pair(x,y));
}
void MapWindow::onFrame(float dt)
{
LocalMapBase::onFrame(dt);
for (std::vector<CellId>::iterator it = mQueuedToExplore.begin(); it != mQueuedToExplore.end(); ++it)
{
mGlobalMapRender->exploreCell(it->first, it->second);
}
mQueuedToExplore.clear();
NoDrop::onFrame(dt);
}
void MapWindow::onDragStart(MyGUI::Widget* _sender, int _left, int _top, MyGUI::MouseButton _id)
{
if (_id!=MyGUI::MouseButton::Left) return;
mLastDragPos = MyGUI::IntPoint(_left, _top);
}
void MapWindow::onMouseDrag(MyGUI::Widget* _sender, int _left, int _top, MyGUI::MouseButton _id)
{
if (_id!=MyGUI::MouseButton::Left) return;
MyGUI::IntPoint diff = MyGUI::IntPoint(_left, _top) - mLastDragPos;
if (!mGlobal)
mLocalMap->setViewOffset( mLocalMap->getViewOffset() + diff );
else
mGlobalMap->setViewOffset( mGlobalMap->getViewOffset() + diff );
mLastDragPos = MyGUI::IntPoint(_left, _top);
}
void MapWindow::onWorldButtonClicked(MyGUI::Widget* _sender)
{
mGlobal = !mGlobal;
mGlobalMap->setVisible(mGlobal);
mLocalMap->setVisible(!mGlobal);
mButton->setCaptionWithReplacing( mGlobal ? "#{sLocal}" :
"#{sWorld}");
if (mGlobal)
globalMapUpdatePlayer ();
}
void MapWindow::onPinToggled()
{
MWBase::Environment::get().getWindowManager()->setMinimapVisibility(!mPinned);
}
void MapWindow::open()
{
// force markers to foreground
for (unsigned int i=0; i<mGlobalMapOverlay->getChildCount (); ++i)
{
if (mGlobalMapOverlay->getChildAt (i)->getName().substr(0,4) == "Door")
mGlobalMapOverlay->getChildAt (i)->castType<MyGUI::Button>()->setImageResource("DoorMarker");
}
globalMapUpdatePlayer();
mPlayerArrowGlobal->setImageTexture ("textures\\compass.dds");
}
void MapWindow::globalMapUpdatePlayer ()
{
// For interiors, position is set by WindowManager via setGlobalMapPlayerPosition
if (MWBase::Environment::get().getWorld ()->isCellExterior ())
{
Ogre::Vector3 pos = MWBase::Environment::get().getWorld ()->getPlayerPtr().getRefData ().getBaseNode ()->_getDerivedPosition ();
Ogre::Quaternion orient = MWBase::Environment::get().getWorld ()->getPlayerPtr().getRefData ().getBaseNode ()->_getDerivedOrientation ();
Ogre::Vector2 dir (orient.yAxis ().x, orient.yAxis().y);
float worldX, worldY;
mGlobalMapRender->worldPosToImageSpace (pos.x, pos.y, worldX, worldY);
worldX *= mGlobalMapRender->getWidth();
worldY *= mGlobalMapRender->getHeight();
mPlayerArrowGlobal->setPosition(MyGUI::IntPoint(worldX - 16, worldY - 16));
MyGUI::ISubWidget* main = mPlayerArrowGlobal->getSubWidgetMain();
MyGUI::RotatingSkin* rotatingSubskin = main->castType<MyGUI::RotatingSkin>();
rotatingSubskin->setCenter(MyGUI::IntPoint(16,16));
float angle = std::atan2(dir.x, dir.y);
rotatingSubskin->setAngle(angle);
// set the view offset so that player is in the center
MyGUI::IntSize viewsize = mGlobalMap->getSize();
MyGUI::IntPoint viewoffs(0.5*viewsize.width - worldX, 0.5*viewsize.height - worldY);
mGlobalMap->setViewOffset(viewoffs);
}
}
void MapWindow::notifyPlayerUpdate ()
{
globalMapUpdatePlayer ();
}
void MapWindow::notifyMapChanged ()
{
// workaround to prevent the map from drawing on top of the button
MyGUI::IntCoord oldCoord = mButton->getCoord ();
MyGUI::Gui::getInstance().destroyWidget (mButton);
mButton = mMainWidget->createWidget<MWGui::Widgets::AutoSizedButton>("MW_Button",
oldCoord, MyGUI::Align::Bottom | MyGUI::Align::Right);
mButton->setProperty ("ExpandDirection", "Left");
mButton->eventMouseButtonClick += MyGUI::newDelegate(this, &MapWindow::onWorldButtonClicked);
mButton->setCaptionWithReplacing( mGlobal ? "#{sLocal}" :
"#{sWorld}");
}
void MapWindow::setGlobalMapPlayerPosition(float worldX, float worldY)
{
float x, y;
mGlobalMapRender->worldPosToImageSpace (worldX, worldY, x, y);
x *= mGlobalMapRender->getWidth();
y *= mGlobalMapRender->getHeight();
mPlayerArrowGlobal->setPosition(MyGUI::IntPoint(x - 16, y - 16));
// set the view offset so that player is in the center
MyGUI::IntSize viewsize = mGlobalMap->getSize();
MyGUI::IntPoint viewoffs(0.5*viewsize.width - x, 0.5*viewsize.height - y);
mGlobalMap->setViewOffset(viewoffs);
}
void MapWindow::clear()
{
mMarkers.clear();
mGlobalMapRender->clear();
while (mEventBoxGlobal->getChildCount())
MyGUI::Gui::getInstance().destroyWidget(mEventBoxGlobal->getChildAt(0));
while (mGlobalMapOverlay->getChildCount())
MyGUI::Gui::getInstance().destroyWidget(mGlobalMapOverlay->getChildAt(0));
}
void MapWindow::write(ESM::ESMWriter &writer, Loading::Listener& progress)
{
ESM::GlobalMap map;
mGlobalMapRender->write(map);
map.mMarkers = mMarkers;
writer.startRecord(ESM::REC_GMAP);
map.save(writer);
writer.endRecord(ESM::REC_GMAP);
progress.increaseProgress();
}
void MapWindow::readRecord(ESM::ESMReader &reader, int32_t type)
{
if (type == ESM::REC_GMAP)
{
ESM::GlobalMap map;
map.load(reader);
mGlobalMapRender->read(map);
for (std::vector<ESM::GlobalMap::CellId>::iterator it = map.mMarkers.begin(); it != map.mMarkers.end(); ++it)
{
const ESM::Cell* cell = MWBase::Environment::get().getWorld()->getStore().get<ESM::Cell>().search(it->first, it->second);
if (cell && !cell->mName.empty())
addVisitedLocation(cell->mName, it->first, it->second);
}
}
}
}
| gpl-3.0 |
UpperSetting/DotNetOpenServerSDK | Protocols/Hello/Windows/HelloProtocolShared/HelloProtocol.cs | 1687 | /*
Copyright 2015-2016 Upper Setting Corporation
This file is part of DotNetOpenServer SDK.
DotNetOpenServer SDK 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.
DotNetOpenServer SDK 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
DotNetOpenServer SDK. If not, see <http://www.gnu.org/licenses/>.
*/
namespace US.OpenServer.Protocols.Hello
{
/// <summary>
/// Base abstract class for the Hello Protocol implementation.
/// </summary>
public abstract class HelloProtocol : ProtocolBase
{
/// <summary>
/// The unique protocol identifier
/// </summary>
public const ushort PROTOCOL_IDENTIFIER = 0x000A;
/// <summary>
/// Creates a HelloProtocol object.
/// </summary>
protected HelloProtocol()
{
}
/// <summary>
/// Log's a message.
/// </summary>
/// <param name="level">A Level that specifies the priority of the message.</param>
/// <param name="message">A string that contains the message.</param>
protected override void Log(Level level, string message)
{
Session.Log(level, string.Format("[Hello] {0}", message));
}
}
}
| gpl-3.0 |
drkpkg/artemisa | db/migrate/20151026024705_create_servicios.rb | 316 | class CreateServicios < ActiveRecord::Migration
def change
create_table :servicios do |t|
t.string :nombre_servicio
t.string :descripcion_servicio
t.references :@cliente, "empleado_id", index: true
t.references :@cliente, "vendedor_id", index: true
t.timestamps
end
end
end
| gpl-3.0 |
Cbsoftware/pressureNETServer-Java | src/ca/cumulonimbus/barometer/Unit.java | 1320 | package ca.cumulonimbus.barometer;
/*
* Units
* Millibars (mbar)
Hectopascals (hPa)
Standard Atmosphere (atm)
Millimeteres of Mercury (mmHg)
*/
public class Unit {
double valueInMb;
String abbrev;
// Conversion factors from http://www.csgnetwork.com/meteorologyconvtbl.html
public double convertToPreferredUnit() {
try {
if(abbrev.contains("mbar")) {
// No change. reading comes to us in mbar.
return valueInMb;
} else if(abbrev.contains("hPa")) {
// mbar = hpa.
return valueInMb;
} else if(abbrev.contains("atm")) {
return valueInMb * 0.000986923;
} else if(abbrev.contains("kPa")) {
return valueInMb * 0.1;
} else if(abbrev.contains("mmHg")) {
return valueInMb * 0.75006;
} else if(abbrev.contains("inHg")) {
return valueInMb * 0.02961;
} else {
return valueInMb;
}
} catch(Exception e) {
return valueInMb;
}
}
public String getDisplayText() {
return convertToPreferredUnit() + abbrev;
}
public Unit(String abbrev) {
this.abbrev = abbrev;
}
public double getValueInMb() {
return valueInMb;
}
public void setValue(double valueInMb) {
this.valueInMb = valueInMb;
}
public String getAbbreviation() {
return abbrev;
}
public void setAbbreviation(String abbreviation) {
this.abbrev = abbreviation;
}
} | gpl-3.0 |
channainfo/reminder | vendor/assets/javascripts/angular-toggle-switch.js | 2996 | angular.module('toggle-switch', ['ng']).directive('toggleSwitch', function($compile) {
return {
restrict: 'EA',
replace: true,
scope: {
model: '=',
disabled: '@',
onLabel: '@',
offLabel: '@',
knobLabel: '@',
html: '=',
onChange: '&'
},
template: '<div class="ats-switch" ng-click="toggle()" ng-class="{ \'disabled\': disabled }"><div class="switch-animate" ng-class="{\'switch-off\': !model, \'switch-on\': model}"><span class="switch-left"></span><span class="knob"></span><span class="switch-right"></span></div></div>',
controller: function($scope) {
$scope.toggle = function toggle() {
if (!$scope.disabled) {
$scope.model = !$scope.model;
}
$scope.onChange();
};
},
compile: function(element, attrs) {
if (angular.isUndefined(attrs.onLabel)) {
attrs.onLabel = 'On';
}
if (angular.isUndefined(attrs.offLabel)) {
attrs.offLabel = 'Off';
}
if (angular.isUndefined(attrs.knobLabel)) {
attrs.knobLabel = '\u00a0';
}
if (angular.isUndefined(attrs.disabled)) {
attrs.disabled = false;
}
if (angular.isUndefined(attrs.html)) {
attrs.html = false;
}
return function postLink(scope, iElement, iAttrs, controller) {
var bindSpan = function(span, html) {
span = angular.element(span);
var bindAttributeName = (html === true) ? 'ng-bind-html' : 'ng-bind';
// remove old ng-bind attributes
span.removeAttr('ng-bind-html');
span.removeAttr('ng-bind');
if (angular.element(span).hasClass("switch-left"))
span.attr(bindAttributeName, 'onLabel');
if (span.hasClass("knob"))
span.attr(bindAttributeName, 'knobLabel');
if (span.hasClass("switch-right"))
span.attr(bindAttributeName, 'offLabel');
$compile(span)(scope, function(cloned, scope) {
span.replaceWith(cloned);
});
};
// add ng-bind attribute to each span element.
// NOTE: you need angular-sanitize to use ng-bind-html
var bindSwitch = function(iElement, html) {
angular.forEach(iElement[0].children[0].children, function(span, index) {
bindSpan(span, html);
});
};
scope.$watch('html', function(newValue) {
bindSwitch(iElement, newValue);
});
};
}
};
});
| gpl-3.0 |
MatiRg/colobot | src/object/object_manager.cpp | 14250 | /*
* This file is part of the Colobot: Gold Edition source code
* Copyright (C) 2001-2016, Daniel Roux, EPSITEC SA & TerranovaTeam
* http://epsitec.ch; http://colobot.info; http://github.com/colobot
*
* 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://gnu.org/licenses
*/
#include "object/object_manager.h"
#include "common/global.h"
#include "common/make_unique.h"
#include "math/all.h"
#include "object/object.h"
#include "object/object_create_exception.h"
#include "object/object_create_params.h"
#include "object/object_factory.h"
#include "object/old_object.h"
#include "object/auto/auto.h"
#include "physics/physics.h"
#include <algorithm>
template<> CObjectManager* CSingleton<CObjectManager>::m_instance = nullptr;
CObjectManager::CObjectManager(Gfx::CEngine* engine,
Gfx::CTerrain* terrain,
Gfx::COldModelManager* oldModelManager,
Gfx::CModelManager* modelManager,
Gfx::CParticle* particle)
: m_objectFactory(MakeUnique<CObjectFactory>(engine,
terrain,
oldModelManager,
modelManager,
particle)),
m_nextId(0),
m_activeObjectIterators(0),
m_shouldCleanRemovedObjects(false)
{
}
CObjectManager::~CObjectManager()
{
}
bool CObjectManager::DeleteObject(CObject* instance)
{
assert(instance != nullptr);
// TODO: temporarily...
auto oldObj = dynamic_cast<COldObject*>(instance);
if (oldObj != nullptr)
oldObj->DeleteObject();
auto it = m_objects.find(instance->GetID());
if (it != m_objects.end())
{
it->second.reset();
m_shouldCleanRemovedObjects = true;
return true;
}
return false;
}
void CObjectManager::CleanRemovedObjectsIfNeeded()
{
if (m_activeObjectIterators != 0)
return;
if (! m_shouldCleanRemovedObjects)
return;
auto it = m_objects.begin();
if (it != m_objects.end())
{
if (it->second == nullptr)
it = m_objects.erase(it);
}
m_shouldCleanRemovedObjects = false;
}
void CObjectManager::DeleteAllObjects()
{
for (auto& it : m_objects)
{
// TODO: temporarily...
auto oldObj = dynamic_cast<COldObject*>(it.second.get());
if (oldObj != nullptr)
{
bool all = true;
oldObj->DeleteObject(all);
}
}
m_objects.clear();
m_nextId = 0;
}
CObject* CObjectManager::GetObjectById(unsigned int id)
{
if (m_objects.count(id) == 0) return nullptr;
return m_objects[id].get();
}
CObject* CObjectManager::GetObjectByRank(unsigned int id)
{
auto objects = GetAllObjects();
auto it = objects.begin();
for (unsigned int i = 0; i < id && it != objects.end(); i++, ++it);
if (it == objects.end()) return nullptr;
return *it;
}
CObject* CObjectManager::CreateObject(ObjectCreateParams params)
{
if (params.id < 0)
{
params.id = m_nextId;
m_nextId++;
}
else
{
if (params.id >= m_nextId)
{
m_nextId = params.id + 1;
}
}
assert(m_objects.find(params.id) == m_objects.end());
auto objectUPtr = m_objectFactory->CreateObject(params);
if (objectUPtr == nullptr)
throw CObjectCreateException("Something went wrong in CObjectFactory", params.type);
CObject* objectPtr = objectUPtr.get();
m_objects[params.id] = std::move(objectUPtr);
return objectPtr;
}
CObject* CObjectManager::CreateObject(Math::Vector pos, float angle, ObjectType type, float power)
{
ObjectCreateParams params;
params.pos = pos;
params.angle = angle;
params.type = type;
params.power = power;
return CreateObject(params);
}
std::vector<CObject*> CObjectManager::GetObjectsOfTeam(int team)
{
std::vector<CObject*> result;
for (CObject* object : GetAllObjects())
{
if (object->GetTeam() == team)
{
result.push_back(object);
}
}
return result;
}
bool CObjectManager::TeamExists(int team)
{
if(team == 0) return true;
for (CObject* object : GetAllObjects())
{
if (!object->GetActive())
continue;
if (object->GetTeam() == team)
return true;
}
return false;
}
void CObjectManager::DestroyTeam(int team, DestructionType destructionType)
{
assert(team != 0);
for (CObject* object : GetAllObjects())
{
if (object->GetTeam() == team)
{
if (object->Implements(ObjectInterfaceType::Destroyable))
{
dynamic_cast<CDestroyableObject*>(object)->DestroyObject(destructionType);
}
else
{
DeleteObject(object);
}
}
}
}
int CObjectManager::CountObjectsImplementing(ObjectInterfaceType interface)
{
int count = 0;
for (CObject* object : GetAllObjects())
{
if (object->Implements(interface))
count++;
}
return count;
}
std::vector<CObject*> CObjectManager::RadarAll(CObject* pThis, ObjectType type, float angle, float focus, float minDist, float maxDist, bool furthest, RadarFilter filter, bool cbotTypes)
{
std::vector<ObjectType> types;
if (type != OBJECT_NULL)
types.push_back(type);
return RadarAll(pThis, types, angle, focus, minDist, maxDist, furthest, filter, cbotTypes);
}
std::vector<CObject*> CObjectManager::RadarAll(CObject* pThis, std::vector<ObjectType> type, float angle, float focus, float minDist, float maxDist, bool furthest, RadarFilter filter, bool cbotTypes)
{
Math::Vector iPos;
float iAngle;
if (pThis != nullptr)
{
iPos = pThis->GetPosition();
iAngle = pThis->GetRotationY();
iAngle = Math::NormAngle(iAngle); // 0..2*Math::PI
}
else
{
iPos = Math::Vector();
iAngle = 0.0f;
}
return RadarAll(pThis, iPos, iAngle, type, angle, focus, minDist, maxDist, furthest, filter, cbotTypes);
}
std::vector<CObject*> CObjectManager::RadarAll(CObject* pThis, Math::Vector thisPosition, float thisAngle, ObjectType type, float angle, float focus, float minDist, float maxDist, bool furthest, RadarFilter filter, bool cbotTypes)
{
std::vector<ObjectType> types;
if (type != OBJECT_NULL)
types.push_back(type);
return RadarAll(pThis, thisPosition, thisAngle, types, angle, focus, minDist, maxDist, furthest, filter, cbotTypes);
}
std::vector<CObject*> CObjectManager::RadarAll(CObject* pThis, Math::Vector thisPosition, float thisAngle, std::vector<ObjectType> type, float angle, float focus, float minDist, float maxDist, bool furthest, RadarFilter filter, bool cbotTypes)
{
CObject *pObj;
Math::Vector iPos, oPos;
float iAngle, d, a;
ObjectType oType;
minDist *= g_unit;
maxDist *= g_unit;
iPos = thisPosition;
iAngle = thisAngle+angle;
iAngle = Math::NormAngle(iAngle); // 0..2*Math::PI
int filter_team = filter & 0xFF;
RadarFilter filter_flying = static_cast<RadarFilter>(filter & (FILTER_ONLYLANDING | FILTER_ONLYFLYING));
RadarFilter filter_enemy = static_cast<RadarFilter>(filter & (FILTER_FRIENDLY | FILTER_ENEMY | FILTER_NEUTRAL));
// Use a multimap to allow for multiple objects at exactly the same distance
// from the origin to be returned.
std::multimap<float, CObject*> best;
for ( auto it = m_objects.begin() ; it != m_objects.end() ; ++it )
{
pObj = it->second.get();
if ( pObj == pThis ) continue; // pThis may be nullptr but it doesn't matter
if (pObj == nullptr) continue;
if (IsObjectBeingTransported(pObj)) continue;
if ( !pObj->GetDetectable() ) continue;
if ( pObj->GetProxyActivate() ) continue;
oType = pObj->GetType();
if (cbotTypes)
{
// TODO: handle this differently (new class describing types? CObjectType::GetBaseType()?)
if ( oType == OBJECT_RUINmobilew2 ||
oType == OBJECT_RUINmobilet1 ||
oType == OBJECT_RUINmobilet2 ||
oType == OBJECT_RUINmobiler1 ||
oType == OBJECT_RUINmobiler2 )
{
oType = OBJECT_RUINmobilew1; // any ruin
}
if ( oType == OBJECT_BARRIER2 ||
oType == OBJECT_BARRIER3 ||
oType == OBJECT_BARRICADE0 ||
oType == OBJECT_BARRICADE1 ) // barriers?
{
oType = OBJECT_BARRIER1; // any barrier
}
// END OF TODO
}
if ( std::find(type.begin(), type.end(), oType) == type.end() && type.size() > 0 ) continue;
if ( (oType == OBJECT_TOTO || oType == OBJECT_CONTROLLER) && type.size() == 0 ) continue; // allow OBJECT_TOTO and OBJECT_CONTROLLER only if explicitly asked in type parameter
if ( filter_flying == FILTER_ONLYLANDING )
{
if ( pObj->Implements(ObjectInterfaceType::Movable) )
{
CPhysics* physics = dynamic_cast<CMovableObject*>(pObj)->GetPhysics();
if ( physics != nullptr )
{
if ( !physics->GetLand() ) continue;
}
}
}
if ( filter_flying == FILTER_ONLYFLYING )
{
if ( !pObj->Implements(ObjectInterfaceType::Movable) ) continue;
CPhysics* physics = dynamic_cast<CMovableObject*>(pObj)->GetPhysics();
if ( physics == nullptr ) continue;
if ( physics->GetLand() ) continue;
}
if ( filter_team != 0 && pObj->GetTeam() != filter_team )
continue;
if( pThis != nullptr )
{
RadarFilter enemy = FILTER_NONE;
if ( pObj->GetTeam() == 0 ) enemy = static_cast<RadarFilter>(enemy | FILTER_NEUTRAL);
if ( pObj->GetTeam() != 0 && pObj->GetTeam() == pThis->GetTeam() ) enemy = static_cast<RadarFilter>(enemy | FILTER_FRIENDLY);
if ( pObj->GetTeam() != 0 && pObj->GetTeam() != pThis->GetTeam() ) enemy = static_cast<RadarFilter>(enemy | FILTER_ENEMY);
if ( filter_enemy != 0 && (filter_enemy & enemy) == 0 ) continue;
}
oPos = pObj->GetPosition();
d = Math::DistanceProjected(iPos, oPos);
if ( d < minDist || d > maxDist ) continue; // too close or too far?
a = Math::RotateAngle(oPos.x-iPos.x, iPos.z-oPos.z); // CW !
if ( Math::TestAngle(a, iAngle-focus/2.0f, iAngle+focus/2.0f) || focus >= Math::PI*2.0f )
{
best.insert(std::make_pair(d, pObj));
}
}
std::vector<CObject*> sortedBest;
if (!furthest)
{
for (auto it = best.begin(); it != best.end(); ++it)
{
sortedBest.push_back(it->second);
}
}
else
{
for (auto it = best.rbegin(); it != best.rend(); ++it)
{
sortedBest.push_back(it->second);
}
}
return sortedBest;
}
CObject* CObjectManager::Radar(CObject* pThis, ObjectType type, float angle, float focus, float minDist, float maxDist, bool furthest, RadarFilter filter, bool cbotTypes)
{
std::vector<CObject*> best = RadarAll(pThis, type, angle, focus, minDist, maxDist, furthest, filter, cbotTypes);
return best.size() > 0 ? best[0] : nullptr;
}
CObject* CObjectManager::Radar(CObject* pThis, std::vector<ObjectType> type, float angle, float focus, float minDist, float maxDist, bool furthest, RadarFilter filter, bool cbotTypes)
{
std::vector<CObject*> best = RadarAll(pThis, type, angle, focus, minDist, maxDist, furthest, filter, cbotTypes);
return best.size() > 0 ? best[0] : nullptr;
}
CObject* CObjectManager::Radar(CObject* pThis, Math::Vector thisPosition, float thisAngle, ObjectType type, float angle, float focus, float minDist, float maxDist, bool furthest, RadarFilter filter, bool cbotTypes)
{
std::vector<CObject*> best = RadarAll(pThis, thisPosition, thisAngle, type, angle, focus, minDist, maxDist, furthest, filter, cbotTypes);
return best.size() > 0 ? best[0] : nullptr;
}
CObject* CObjectManager::Radar(CObject* pThis, Math::Vector thisPosition, float thisAngle, std::vector<ObjectType> type, float angle, float focus, float minDist, float maxDist, bool furthest, RadarFilter filter, bool cbotTypes)
{
std::vector<CObject*> best = RadarAll(pThis, thisPosition, thisAngle, type, angle, focus, minDist, maxDist, furthest, filter, cbotTypes);
return best.size() > 0 ? best[0] : nullptr;
}
CObject* CObjectManager::FindNearest(CObject* pThis, ObjectType type, float maxDist, bool cbotTypes)
{
return Radar(pThis, type, 0.0f, Math::PI*2.0f, 0.0f, maxDist, false, FILTER_NONE, cbotTypes);
}
CObject* CObjectManager::FindNearest(CObject* pThis, std::vector<ObjectType> type, float maxDist, bool cbotTypes)
{
return Radar(pThis, type, 0.0f, Math::PI*2.0f, 0.0f, maxDist, false, FILTER_NONE, cbotTypes);
}
CObject* CObjectManager::FindNearest(CObject* pThis, Math::Vector thisPosition, ObjectType type, float maxDist, bool cbotTypes)
{
return Radar(pThis, thisPosition, 0.0f, type, 0.0f, Math::PI*2.0f, 0.0f, maxDist, false, FILTER_NONE, cbotTypes);
}
CObject* CObjectManager::FindNearest(CObject* pThis, Math::Vector thisPosition, std::vector<ObjectType> type, float maxDist, bool cbotTypes)
{
return Radar(pThis, thisPosition, 0.0f, type, 0.0f, Math::PI*2.0f, 0.0f, maxDist, false, FILTER_NONE, cbotTypes);
}
| gpl-3.0 |
JoyTeam/metagam | mg/core/nginx.py | 3971 | #!/usr/bin/python2.6
# This file is a part of Metagam project.
#
# Metagam 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
# any later version.
#
# Metagam 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 Metagam. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
from concurrence import Tasklet
from mg.core.cluster import DBCluster
import subprocess
import mg
import re
re_class = re.compile('^upstream (\S+) {')
class Nginx(mg.Module):
def register(self):
self.rhook("nginx.register", self.register_nginx)
self.rhook("core.fastidle", self.fastidle)
self.rhook("ngx-nginx.reload", self.reload, priv="public")
def register_nginx(self):
inst = self.app().inst
# Load nginx configuration
self.nginx_config = inst.conf("nginx", "conffile", "/etc/nginx/nginx-metagam.conf")
self.nginx_upstreams = set()
self.nginx_backends = None
self.nginx_nextcheck = ""
try:
with open(self.nginx_config, "r") as f:
for line in f:
m = re_class.match(line)
if m:
cls = m.group(1)
self.nginx_upstreams.add(cls)
except IOError as e:
pass
# Register service
int_app = inst.int_app
srv = mg.SingleApplicationWebService(self.app(), "%s-nginx" % inst.instid, "nginx", "ngx")
srv.serve_any_port()
int_app.call("cluster.register-service", srv)
def fastidle(self):
if self.now() < self.nginx_nextcheck:
return
self.nginx_nextcheck = self.now(10)
self.nginx_check()
def reload(self):
self.nginx_nextcheck = ""
self.call("web.response_json", {"retval": 1})
def nginx_check(self):
daemons = self.obj(DBCluster, "daemons", silent=True)
backends = {}
for cls in self.nginx_upstreams:
backends[cls] = set()
for dmnid, dmninfo in daemons.data.iteritems():
for svcid, svcinfo in dmninfo.get("services", {}).iteritems():
webbackend = svcinfo.get("webbackend")
if not webbackend:
continue
port = svcinfo.get("webbackendport")
if port is None:
port = svcinfo.get("port")
ent = "%s:%d" % (svcinfo.get("addr"), port)
if webbackend not in backends:
backends[webbackend] = set()
self.nginx_upstreams.add(webbackend)
backends[webbackend].add(ent)
if self.nginx_backends != backends:
self.debug("Nginx backends: %s", "%s" % backends)
try:
with open(self.nginx_config, "w") as f:
for cls, lst in backends.iteritems():
print("upstream %s {" % cls, file=f)
if lst:
for srv in lst:
print("\tserver %s;" % srv, file=f)
else:
print("\tserver 127.0.0.1:65534;", file=f)
print("}", file=f)
subprocess.check_call(["/usr/bin/sudo", "/etc/init.d/nginx", "reload"])
self.nginx_backends = backends
except IOError as e:
self.error("Error writing %s: %s", self.nginx_config, e)
except subprocess.CalledProcessError as e:
self.error("Error reloading nginx: %s", e)
| gpl-3.0 |
SivilTaram/MyFlask | API/WeChatUtil/WeChat.py | 12748 | # -*- coding:utf-8 -*-
"""
微信企业号消息接口封装模块
封装了多媒体消息接口以及普通文本消息接口
"""
import os
import sys
import time
import copy
import json
import logging
import tempfile
import mimetypes
import flask
import requests
import MyFlask.API.WeChatUtil.CryptoUtil as utils
'''
企业号请求URL
'''
WEIXIN_URL = 'https://qyapi.weixin.qq.com'
class WeChatBase(object):
"""
微信消息发送与接收类的公共基类
负责进行日志的初始化工作等
"""
logger_ok = False
def __init__(self, appname, ini_name):
"""
基类构造函数
@param appname: 应用名称
@param ini_name: 配置文件路径
@return:
"""
self.appname = appname
if ini_name:
self.config = utils.get_config(ini_name)
else:
self.config = utils.get_config()
self.logger = logging.getLogger('easy_wechat')
self.init_logger()
def init_logger(self):
"""
初始化日志模块相关参数
@return: None
"""
if WeChatBase.logger_ok:
return
self.logger.setLevel(logging.INFO)
log_path = self.config.get('system', 'log_path')
log_name = self.config.get('system', 'log_name')
if not (os.path.exists(log_path) and os.path.isdir(log_path)):
log_path = tempfile.gettempdir()
if not log_name:
log_name = 'easy_wechat.log'
# 日志格式化
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 记录日志到文件
log_handler = logging.FileHandler(os.path.join(log_path, log_name))
log_handler.setFormatter(formatter)
self.logger.addHandler(log_handler)
# 记录日志到stderr
stream_handler = logging.StreamHandler(sys.stderr)
stream_handler.setFormatter(formatter)
self.logger.addHandler(stream_handler)
# 注意日志模块只需要被初始化一次
# 所以要在这里进行标记
WeChatBase.logger_ok = True
class WeChatClient(WeChatBase):
"""
消息发送类
"""
def __init__(self, appname, ini_name=None):
"""
构造函数
@param appname: 应用名称, 需要与配置文件中section对应
@return: WeChatClient对象实例
"""
super(WeChatClient, self).__init__(appname, ini_name)
self.CorpID = self.config.get(self.appname, 'corpid')
self.Secret = self.config.get(self.appname, 'secret')
self.AppID = self.config.get(self.appname, 'appid')
@staticmethod
def url_request(url, get=True, data=''):
"""
请求指定的URL
@param url: 字符串
@param get: 是否使用GET方法
@param data: 附加数据(POST)
@return: 转换为dict的请求结果
"""
try:
if get:
req = requests.get(url)
else:
req = requests.post(url, data)
except Exception as e:
# wrap exception message with more detail
raise type(e)('unable to retrieve URL: %s with exception: %s', (url, e.message))
else:
try:
res_dict = json.loads(req.content)
except Exception as e:
raise type(e)('invalid json content: %s with exception: %s',
(req.content, e.message))
return res_dict
def get_token(self):
"""
获取发送消息时的验证token
@return: token字符串
"""
token_url = '%s/cgi-bin/gettoken?corpid=%s&corpsecret=%s' \
% (WEIXIN_URL, self.CorpID, self.Secret)
res = self.url_request(token_url)
return res['access_token']
def upload_media(self, file_type, file_path):
"""
上传临时媒体素材到微信服务器
@param file_type: 文件类型
@param file_path: 文件绝对路径
@return: 服务器返回值dict
"""
def make_err_return(err_msg):
"""
一个简单的内部函数, 将错误信息包装并返回
@param err_msg: 错误信息
@return:
"""
return {
'errcode': -1,
'errmsg': err_msg,
}
if file_type not in ('image', 'voice', 'video', 'file'):
errmsg = 'Invalid media/message format'
self.logger.error(errmsg)
return make_err_return(errmsg)
try:
post_url = '%s/cgi-bin/media/upload?access_token=%s&type=%s' \
% (WEIXIN_URL, self.get_token(), file_type)
except Exception as e:
self.logger.error(e.message)
return make_err_return(e.message)
try:
file_dir, file_name = os.path.split(file_path)
files = {'file': (file_name, open(file_path, 'rb'),
mimetypes.guess_type(file_path, strict=False), {'Expires': '0'})}
r = requests.post(post_url, files=files)
except Exception as e:
self.logger.error(e.message)
return make_err_return(e.message)
try:
res_dict = json.loads(r.content)
except Exception as e:
raise type(e)('invalid json content: %s with exception: %s',
(r.content, e.message))
return res_dict
def send_media(self, media_type, media_content, touser,
toparty='', totag=''):
"""
发送消息/视频/图片给指定的用户
@param media_type: 消息类型
@param media_content: 消息内容, 是一个dict, 包含具体的描述信息
@param touser: 用户名, '|'分割
@param toparty: 分组名, '|'分割
@param totag: 标签名, '|'分割
@return: 服务器返回值dict
"""
if media_type not in ('text', 'image', 'voice', 'video', 'file'):
errmsg = 'Invalid media/message format'
self.logger.error(errmsg)
return {
'errcode': -1,
'errmsg': errmsg,
}
try:
send_url = '%s/cgi-bin/message/send?access_token=%s' \
% (WEIXIN_URL, self.get_token())
except Exception as e:
# since all error code definitions of wechat is unknown
# we simply just return -1 as our error code
self.logger.error(e.message)
return {
'errcode': -1,
'errmsg': e.message,
}
message_data = {
"touser": touser,
"toparty": toparty,
"totag": totag,
"msgtype": media_type,
"agentid": self.AppID,
media_type: media_content,
"safe": "0"
}
raw_data = json.dumps(message_data, ensure_ascii=False)
try:
res = self.url_request(send_url, False, raw_data.encode('utf-8'))
except Exception as e:
sys.stderr.write(str(e) + '\n')
errmsg = 'failed when post json data: %s to wechat server with exception: %s' \
% (raw_data, e.message)
self.logger.error(errmsg)
return {
'errcode': -1,
'errmsg': errmsg,
}
if int(res['errcode']) == 0:
self.logger.info('send message successful to %s' % touser)
else:
self.logger.error('send message failed with error: %s' % res['errmsg'])
return res
class WeChatServer(WeChatBase):
"""
消息接收类(server)
"""
def __init__(self, appname, ini_name, flaskapp):
"""
构造函数
@param flaskapp: 已经实例化的flask应用
@param appname: APP名称, 与配置文件中section对应
@return: 构造的对象
"""
super(WeChatServer, self).__init__(appname, ini_name)
self.callback_funcs = {
'text': None,
'image': None,
'voice': None,
'video': None,
'shortvideo': None,
'location': None,
}
token = self.config.get(appname, 'token')
aes_key = self.config.get(appname, 'encoding_aes_key')
corp_id = self.config.get(appname, 'corpid')
self.wxcpt = utils.WXBizMsgCrypt(token, aes_key, corp_id)
# flaskapp为api blueprint
self.app = flaskapp
# 为微信添加路由规则
self.app.add_url_rule('/' + self.config.get('system', 'route_name'),
None, self.callback, methods=['GET', 'POST'])
def register_callback(self, msg_type, func):
"""
注册收到某种类型消息后的回调函数
@param msg_type: 消息类型
@param func: 回调函数
@return: None
"""
if msg_type in self.callback_funcs:
self.callback_funcs[msg_type] = func
else:
raise KeyError('Invalid media type.')
def callback(self):
"""
响应对/weixin请求的函数
@return: 返回响应内容
"""
method = flask.request.method
if method == 'GET':
return self.verify()
elif method == 'POST':
return self.do_reply()
else:
self.logger.error('unsupported method, return 405 method not allowed')
# unknown method, return 405 method not allowed
flask.abort(405)
def verify(self):
"""
验证接口可用性
@return: 回显字符串
"""
verify_msg_sig = flask.request.args.get('msg_signature', '')
timestamp = flask.request.args.get('timestamp', '')
nonce = flask.request.args.get('nonce', '')
echo_str = flask.request.args.get('echostr', '')
# do decoding and return
ret, echo_str_res = self.wxcpt.VerifyURL(verify_msg_sig, timestamp, nonce, echo_str)
if ret != 0:
self.logger.error('verification failed with return value %d' % ret)
# if verification failed, return 403 forbidden
flask.abort(403)
else:
return echo_str_res
def do_reply(self):
"""
根据消息类型调用对应的回调函数进行回复
@return: 回复的消息, 按照微信接口加密
"""
req_msg_sig = flask.request.args.get('msg_signature', '')
timestamp = flask.request.args.get('timestamp', '')
nonce = flask.request.args.get('nonce', '')
req_data = flask.request.data
ret, xml_str = self.wxcpt.DecryptMsg(req_data, req_msg_sig, timestamp, nonce)
if ret == 0:
param_dict = utils.xml_to_dict(xml_str)
msg_type = param_dict.get("MsgType", '')
if msg_type in self.callback_funcs:
callback_func = self.callback_funcs[msg_type]
if callback_func:
# call the callback function and get return message (dict)
res_dict = callback_func(copy.deepcopy(param_dict))
default_params = {
'MsgType': param_dict['MsgType'],
'CreateTime': int(time.time())
}
for key, val in default_params.items():
if not res_dict.get(key, None):
res_dict[key] = val
res_dict['ToUserName'] = param_dict['FromUserName']
res_dict['FromUserName'] = param_dict['ToUserName']
xml_data = utils.dict_to_xml(res_dict)
# encrypted_data 是加密后的回复消息
ret_val, encrypted_data = \
self.wxcpt.EncryptMsg(xml_data, nonce, timestamp)
if ret_val == 0:
self.logger.info('replied \' %s \' to %s' %
(res_dict['Content'],res_dict.get('ToUserName', 'null')))
return flask.Response(encrypted_data, mimetype='text/xml')
# 如果没有正确走完这个流程, 就记录日志返回错误
self.logger.error('request failed with request data: %r' % req_data)
# if decryption failed or all other reasons, return 400 bad request code
flask.abort(400)
#def run(self, *args, **kwargs):
# """
# 启动server循环
# @param args: 参数列表
# @param kwargs: 参数字典
# @return: None
# """
# self.app.run(*args, **kwargs)
| gpl-3.0 |
peijen/TravelExpense | src/ca/ualberta/cs/peijen_travelexpense/ExpenseList.java | 2348 | /*
Travel Expense: travel expense tracking application
Copyright (C) 2015 Chris Lin peijen@ualberta.ca
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 ca.ualberta.cs.peijen_travelexpense;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
public class ExpenseList implements Serializable {
/**
* ExpenseList serialization ID
*/
private static final long serialVersionUID = -3035358862621688030L;
protected ArrayList<Expense> expenseList = null;
protected transient ArrayList<Listener> listeners = null;
public ExpenseList(){
expenseList = new ArrayList<Expense>();
listeners = new ArrayList<Listener>();
}
private ArrayList<Listener> getListeners(){
if(listeners == null){
listeners = new ArrayList<Listener>();
}
return listeners;
}
public Collection<Expense> getExpenses() {
return expenseList;
}
public void addExpense(Expense testExpense) {
expenseList.add(testExpense);
notifyListeners();
}
private void notifyListeners() {
// TODO Auto-generated method stub
for (Listener listener : getListeners()) {
listener.update();
}
}
public void deleteExpense(Expense testExpense) {
expenseList.remove(testExpense);
notifyListeners();
}
public int size() {
return expenseList.size();
}
public boolean contains(Expense testExpense) {
return expenseList.contains(testExpense);
}
public Expense chooseExpense() {
int size = expenseList.size();
/*
if(size<=0){
}
*/
int element = 0;
return expenseList.get(element);
}
public void addListener(Listener l) {
getListeners().add(l);
}
public void removeListener(Listener l) {
getListeners().remove(l);
}
}
| gpl-3.0 |
BukkitDocChinese/BukkitAPI | src/main/java/org/bukkit/BanList.java | 1887 | package org.bukkit;
import java.util.Date;
import java.util.Set;
/**
* 一个ban列表,包含一些 {@link Type} 类型的ban。
*/
public interface BanList {
/**
* 表示一个ban-type 使得 {@link BanList} 可追踪.
*/
public enum Type {
/**
* 被ban玩家名字
*/
NAME,
/**
* 被ban的IP地址
*/
IP,
;
}
/**
* 通过目标获取一个 {@link BanEntry}
*
* @param target 搜索的参数
* @return 返回有关结果,null表示无结果
*/
public BanEntry getBanEntry(String target);
/**
* 添加一个ban到ban列表。如果有一个过去的ban存在,这会更新过去添加的ban。
*
* @param target ban的目标
* @param reason ban的原因, null表示implementation default
* @param expires ban或unban的日期,null表示永久
* @param source ban的来源,null表示implementation default
* @return 最新创建的ban的entry,或者过去/更新的ban
*/
public BanEntry addBan(String target, String reason, Date expires, String source);
/**
* 获得一个包含所有 {@link BanEntry} 在这列表中。
*
* @return an immutable set containing every entry tracked by this list
*/
public Set<BanEntry> getBanEntries();
/**
* 获取目标的 {@link BanEntry} 是否存在,表示一个活动的ban状态。
*
* @param target 所要寻找的目标
* @return 如果 {@link BanEntry} 有这名字存在返回true,表示一个活动的
* ban状态,否则为null。
*/
public boolean isBanned(String target);
/**
* 从列表上删除一个指定目标,因此也会有"not banned"状态.
*
* @param target 要从列表上删除的目标
*/
public void pardon(String target);
}
| gpl-3.0 |
mscuthbert/abjad | abjad/tools/developerscripttools/get_developer_script_classes.py | 1011 | # -*- encoding: utf-8 -*-
import inspect
from abjad.tools import documentationtools
def get_developer_script_classes():
r'''Returns a list of all developer script classes.
'''
from abjad.tools import abjadbooktools
from abjad.tools import developerscripttools
tools_package_paths = []
tools_package_paths.extend(abjadbooktools.__path__)
tools_package_paths.extend(developerscripttools.__path__)
script_classes = []
for tools_package_path in tools_package_paths:
generator = documentationtools.yield_all_classes(
code_root=tools_package_path,
root_package_name='abjad',
)
for developer_script_class in generator:
if developerscripttools.DeveloperScript in \
inspect.getmro(developer_script_class) and \
not inspect.isabstract(developer_script_class):
script_classes.append(developer_script_class)
return list(sorted(script_classes, key=lambda x: x.__name__)) | gpl-3.0 |
vmware/vco-powershel-plugin | powershell/o11nplugin-powershell-core/src/main/java/com/vmware/o11n/plugin/powershell/util/ssh/SSHException.java | 1253 | /*
* Copyright (c) 2011-2012 VMware, Inc.
*
* This file is part of the vCO PowerShell Plug-in.
*
* The vCO PowerShell Plug-in 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 and no later version.
*
* The vCO PowerShell Plug-in 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 version 3
* 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
* St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.vmware.o11n.plugin.powershell.util.ssh;
import java.io.IOException;
public class SSHException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public SSHException(String msg) {
super(msg);
}
public SSHException(String message, Exception e) {
super(message, e);
}
public SSHException(IOException e) {
super(e);
}
}
| gpl-3.0 |
competitive-programming-itb/contests | JOINTS2021/final/H-ItbNoFukkatsu.cpp | 1268 | /**
* Contest : Joints 2021 Final
* Team : ItbNoFukkatsu
* Author : Muhammad Kamal Shafi
* Problem : H
*/
#include <bits/stdc++.h>
#define fi first
#define se second
#define pb(a) push_back(a)
#define mp(a, b) make_pair(a, b)
#define el '\n'
using namespace std;
using ll = long long;
using pii = pair<int, int>;
const int N = 1e6 + 10;
const int INF = 1e9;
ll money; //
int konten = 0;
int c, t, n;
vector<pii> pos, neg;
int main () {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> money >> c >> t >> n;
money -= c + t;
if (money < 0){
cout << "Gagal" << el;
return 0;
}
for (int i=1;i<=n;i++){
int a, b;
cin >> a >> b;
if (b - a >= 0) pos.pb(mp(a, b - a));
else neg.pb(mp(b - a, a));
}
sort(pos.begin(), pos.end());
for (auto& x : pos){
if (money >= x.fi){
money += x.se;
konten++;
}
}
sort(neg.begin(), neg.end(), greater<pii>());
for (auto& x : neg){
if (money >= x.se){
money += x.fi;
konten++;
}
}
if (konten == 0){
cout << "Gagal" << el;
return 0;
}
cout << konten << " " << money << el;
return 0;
} | gpl-3.0 |
Hunsu/L3Project | L3Project/DoxyGen-Doc/interfaceindividu_1_1_i_element.js | 648 | var interfaceindividu_1_1_i_element =
[
[ "ajouterConnu", "interfaceindividu_1_1_i_element.html#a8c265785d6fb0f25cc54ec5850c602d3", null ],
[ "getElementsConnus", "interfaceindividu_1_1_i_element.html#abb2ad9e31a3500c3c4deaaf58f9e01c9", null ],
[ "getNom", "interfaceindividu_1_1_i_element.html#a7783ed1b115d522ddd6a8a0c2aded632", null ],
[ "getVie", "interfaceindividu_1_1_i_element.html#a2f5272cb7b7f334bb9352cc2010c0abe", null ],
[ "setVie", "interfaceindividu_1_1_i_element.html#a386d0b896afaf5481da8c6f667b11297", null ],
[ "toString", "interfaceindividu_1_1_i_element.html#a4609baa01e8f8558e931b2f8901e789d", null ]
]; | gpl-3.0 |
sebcourtois/pypeline-tool-devkit | pytaya/core/modeling.py | 4276 |
import maya.cmds as mc
import pymel.core as pm
from pytd.util.logutils import logMsg
from pytaya.core.general import lsNodes
from pytaya.util.sysutils import withSelectionRestored
from pytaya.util import apiutils as myapi
@withSelectionRestored
def bakeDiffuseToVertexColor(**kwargs):
bOnRefs = kwargs.pop("onReferences", kwargs.pop("onRefs", False))
fAmbient = kwargs.pop("ambient", 1.0)
sCamShape = ""
if mc.about(batch=True):
sCamShape = kwargs["camera"]
if "meshes" not in kwargs:
sMeshList = lsNodes(sl=True, dag=True, ni=True, type="mesh",
not_referencedNodes=not bOnRefs, nodeNames=True)
if not sMeshList:
logMsg("No meshes found in selection !" , warning=True)
return False
else:
sMeshList = kwargs.pop("meshes")
if not sMeshList:
return False
mc.polyOptions(sMeshList, colorShadedDisplay=False)
sLightList = tuple(sLight for sLight in mc.ls(type=mc.listNodeTypes('light'))
if myapi.getDagPath(sLight).isVisible())
for sLight in sLightList:
try:
mc.setAttr(sLight + ".visibility", False)
except RuntimeError as e:
pm.displayWarning(e)
ambLight = pm.shadingNode("ambientLight", asLight=True)
ambLight.setAttr("intensity", fAmbient)
ambLight.setAmbientShade(0.0)
ambLight.setAttr("color", (1.0, 1.0, 1.0))
ambLight.setAttr("shadowColor", (0.0, 0.0, 0.0))
ambLight.setAttr("useRayTraceShadows", False)
pm.refresh()
##Storing if exist, reflectivity connection or value before applying the bakeTexture,
##as it could affects the "rendering/baking" aspect of the object.
##After bake, reapply the value.
oReflDct = {}
for oMat in lsNodes(type=mc.listNodeTypes('shader', ex="texture"), not_referencedNodes=not bOnRefs):
if oMat.hasAttr("reflectivity"):
oReflAttr = oMat.attr("reflectivity")
oInputs = oReflAttr.inputs(sourceFirst=True, c=True, plugs=True)
if oInputs:
oReflDct[oMat] = dict(oInputs)
pm.disconnectAttr(*oInputs)
else:
try:
value = oReflAttr.get()
except RuntimeError as e:
pm.displayInfo(u"{}: {}".format(e.message.strip(), oReflAttr))
continue
oReflDct[oMat] = value
oReflAttr.set(0.0)
if sCamShape:
sMeshList.append(sCamShape)
try:
mc.polyGeoSampler(sMeshList,
ignoreDoubleSided=True,
scaleFactor=1.0,
shareUV=True,
colorDisplayOption=True,
colorBlend="overwrite",
alphaBlend="overwrite",
flatShading=False,
lightingOnly=False,
averageColor=True,
clampAlphaMin=1.0,
clampAlphaMax=1.0)
mc.polyOptions(sMeshList, colorMaterialChannel="ambientDiffuse")
finally:
for sLight in sLightList:
try:
mc.setAttr(sLight + ".visibility", True)
except RuntimeError as e:
pm.displayWarning(e)
for oMat, oValues in oReflDct.items():
if isinstance(oValues, dict):
for k, v in oValues.items():
pm.connectAttr(k, v)
else:
oMat.setAttr("reflectivity", oValues)
if ambLight:
pm.delete(ambLight)
return True
def disableVertexColorDisplay(**kwargs):
bOnRefs = kwargs.pop("onReferences", kwargs.pop("onRefs", True))
if "meshes" not in kwargs:
sMeshList = lsNodes(sl=True, dag=True, ni=True, type="mesh",
not_referencedNodes=not bOnRefs, nodeNames=True)
if not sMeshList:
logMsg("No meshes found in selection !" , warning=True)
return False
else:
sMeshList = kwargs.pop("meshes")
if not sMeshList:
return False
pm.polyOptions(sMeshList, colorShadedDisplay=False)
return True
| gpl-3.0 |
aubzen/sheltermanager | src/db.py | 19630 | #!/usr/bin/python
import al
import cache
import datetime
import hashlib
import i18n
import sys
from sitedefs import ASM3_DBTYPE, ASM3_DBHOST, ASM3_DBPORT, ASM3_DBUSERNAME, ASM3_DBPASSWORD, ASM3_DBNAME, ASM3_HAS_ASM2_PK_TABLE, ASM3_PK_STRATEGY, CACHE_COMMON_QUERIES, MULTIPLE_DATABASES_MAP
try:
import MySQLdb
except:
pass
try:
import psycopg2
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
except:
pass
try:
import sqlite3
except:
pass
class DatabaseInfo():
"""
Handles information on connecting to a database.
Default values are supplied by the sitedefs.py file.
"""
dbtype = ASM3_DBTYPE # MYSQL, POSTGRESQL or SQLITE
host = ASM3_DBHOST
port = ASM3_DBPORT
username = ASM3_DBUSERNAME
password = ASM3_DBPASSWORD
database = ASM3_DBNAME
alias = ""
locale = "en"
timezone = 0
installpath = ""
locked = False
has_asm2_pk_table = ASM3_HAS_ASM2_PK_TABLE
is_large_db = False
connection = None
def __repr__(self):
return "DatabaseInfo->locale=%s:dbtype=%s:host=%s:port=%d:db=%s:alias=%s:user=%s:pass=%s" % ( self.locale, self.dbtype, self.host, self.port, self.database, self.alias, self.username, self.password )
def connection(dbo):
"""
Creates a connection to the database and returns it
"""
try:
if dbo.dbtype == "MYSQL":
if dbo.password != "":
return MySQLdb.connect(host=dbo.host, port=dbo.port, user=dbo.username, passwd=dbo.password, db=dbo.database, charset="utf8", use_unicode=True)
else:
return MySQLdb.connect(host=dbo.host, port=dbo.port, user=dbo.username, db=dbo.database, charset="utf8", use_unicode=True)
if dbo.dbtype == "POSTGRESQL":
c = psycopg2.connect(host=dbo.host, port=dbo.port, user=dbo.username, password=dbo.password, database=dbo.database)
c.set_client_encoding("UTF8")
return c
if dbo.dbtype == "SQLITE":
return sqlite3.connect(dbo.database, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
except Exception,err:
al.error(str(err), "db.connection", dbo, sys.exc_info())
def connect_cursor_open(dbo):
"""
Returns a tuple containing an open connection and cursor.
If the dbo object contains an active connection, we'll just use
that to get a cursor.
"""
if dbo.connection is not None:
return dbo.connection, dbo.connection.cursor()
else:
c = connection(dbo)
return c, c.cursor()
def connect_cursor_close(dbo, c, s):
"""
Closes a connection and cursor pair. If dbo.connection exists, then
c must be it, so don't close it.
"""
try:
s.close()
except:
pass
if dbo.connection is None:
try:
c.close()
except:
pass
def query(dbo, sql):
"""
Runs the query given and returns the resultset
as a list of dictionaries. All fieldnames are
uppercased when returned.
"""
try:
c, s = connect_cursor_open(dbo)
# Run the query and retrieve all rows
s.execute(sql)
c.commit()
d = s.fetchall()
# Initalise our list of results
l = []
for row in d:
# Intialise a map for each row
rowmap = {}
for i in xrange(0, len(row)):
v = row[i]
if type(v) == unicode:
if v is not None:
v = v.encode("ascii", "xmlcharrefreplace")
v = v.replace("`", "'")
v = v.replace("\x92", "'")
if type(v) == str:
if v is not None:
v = v.replace("`", "'")
v = v.replace("\x92", "'")
rowmap[s.description[i][0].upper()] = v
l.append(rowmap)
connect_cursor_close(dbo, c, s)
return l
except Exception,err:
al.error(str(err), "db.query", dbo, sys.exc_info())
try:
connect_cursor_close(dbo, c, s)
except:
pass
raise err
finally:
try:
connect_cursor_close(dbo, c, s)
except:
pass
def query_cache(dbo, sql, age = 60):
"""
Runs the query given and caches the result
for age seconds. If there's already a valid cached
entry for the query, returns the cached result
instead.
If CACHE_COMMON_QUERIES is set to false, just runs the query
without doing any caching and is equivalent to db.query()
"""
if not CACHE_COMMON_QUERIES or not cache.available(): return query(dbo, sql)
cache_key = "%s:%s:%s" % (dbo.alias, dbo.database, sql.replace(" ", "_"))
m = hashlib.md5()
m.update(cache_key)
cache_key = "q:%s" % m.hexdigest()
results = cache.get(cache_key)
if results is not None:
return results
results = query(dbo, sql)
cache.put(cache_key, results, age)
return results
def query_columns(dbo, sql):
"""
Runs the query given and returns the column names as
a list in the order they appeared in the query
"""
try:
c, s = connect_cursor_open(dbo)
# Run the query and retrieve all rows
s.execute(sql)
c.commit()
# Build a list of the column names
cn = []
for col in s.description:
cn.append(col[0].upper())
connect_cursor_close(dbo, c, s)
return cn
except Exception,err:
al.error(str(err), "db.query_columns", dbo, sys.exc_info())
raise err
finally:
try:
connect_cursor_close(dbo, c, s)
except:
pass
def query_tuple(dbo, sql):
"""
Runs the query given and returns the resultset
as a grid of tuples
"""
try:
c, s = connect_cursor_open(dbo)
# Run the query and retrieve all rows
s.execute(sql)
d = s.fetchall()
c.commit()
connect_cursor_close(dbo, c, s)
return d
except Exception,err:
al.error(str(err), "db.query_tuple", dbo, sys.exc_info())
raise err
finally:
try:
connect_cursor_close(dbo, c, s)
except:
pass
def query_tuple_columns(dbo, sql):
"""
Runs the query given and returns the resultset
as a grid of tuples and a list of columnames
"""
try:
c, s = connect_cursor_open(dbo)
# Run the query and retrieve all rows
s.execute(sql)
d = s.fetchall()
c.commit()
# Build a list of the column names
cn = []
for col in s.description:
cn.append(col[0].upper())
connect_cursor_close(dbo, c, s)
return (d, cn)
except Exception,err:
al.error(str(err), "db.query_tuple_columns", dbo, sys.exc_info())
raise err
finally:
try:
connect_cursor_close(dbo, c, s)
except:
pass
def query_json(dbo, sql):
"""
Runs the query given and returns the resultset
as a JSON array with column names. This is
more efficient than having query() marshall into
dictionaries and then iterating those, so if
you're querying to get JSON, use this instead of
json(query(dbo, "SQL"))
"""
try:
c, s = connect_cursor_open(dbo)
# Run the query
s.execute(sql)
c.commit()
# Loop round the rows
rows = ""
while 1:
d = s.fetchone()
if d is None: break
row = "{"
for i in xrange(0, len(d)):
if row != "{": row += ", "
# if it's null
if d[i] is None:
value = "null"
# if it's numeric
elif is_number(d[i]):
value = str(d[i])
# if it's a string
else:
value = "\"" + str(d[i]).replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t").replace("`", "'").replace("\"", "\\\"") + "\""
row += "\"%s\" : %s" % ( s.description[i][0].upper(), value )
row += "}"
if rows != "": rows += ",\n"
rows += row
json = "[\n" + rows + "\n]"
connect_cursor_close(dbo, c, s)
return json
except Exception,err:
al.error(str(err), "db.query_json", dbo, sys.exc_info())
return ""
finally:
try:
connect_cursor_close(dbo, c, s)
except:
pass
def execute_dbupdate(dbo, sql):
"""
Runs an action query for a dbupdate script (sets override_lock
to True so we don't forget)
"""
return execute(dbo, sql, True)
def execute(dbo, sql, override_lock = False):
"""
Runs the action query given and returns rows affected
override_lock: if this is set to False and dbo.locked = True,
we don't do anything. This makes it easy to lock the database
for writes, but keep databases upto date.
"""
if not override_lock and dbo.locked: return
try:
c, s = connect_cursor_open(dbo)
s.execute(sql)
rv = s.rowcount
c.commit()
connect_cursor_close(dbo, c, s)
return rv
except Exception,err:
al.error(str(err), "db.execute", dbo, sys.exc_info())
try:
# An error can leave a connection in unusable state,
# rollback any attempted changes.
c.rollback()
except:
pass
raise err
finally:
try:
connect_cursor_close(dbo, c, s)
except:
pass
def execute_many(dbo, sql, params, override_lock = False):
"""
Runs the action query given with a list of tuples that contain
substitution parameters. Eg:
"INSERT INTO table (field1, field2) VALUES (%s, %s)", [ ( "val1", "val2" ), ( "val3", "val4" ) ]
Returns rows affected
override_lock: if this is set to False and dbo.locked = True,
we don't do anything. This makes it easy to lock the database
for writes, but keep databases upto date.
"""
if not override_lock and dbo.locked: return
try:
c, s = connect_cursor_open(dbo)
s.executemany(sql, params)
rv = s.rowcount
c.commit()
connect_cursor_close(dbo, c, s)
return rv
except Exception,err:
al.error(str(err), "db.execute_many", dbo, sys.exc_info())
try:
# An error can leave a connection in unusable state,
# rollback any attempted changes.
c.rollback()
except:
pass
raise err
finally:
try:
connect_cursor_close(dbo, c, s)
except:
pass
def is_number(x):
return isinstance(x, (int, long, float, complex))
def has_structure(dbo):
try:
execute(dbo, "select * from primarykey")
return True
except:
return False
def _get_id_set_asm2_primarykey(dbo, table, nextid):
"""
Update the ASM2 primary key table.
"""
try:
affected = execute(dbo, "UPDATE primarykey SET NextID = %d WHERE TableName = '%s'" % (nextid, table))
if affected == 0:
execute(dbo, "INSERT INTO primarykey (TableName, NextID) VALUES ('%s', %d)" % (table, nextid))
except:
pass
def _get_id_max(dbo, table):
return query_int(dbo, "SELECT MAX(ID) FROM %s" % table) + 1
def _get_id_memcache(dbo, table):
cache_key = "db:%s:as:%s:tb:%s" % (dbo.database, dbo.alias, table)
nextid = cache.increment(cache_key)
if nextid is None:
nextid = query_int(dbo, "SELECT MAX(ID) FROM %s" % table) + 1
cache.put(cache_key, nextid, 600)
return nextid
def _get_id_postgres_seq(dbo, table):
return query_int(dbo, "SELECT nextval('seq_%s')" % table)
def get_id(dbo, table):
"""
Returns the next ID in sequence for a table.
Will use memcache for pk generation if the CACHE_PRIMARY_KEYS option is on
and will set the cache first value if not set.
If the database has an ASM2 primary key table, it will be updated
with the next pk value.
"""
strategy = ""
nextid = 0
if ASM3_PK_STRATEGY == "max" or dbo.has_asm2_pk_table:
nextid = _get_id_max(dbo, table)
strategy = "max"
elif ASM3_PK_STRATEGY == "memcache" and cache.available():
nextid = _get_id_memcache(dbo, table)
strategy = "memcache"
elif ASM3_PK_STRATEGY == "pseq" and dbo.dbtype == "POSTGRESQL":
nextid = _get_id_postgres_seq(dbo, table)
strategy = "pseq"
else:
raise Exception("No valid PK strategy found")
if dbo.has_asm2_pk_table:
_get_id_set_asm2_primarykey(dbo, table, nextid + 1)
strategy += " asm2pk"
al.debug("get_id: %s -> %d (%s)" % (table, nextid, strategy), "db.get_id", dbo)
return nextid
def get_multiple_database_info(alias):
"""
Gets the database info for the alias from our configured map.
"""
dbo = DatabaseInfo()
if not MULTIPLE_DATABASES_MAP.has_key(alias):
dbo.database = "FAIL"
return dbo
mapinfo = MULTIPLE_DATABASES_MAP[alias]
dbo.alias = alias
dbo.dbtype = mapinfo["dbtype"]
dbo.host = mapinfo["host"]
dbo.port = mapinfo["port"]
dbo.username = mapinfo["username"]
dbo.password = mapinfo["password"]
dbo.database = mapinfo["database"]
return dbo
def query_int(dbo, sql):
r = query_tuple(dbo, sql)
try:
v = r[0][0]
return int(v)
except:
return int(0)
def query_float(dbo, sql):
r = query_tuple(dbo, sql)
try:
v = r[0][0]
return float(v)
except:
return float(0)
def query_string(dbo, sql):
r = query_tuple(dbo, sql)
try :
v = r[0][0].replace("`", "'")
return v.encode('ascii', 'xmlcharrefreplace')
except:
return str("")
def query_date(dbo, sql):
r = query_tuple(dbo, sql)
try:
v = r[0][0]
return v
except:
return None
def today():
""" Returns today as a python date """
return datetime.datetime.today()
def todaysql():
""" Returns today as an SQL date """
return dd(today())
def nowsql():
""" Returns today as an SQL date """
return ddt(today())
def python2db(d):
""" Formats a python date as a date for the database """
if d is None: return "NULL"
return "%d-%02d-%02d" % ( d.year, d.month, d.day )
def ddt(d):
""" Formats a python date and time as a date for the database """
if d is None: return "NULL"
return "'%04d-%02d-%02d %02d:%02d:%02d'" % ( d.year, d.month, d.day, d.hour, d.minute, d.second )
def dd(d):
""" Formats a python date as a date for the database """
if d is None: return "NULL"
return "'%04d-%02d-%02d 00:00:00'" % ( d.year, d.month, d.day )
def ds(s):
""" Formats a value as a string for the database """
if s is None: return "NULL"
return "'%s'" % str(s).replace("'", "`").replace("\\", "\\\\")
def df(f):
""" Formats a value as a float for the database """
if f is None: return "NULL"
return str(f)
def di(i):
""" Formats a value as an integer for the database """
if i is None: return "NULL"
s = str(i)
try:
return str(int(s))
except:
return "0"
def concat(dbo, items):
""" Writes a database independent concat """
if dbo.dbtype == "MYSQL":
return "CONCAT(" + ",".join(items) + ")"
elif dbo.dbtype == "POSTGRESQL" or dbo.dbtype == "SQLITE":
return " || ".join(items)
def char_length(dbo, item):
""" Writes a database independent char length """
if dbo.dbtype == "MYSQL":
return "LENGTH(%s)" % item
elif dbo.dbtype == "POSTGRESQL":
return "char_length(%s)" % item
elif dbo.dbtype == "SQLITE":
return "length(%s)" % item
def escape(s):
""" Makes a value safe for queries """
return s.replace("'", "`")
def recordversion():
"""
Returns an integer representation of now.
"""
d = today()
i = d.hour * 10000
i += d.minute * 100
i += d.second
return i
def make_insert_sql(table, s):
"""
Creates insert sql, 'table' is the table name,
's' is a tuple of tuples containing the field names
and values, eg:
make_insert_sql("animal", ( ( "ID", di(52) ), ( "AnimalName", ds("Indy") ) ))
"""
fl = ""
fv = ""
for r in s:
if r is None: break
if fl != "":
fl += ", "
fv += ", "
fl += r[0]
fv += r[1]
return "INSERT INTO %s (%s) VALUES (%s);" % ( table, fl, fv )
def make_insert_user_sql(dbo, table, username, s, stampRecordVersion = True):
"""
Creates insert sql for a user, 'table' is the table name,
username is the name of the user to be stamped in the fields
's' is a tuple of tuples containing the field names
and values, eg:
make_insert_user_sql("animal", "jeff", ( ( "ID", di(52) ), ( "AnimalName", ds("Indy") ) ))
"""
l = list(s)
l.append(("CreatedBy", ds(username)))
l.append(("CreatedDate", ddt(i18n.now())))
l.append(("LastChangedBy", ds(username)))
l.append(("LastChangedDate", ddt(i18n.now(dbo.timezone))))
if stampRecordVersion: l.append(("RecordVersion", di(recordversion())))
return make_insert_sql(table, l)
def make_update_sql(table, cond, s):
"""
Creates update sql, 'table' is the table name,
's' is a tuple of tuples containing the field names
and values, 'cond' is the where condition eg:
make_update_sql("animal", "ID = 52", (( "AnimalName", ds("James") )))
"""
o = "UPDATE %s SET " % table
first = True
for r in s:
if r is None: break
if not first:
o += ", "
first = False
o += r[0] + "=" + r[1]
if cond != "":
o += " WHERE " + cond
return o
def make_update_user_sql(dbo, table, username, cond, s, stampRecordVersion = True):
"""
Creates update sql for a given user, 'table' is the table
name, username is the username of the user making the change,
cond is the where condition eg:
make_update_user_sql("animal", "jeff", "ID = 52", (( "AnimalName", ds("James") )))
"""
l = list(s)
l.append(("LastChangedBy", ds(username)))
l.append(("LastChangedDate", ddt(i18n.now(dbo.timezone))))
if stampRecordVersion: l.append(("RecordVersion", di(recordversion())))
return make_update_sql(table, cond, l);
def rows_to_insert_sql(table, rows, escapeCR = ""):
"""
Writes an INSERT query for a list of rows (a list containing dictionaries)
"""
ins = []
fields = []
donefields = False
for r in rows:
values = []
for k in sorted(r.iterkeys()):
if not donefields:
fields.append(k)
v = r[k]
if v is None:
values.append("null")
elif type(v) == unicode or type(v) == str:
if escapeCR != "": v = v.replace("\n", escapeCR).replace("\r", "")
values.append(ds(v))
elif type(v) == datetime.datetime:
values.append(ddt(v))
else:
values.append(di(v))
donefields = True
ins.append("INSERT INTO %s (%s) VALUES (%s);\n" % (table, ",".join(fields), ",".join(values)))
return "".join(ins)
| gpl-3.0 |
albz/Architect | utils/python_utils/architect_graphycal_unit/architect_read_section_bin.py | 17931 | #!/usr/bin/python
######################################################################
# Name: read_Architect_bin_section.py
# Author: A. Marocchino (last version: I have made the mess with double precision) and F. Massimo
# Date: 2016-11-10
# Purpose: read Binary Sections
# Source: Python
#####################################################################
### loading shell commands
import os, os.path, glob, sys, shutil, time
import struct
import numpy as np
sys.path.append(os.path.join(os.path.expanduser('~'),'Codes/Code_Architect/Architect/utils/python_utils/architect_graphycal_unit'))
import global_variables as var
### --- ###
def read_Architect_bin_section_output_v_1(dir_path,file_name):
# - #
path = os.path.join(os.path.join(dir_path,file_name))
f = open(path,'rb')
output_version = struct.unpack('i', f.read(4))[0]
dist = struct.unpack('i', f.read(4))[0] # distance traveled
#- radial and axial dimensions -#
Nr = struct.unpack('i', f.read(4))[0] # half-plane axis dim (radial direction )
Nz = struct.unpack('i', f.read(4))[0] # z dim (longitudinal direction)
#### Start reading grid data
# r_mesh axis
r_mesh = np.zeros(Nr)
for j in range(0,Nr): # read r axis
r = struct.unpack('f', f.read(4))[0]
r_mesh[j] = r
# z_mesh axis
z_mesh = np.zeros(Nz)
for i in range(0,Nz): # read z axis
z = struct.unpack('f', f.read(4))[0]
z_mesh[i] = z
# rho_b - bunch electron density
rho_b = np.zeros((Nr,Nz))
for j in range(0,Nr):
for i in range(0,Nz):
rho_b[j,i] = struct.unpack('f', f.read(4))[0]
# n_bck - plasma electron density
n_bck = np.zeros((Nr,Nz))
for j in range(0,Nr):
for i in range(0,Nz):
n_bck[j,i] = struct.unpack('f', f.read(4))[0]
# Er - Electric field, transverse
Er = np.zeros((Nr,Nz)) # total field
for j in range(0,Nr):
for i in range(0,Nz):
Er[j,i] = struct.unpack('f', f.read(4))[0]
# Ez - Electric field, longitudinal
Ez = np.zeros((Nr,Nz)) # total field
for j in range(0,Nr):
for i in range(0,Nz):
Ez[j,i] = struct.unpack('f', f.read(4))[0]
# Bphi - Magnetic field, azimuthal
Bphi = np.zeros((Nr,Nz)) # total field
for j in range(0,Nr):
for i in range(0,Nz):
Bphi[j,i] = struct.unpack('f', f.read(4))[0]
# Jbr - Bunch current density, transverse
Jbr = np.zeros((Nr,Nz)) # total field
for j in range(0,Nr):
for i in range(0,Nz):
Jbr[j,i] = struct.unpack('f', f.read(4))[0]
# Jbckr - Plasma current density, transverse
Jbckr = np.zeros((Nr,Nz)) # background field
for j in range(0,Nr):
for i in range(0,Nz):
Jbckr[j,i] = struct.unpack('f', f.read(4))[0]
# Jbr - Bunch current density, transverse
Jbz = np.zeros((Nr,Nz)) # total field
for j in range(0,Nr):
for i in range(0,Nz):
Jbz[j,i] = struct.unpack('f', f.read(4))[0]
# Jbckr - Plasma current density, transverse
Jbckz = np.zeros((Nr,Nz)) # background field
for j in range(0,Nr):
for i in range(0,Nz):
Jbckz[j,i] = struct.unpack('f', f.read(4))[0]
f.close()
return dist,r_mesh,z_mesh,rho_b,n_bck,Er,Ez,Bphi,Jbr,Jbckr,Jbz,Jbckz
def read_Architect_bin_section_output_v_2(dir_path,file_name):
# - #
path = os.path.join(os.path.join(dir_path,file_name))
f = open(path,'rb')
output_version = struct.unpack('i', f.read(4))[0]
dist = struct.unpack('i', f.read(4))[0] # distance traveled
#- vector length -#
Nr = struct.unpack('i', f.read(4))[0] # half-plane axis dim (radial direction )
Nz = struct.unpack('i', f.read(4))[0] # z dim (longitudinal direction)
#### Start reading grid data
# r_mesh axis
r_mesh = np.zeros(Nr)
for j in range(0,Nr): # read r axis
r = struct.unpack('f', f.read(4))[0]
r_mesh[j] = r
# z_mesh axis
z_mesh = np.zeros(Nz)
for i in range(0,Nz): # read z axis
z = struct.unpack('f', f.read(4))[0]
z_mesh[i] = z
# rho_b - bunch electron density
rho_b = np.zeros((Nr,Nz))
for j in range(0,Nr):
for i in range(0,Nz):
rho_b[j,i] = struct.unpack('f', f.read(4))[0]
# n_bck - plasma electron density
n_bck = np.zeros((Nr,Nz))
for j in range(0,Nr):
for i in range(0,Nz):
n_bck[j,i] = struct.unpack('f', f.read(4))[0]
# Er - Electric field, transverse
Er = np.zeros((Nr,Nz)) # total field
for j in range(0,Nr):
for i in range(0,Nz):
Er[j,i] = struct.unpack('f', f.read(4))[0]
Er_bck = np.zeros((Nr,Nz)) # background field
for j in range(0,Nr):
for i in range(0,Nz):
Er_bck[j,i] = struct.unpack('f', f.read(4))[0]
Er_b = np.zeros((Nr,Nz)) # bunch field
for j in range(0,Nr):
for i in range(0,Nz):
Er_b[j,i] = struct.unpack('f', f.read(4))[0]
# Ez - Electric field, longitudinal
Ez = np.zeros((Nr,Nz)) # total field
for j in range(0,Nr):
for i in range(0,Nz):
Ez[j,i] = struct.unpack('f', f.read(4))[0]
Ez_bck = np.zeros((Nr,Nz)) # background field
for j in range(0,Nr):
for i in range(0,Nz):
Ez_bck[j,i] = struct.unpack('f', f.read(4))[0]
Ez_b = np.zeros((Nr,Nz)) # bunch field
for j in range(0,Nr):
for i in range(0,Nz):
Ez_b[j,i] = struct.unpack('f', f.read(4))[0]
# Bphi - Magnetic field, azimuthal
Bphi = np.zeros((Nr,Nz)) # total field
for j in range(0,Nr):
for i in range(0,Nz):
Bphi[j,i] = struct.unpack('f', f.read(4))[0]
Bphi_bck = np.zeros((Nr,Nz)) # background field
for j in range(0,Nr):
for i in range(0,Nz):
Bphi_bck[j,i] = struct.unpack('f', f.read(4))[0]
Bphi_b = np.zeros((Nr,Nz)) # bunch field
for j in range(0,Nr):
for i in range(0,Nz):
Bphi_b[j,i] = struct.unpack('f', f.read(4))[0]
# Jbr - Bunch current density, transverse
Jbr = np.zeros((Nr,Nz)) # total field
for j in range(0,Nr):
for i in range(0,Nz):
Jbr[j,i] = struct.unpack('f', f.read(4))[0]
# Jbckr - Plasma current density, transverse
Jbckr = np.zeros((Nr,Nz)) # background field
for j in range(0,Nr):
for i in range(0,Nz):
Jbckr[j,i] = struct.unpack('f', f.read(4))[0]
# Jbr - Bunch current density, transverse
Jbz = np.zeros((Nr,Nz)) # total field
for j in range(0,Nr):
for i in range(0,Nz):
Jbz[j,i] = struct.unpack('f', f.read(4))[0]
# Jbckr - Plasma current density, transverse
Jbckz = np.zeros((Nr,Nz)) # background field
for j in range(0,Nr):
for i in range(0,Nz):
Jbckz[j,i] = struct.unpack('f', f.read(4))[0]
f.close()
return dist,r_mesh,z_mesh,rho_b,n_bck,Er,Er_bck,Er_b,Ez,Ez_bck,Ez_b,Bphi,Bphi_bck,Bphi_b,Jbr,Jbckr,Jbz,Jbckz
def read_Architect_bin_section_output_v_3(dir_path,file_name):
# - #
path = os.path.join(os.path.join(dir_path,file_name))
f = open(path,'rb')
output_version = struct.unpack('i', f.read(4))[0]
dist = struct.unpack('i', f.read(4))[0] # distance traveled
#- vector length -#
Nr = struct.unpack('i', f.read(4))[0] # half-plane axis dim (radial direction )
Nz = struct.unpack('i', f.read(4))[0] # z dim (longitudinal direction)
#### Start reading grid data
# r_mesh axis
r_mesh = np.zeros(Nr)
for j in range(0,Nr): # read r axis
r = struct.unpack('f', f.read(4))[0]
r_mesh[j] = r
# z_mesh axis
z_mesh = np.zeros(Nz)
for i in range(0,Nz): # read z axis
z = struct.unpack('f', f.read(4))[0]
z_mesh[i] = z
# rho_b - bunch electron density
rho_b = np.zeros((Nr,Nz))
for j in range(0,Nr):
for i in range(0,Nz):
rho_b[j,i] = struct.unpack('f', f.read(4))[0]
# n_bck - plasma electron density
n_bck = np.zeros((Nr,Nz))
for j in range(0,Nr):
for i in range(0,Nz):
n_bck[j,i] = struct.unpack('f', f.read(4))[0]
# Er - Electric field, transverse
Er = np.zeros((Nr,Nz)) # total field
for j in range(0,Nr):
for i in range(0,Nz):
Er[j,i] = struct.unpack('f', f.read(4))[0]
Er_bck = np.zeros((Nr,Nz)) # background field
for j in range(0,Nr):
for i in range(0,Nz):
Er_bck[j,i] = struct.unpack('f', f.read(4))[0]
Er_b = np.zeros((Nr,Nz)) # bunch field
for j in range(0,Nr):
for i in range(0,Nz):
Er_b[j,i] = struct.unpack('f', f.read(4))[0]
# Ez - Electric field, longitudinal
Ez = np.zeros((Nr,Nz)) # total field
for j in range(0,Nr):
for i in range(0,Nz):
Ez[j,i] = struct.unpack('f', f.read(4))[0]
Ez_bck = np.zeros((Nr,Nz)) # background field
for j in range(0,Nr):
for i in range(0,Nz):
Ez_bck[j,i] = struct.unpack('f', f.read(4))[0]
Ez_b = np.zeros((Nr,Nz)) # bunch field
for j in range(0,Nr):
for i in range(0,Nz):
Ez_b[j,i] = struct.unpack('f', f.read(4))[0]
# Bphi - Magnetic field, azimuthal
Bphi = np.zeros((Nr,Nz)) # total field
for j in range(0,Nr):
for i in range(0,Nz):
Bphi[j,i] = struct.unpack('f', f.read(4))[0]
Bphi_bck = np.zeros((Nr,Nz)) # background field
for j in range(0,Nr):
for i in range(0,Nz):
Bphi_bck[j,i] = struct.unpack('f', f.read(4))[0]
Bphi_b = np.zeros((Nr,Nz)) # bunch field
for j in range(0,Nr):
for i in range(0,Nz):
Bphi_b[j,i] = struct.unpack('f', f.read(4))[0]
B_ex_poloidal = np.zeros((Nr,Nz)) # bunch field
for j in range(0,Nr):
for i in range(0,Nz):
B_ex_poloidal[j,i] = struct.unpack('f', f.read(4))[0]
# Jbr - Bunch current density, transverse
Jbr = np.zeros((Nr,Nz)) # total field
for j in range(0,Nr):
for i in range(0,Nz):
Jbr[j,i] = struct.unpack('f', f.read(4))[0]
# Jbckr - Plasma current density, transverse
Jbckr = np.zeros((Nr,Nz)) # background field
for j in range(0,Nr):
for i in range(0,Nz):
Jbckr[j,i] = struct.unpack('f', f.read(4))[0]
# Jbr - Bunch current density, transverse
Jbz = np.zeros((Nr,Nz)) # total field
for j in range(0,Nr):
for i in range(0,Nz):
Jbz[j,i] = struct.unpack('f', f.read(4))[0]
# Jbckr - Plasma current density, transverse
Jbckz = np.zeros((Nr,Nz)) # background field
for j in range(0,Nr):
for i in range(0,Nz):
Jbckz[j,i] = struct.unpack('f', f.read(4))[0]
f.close()
return dist,r_mesh,z_mesh,rho_b,n_bck,Er,Er_bck,Er_b,Ez,Ez_bck,Ez_b,Bphi,Bphi_bck,Bphi_b,B_ex_poloidal,Jbr,Jbckr,Jbz,Jbckz
def read_Architect_bin_section_output_v_4(dir_path,file_name):
# - #
path = os.path.join(os.path.join(dir_path,file_name))
f = open(path,'rb')
var.output_version = struct.unpack('i', f.read(4))[0]
var.dist_um = struct.unpack('i', f.read(4))[0] # distance traveled
#- vector length -#
var.Nr = struct.unpack('i', f.read(4))[0] # half-plane axis dim (radial direction )
var.Nz = struct.unpack('i', f.read(4))[0] # z dim (longitudinal direction)
#--- Grid data ---#
# r_mesh axis
var.r_mesh = np.zeros(var.Nr)
for j in range(0,var.Nr): # read r axis
r = struct.unpack('d', f.read(8))[0]
var.r_mesh[j] = r
# z_mesh axis
var.z_mesh = np.zeros(var.Nz)
for i in range(0,var.Nz): # read z axis
z = struct.unpack('d', f.read(8))[0]
var.z_mesh[i] = z
# rho_b - bunch electron density
var.rho_b = np.zeros((var.Nr,var.Nz))
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.rho_b[j,i] = struct.unpack('d', f.read(8))[0]
# rho_bck - plasma electron density
var.rho_bck = np.zeros((var.Nr,var.Nz))
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.rho_bck[j,i] = struct.unpack('d', f.read(8))[0]
var.rho = np.zeros((var.Nr,var.Nz))
var.rho = var.rho_b+var.rho_bck
# Er fields
var.Er = np.zeros((var.Nr,var.Nz))
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Er[j,i] = struct.unpack('d', f.read(8))[0]
var.Er_bck = np.zeros((var.Nr,var.Nz))
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Er_bck[j,i] = struct.unpack('d', f.read(8))[0]
var.Er_b = np.zeros((var.Nr,var.Nz))
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Er_b[j,i] = struct.unpack('d', f.read(8))[0]
# Ez - Electric field, longitudinal
var.Ez = np.zeros((var.Nr,var.Nz)) # total field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Ez[j,i] = struct.unpack('d', f.read(8))[0]
var.Ez_bck = np.zeros((var.Nr,var.Nz)) # background field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Ez_bck[j,i] = struct.unpack('d', f.read(8))[0]
var.Ez_b = np.zeros((var.Nr,var.Nz)) # bunch field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Ez_b[j,i] = struct.unpack('d', f.read(8))[0]
# Bphi - Magnetic field, azimuthal
var.Bphi = np.zeros((var.Nr,var.Nz)) # total field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Bphi[j,i] = struct.unpack('d', f.read(8))[0]
var.Bphi_bck = np.zeros((var.Nr,var.Nz)) # background field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Bphi_bck[j,i] = struct.unpack('d', f.read(8))[0]
var.Bphi_b = np.zeros((var.Nr,var.Nz)) # bunch field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Bphi_b[j,i] = struct.unpack('d', f.read(8))[0]
var.Bphi_ex = np.zeros((var.Nr,var.Nz)) # bunch field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Bphi_ex[j,i] = struct.unpack('d', f.read(8))[0]
# Radial Current Jr
var.Jr_b = np.zeros((var.Nr,var.Nz)) # total field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Jr_b[j,i] = struct.unpack('d', f.read(8))[0]
#Plasma current density, transverse
var.Jr_bck = np.zeros((var.Nr,var.Nz)) # background field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Jr_bck[j,i] = struct.unpack('d', f.read(8))[0]
var.Jr = np.zeros((var.Nr,var.Nz))
var.Jr = var.Jr_b+var.Jr_bck
# Jbr - Bunch current density, transverse
var.Jz_b = np.zeros((var.Nr,var.Nz)) # total field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Jz_b[j,i] = struct.unpack('d', f.read(8))[0]
# Jbckr - Plasma current density, transverse
var.Jz_bck = np.zeros((var.Nr,var.Nz)) # background field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Jz_bck[j,i] = struct.unpack('d', f.read(8))[0]
var.Jz = np.zeros((var.Nr,var.Nz))
var.Jz = var.Jz_b+var.Jz_bck
f.close()
def read_Architect_bin_section_output_v_5(dir_path,file_name):
# - #
path = os.path.join(os.path.join(dir_path,file_name))
f = open(path,'rb')
var.output_version = struct.unpack('i', f.read(4))[0]
#--- parameters ---#
var.kp = struct.unpack('d', f.read(8))[0]
var.wp = struct.unpack('d', f.read(8))[0]
var.dist = struct.unpack('d', f.read(8))[0]
var.np = struct.unpack('d', f.read(8))[0]
var.dist_um = struct.unpack('d', f.read(8))[0]
#- vector length -#
var.Nr = struct.unpack('i', f.read(4))[0] # half-plane axis dim (radial direction )
var.Nz = struct.unpack('i', f.read(4))[0] # z dim (longitudinal direction)
#--- Grid data ---#
# r_mesh axis
var.r_mesh = np.zeros(var.Nr)
for j in range(0,var.Nr): # read r axis
r = struct.unpack('d', f.read(8))[0]
var.r_mesh[j] = r
# z_mesh axis
var.z_mesh = np.zeros(var.Nz)
for i in range(0,var.Nz): # read z axis
z = struct.unpack('d', f.read(8))[0]
var.z_mesh[i] = z
# rho_b - bunch electron density
var.rho_b = np.zeros((var.Nr,var.Nz))
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.rho_b[j,i] = struct.unpack('d', f.read(8))[0]
# rho_bck - plasma electron density
var.rho_bck = np.zeros((var.Nr,var.Nz))
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.rho_bck[j,i] = struct.unpack('d', f.read(8))[0]
var.rho = np.zeros((var.Nr,var.Nz))
var.rho = var.rho_b+var.rho_bck
# Er fields
var.Er = np.zeros((var.Nr,var.Nz))
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Er[j,i] = struct.unpack('d', f.read(8))[0]
var.Er_bck = np.zeros((var.Nr,var.Nz))
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Er_bck[j,i] = struct.unpack('d', f.read(8))[0]
var.Er_b = np.zeros((var.Nr,var.Nz))
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Er_b[j,i] = struct.unpack('d', f.read(8))[0]
# Ez - Electric field, longitudinal
var.Ez = np.zeros((var.Nr,var.Nz)) # total field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Ez[j,i] = struct.unpack('d', f.read(8))[0]
var.Ez_bck = np.zeros((var.Nr,var.Nz)) # background field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Ez_bck[j,i] = struct.unpack('d', f.read(8))[0]
var.Ez_b = np.zeros((var.Nr,var.Nz)) # bunch field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Ez_b[j,i] = struct.unpack('d', f.read(8))[0]
# Bphi - Magnetic field, azimuthal
var.Bphi = np.zeros((var.Nr,var.Nz)) # total field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Bphi[j,i] = struct.unpack('d', f.read(8))[0]
var.Bphi_bck = np.zeros((var.Nr,var.Nz)) # background field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Bphi_bck[j,i] = struct.unpack('d', f.read(8))[0]
var.Bphi_b = np.zeros((var.Nr,var.Nz)) # bunch field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Bphi_b[j,i] = struct.unpack('d', f.read(8))[0]
var.Bphi_ex = np.zeros((var.Nr,var.Nz)) # bunch field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Bphi_ex[j,i] = struct.unpack('d', f.read(8))[0]
# Radial Current Jr
var.Jr_b = np.zeros((var.Nr,var.Nz)) # total field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Jr_b[j,i] = struct.unpack('d', f.read(8))[0]
#Plasma current density, transverse
var.Jr_bck = np.zeros((var.Nr,var.Nz)) # background field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Jr_bck[j,i] = struct.unpack('d', f.read(8))[0]
var.Jr = np.zeros((var.Nr,var.Nz))
var.Jr = var.Jr_b+var.Jr_bck
# Jbr - Bunch current density, transverse
var.Jz_b = np.zeros((var.Nr,var.Nz)) # total field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Jz_b[j,i] = struct.unpack('d', f.read(8))[0]
# Jbckr - Plasma current density, transverse
var.Jz_bck = np.zeros((var.Nr,var.Nz)) # background field
for j in range(0,var.Nr):
for i in range(0,var.Nz):
var.Jz_bck[j,i] = struct.unpack('d', f.read(8))[0]
var.Jz = np.zeros((var.Nr,var.Nz))
var.Jz = var.Jz_b+var.Jz_bck
f.close()
| gpl-3.0 |
gkrintir/topskim | makeEMuSkim_OnBatch2.C | 14020 | #include "TFile.h"
#include "TDatime.h"
#include "TNamed.h"
#include "TMath.h"
#include "TLorentzVector.h"
#include "EMuSkimTree.h"
#include <string>
#include <vector>
const Bool_t isDebug = false;
const Float_t jetPtCut = 25.;
const Float_t lepPtCut = 15;
const Float_t muEtaCut = 2.4;
const Float_t muPtCut = 15;
const Float_t muChi2NDFCut = 10;
const Float_t muInnerD0Cut = 0.2;
const Float_t muInnerDzCut = 0.5;
const Int_t muMuonHitsCut = 0;
const Int_t muStationsCut = 1;
const Int_t muTrkLayersCut = 5;
const Int_t muPixelHitsCut = 0;
//see https://twiki.cern.ch/twiki/bin/view/CMS/CutBasedElectronIdentificationRun2#Spring15_selection_25ns (electron id)
const Float_t eleEtaCut = 2.4;
const Float_t elePtCut = 15;
const Float_t barrelEndcapEta = 1.479;
const Int_t nBarrelEndcap = 2; // barrel = 0, endcap = 1
const Float_t eleSigmaIEtaIEta_VetoCut[nBarrelEndcap] = {0.0114, 0.0352};
const Float_t eleDEtaIn_VetoCut[nBarrelEndcap] = {0.0152, 0.0113};
const Float_t eleDPhiIn_VetoCut[nBarrelEndcap] = {0.216, 0.237};
const Float_t eleHOverE_VetoCut[nBarrelEndcap] = {0.181, 0.116};
const Float_t eleRelIsoWithEA_VetoCut[nBarrelEndcap] = {0.126, 0.144};
const Float_t eleOOEmooP_VetoCut[nBarrelEndcap] = {0.207, 0.174};
const Float_t eleD0_VetoCut[nBarrelEndcap] = {0.0564, 0.222};
const Float_t eleDZ_VetoCut[nBarrelEndcap] = {0.472, 0.921};
const Float_t eleMissingInnerHits_VetoCut[nBarrelEndcap] = {2, 3};
void makeEMuSkim_OnBatch2(const std::string inFileName = "", int firstFile, int lastFile, const std::string outFileName = "", bool isMC=true)
{
if(!strcmp(inFileName.c_str(), "")){
std::cout << "No inputs specified. return" << std::endl;
return;
}
if(isDebug) std::cout << __LINE__ << std::endl;
TFile* outFile_p = new TFile(outFileName.c_str(), "RECREATE");
skimTree_p = new TTree("skimTree", "skimTree");
BookTree();
std::vector<std::string>* inFileNames_p = new std::vector<std::string>;
int count = 0;std:: string line;
ifstream file1 ( inFileName.c_str() );
if (!file1.is_open())
{
cout<<"Could not open file\n";
}
else
{
do
{
getline(file1,line);
if (file1)
{
if (count>=firstFile && count<=lastFile)
{
inFileNames_p->push_back(line);
}
count++;
}
} while (file1);
}
file1.close();
//inFileNames_p->push_back(inFileName);
// if(strcmp(inFileName.c_str(), "") != 0) inFileNames_p->push_back(inFileName);
const Int_t nFiles = (Int_t)inFileNames_p->size();
for(Int_t fileIter = 0; fileIter < nFiles; fileIter++){
std::cout << "On file: " << fileIter << "/" << nFiles << ", "<< inFileNames_p->at(fileIter).c_str() << std::endl;
TFile *inFile_p = TFile::Open(inFileNames_p->at(fileIter).c_str(), "READ");
TTree* lepTree_p = (TTree*)inFile_p->Get("ggHiNtuplizer/EventTree");
TTree* jetTree_p = (TTree*)inFile_p->Get("ak4PFJetAnalyzer/t");
TTree* hiTree_p = (TTree*)inFile_p->Get("hiEvtAnalyzer/HiTree");
TTree* hltTree_p = (TTree*)inFile_p->Get("hltanalysis/HltTree");
std::vector<float>* muPt_p = 0;
std::vector<float>* muPhi_p = 0;
std::vector<float>* muEta_p = 0;
std::vector<int>* muChg_p = 0;
std::vector<float>* muChi2NDF_p = 0;
std::vector<float>* muInnerD0_p = 0;
std::vector<float>* muInnerDz_p = 0;
std::vector<int>* muMuonHits_p = 0;
std::vector<int>* muStations_p = 0;
std::vector<int>* muTrkLayers_p = 0;
std::vector<int>* muPixelHits_p = 0;
std::vector<float>* elePt_p = 0;
std::vector<float>* elePhi_p = 0;
std::vector<float>* eleEta_p = 0;
std::vector<int>* eleChg_p = 0;
std::vector<float>* eleSigmaIEtaIEta_p = 0;
std::vector<float>* eleDEtaAtVtx_p = 0;
std::vector<float>* eleDPhiAtVtx_p = 0;
std::vector<float>* eleHOverE_p = 0;
std::vector<float>* eleD0_p = 0;
std::vector<float>* eleDz_p = 0;
const int maxJets = 5000;
Int_t nref;
Float_t jtpt[maxJets];
Float_t jteta[maxJets];
Float_t jtphi[maxJets];
Float_t jtm[maxJets];
Float_t discr_csvV2[maxJets];
int trig = 0;
lepTree_p->SetBranchStatus("*", 0);
lepTree_p->SetBranchStatus("muPt", 1);
lepTree_p->SetBranchStatus("muPhi", 1);
lepTree_p->SetBranchStatus("muEta", 1);
lepTree_p->SetBranchStatus("muCharge", 1);
lepTree_p->SetBranchStatus("muChi2NDF", 1);
lepTree_p->SetBranchStatus("muInnerD0", 1);
lepTree_p->SetBranchStatus("muInnerDz", 1);
lepTree_p->SetBranchStatus("muMuonHits", 1);
lepTree_p->SetBranchStatus("muStations", 1);
lepTree_p->SetBranchStatus("muTrkLayers", 1);
lepTree_p->SetBranchStatus("muPixelHits", 1);
lepTree_p->SetBranchAddress("muPt", &muPt_p);
lepTree_p->SetBranchAddress("muPhi", &muPhi_p);
lepTree_p->SetBranchAddress("muEta", &muEta_p);
lepTree_p->SetBranchAddress("muCharge", &muChg_p);
lepTree_p->SetBranchAddress("muChi2NDF", &muChi2NDF_p);
lepTree_p->SetBranchAddress("muInnerD0", &muInnerD0_p);
lepTree_p->SetBranchAddress("muInnerDz", &muInnerDz_p);
lepTree_p->SetBranchAddress("muMuonHits", &muMuonHits_p);
lepTree_p->SetBranchAddress("muStations", &muStations_p);
lepTree_p->SetBranchAddress("muTrkLayers", &muTrkLayers_p);
lepTree_p->SetBranchAddress("muPixelHits", &muPixelHits_p);
lepTree_p->SetBranchStatus("elePt", 1);
lepTree_p->SetBranchStatus("elePhi", 1);
lepTree_p->SetBranchStatus("eleEta", 1);
lepTree_p->SetBranchStatus("eleCharge", 1);
lepTree_p->SetBranchStatus("eleSigmaIEtaIEta", 1);
lepTree_p->SetBranchStatus("eledEtaAtVtx", 1);
lepTree_p->SetBranchStatus("eledPhiAtVtx", 1);
lepTree_p->SetBranchStatus("eleHoverE", 1);
lepTree_p->SetBranchStatus("eleD0", 1);
lepTree_p->SetBranchStatus("eleDz", 1);
lepTree_p->SetBranchAddress("elePt", &elePt_p);
lepTree_p->SetBranchAddress("elePhi", &elePhi_p);
lepTree_p->SetBranchAddress("eleEta", &eleEta_p);
lepTree_p->SetBranchAddress("eleCharge", &eleChg_p);
lepTree_p->SetBranchAddress("eleSigmaIEtaIEta", &eleSigmaIEtaIEta_p);
lepTree_p->SetBranchAddress("eledEtaAtVtx", &eleDEtaAtVtx_p);
lepTree_p->SetBranchAddress("eledPhiAtVtx", &eleDPhiAtVtx_p);
lepTree_p->SetBranchAddress("eleHoverE", &eleHOverE_p);
lepTree_p->SetBranchAddress("eleD0", &eleD0_p);
lepTree_p->SetBranchAddress("eleDz", &eleDz_p);
jetTree_p->SetBranchStatus("*", 0);
jetTree_p->SetBranchStatus("nref", 1);
jetTree_p->SetBranchStatus("jtpt", 1);
jetTree_p->SetBranchStatus("jtphi", 1);
jetTree_p->SetBranchStatus("jteta", 1);
jetTree_p->SetBranchStatus("jtm", 1);
jetTree_p->SetBranchStatus("discr_csvV2", 1);
jetTree_p->SetBranchAddress("nref", &nref);
jetTree_p->SetBranchAddress("jtpt", jtpt);
jetTree_p->SetBranchAddress("jtphi", jtphi);
jetTree_p->SetBranchAddress("jteta", jteta);
jetTree_p->SetBranchAddress("jtm", jtm);
jetTree_p->SetBranchAddress("discr_csvV2", discr_csvV2);
hiTree_p->SetBranchStatus("*", 0);
hiTree_p->SetBranchStatus("run", 1);
hiTree_p->SetBranchStatus("evt", 1);
hiTree_p->SetBranchStatus("lumi", 1);
hiTree_p->SetBranchStatus("hiBin", 1);
hiTree_p->SetBranchStatus("vz", 1);
hiTree_p->SetBranchAddress("run", &run_);
hiTree_p->SetBranchAddress("evt", &evt_);
hiTree_p->SetBranchAddress("lumi", &lumi_);
hiTree_p->SetBranchAddress("hiBin", &hiBin_);
hiTree_p->SetBranchAddress("vz", &vz_);
std::string triggerName;
triggerName = isMC ? "HLT_HIL2Mu15ForPPRef_v1" : "HLT_HIL2Mu15_v1";
hltTree_p->SetBranchStatus(triggerName.data(),1);
hltTree_p->SetBranchAddress(triggerName.data(),&trig);
if(isDebug) std::cout << __LINE__ << std::endl;
if(isDebug) std::cout << __LINE__ << std::endl;
Int_t nEntries = (Int_t)lepTree_p->GetEntries();
Int_t entryDiv = ((Int_t)(nEntries/20));
if(isDebug) std::cout << __LINE__ << std::endl;
for(Int_t entry = 0; entry < nEntries; entry++){
if(isDebug) std::cout << __LINE__ << std::endl;
if(entry%entryDiv == 0 && nEntries >= 10000) std::cout << "Entry # " << entry << "/" << nEntries << std::endl;
if(isDebug) std::cout << __LINE__ << std::endl;
lepTree_p->GetEntry(entry);
jetTree_p->GetEntry(entry);
hiTree_p->GetEntry(entry);
hltTree_p->GetEntry(entry);
if(!trig) continue;
if(TMath::Abs(vz_) > 15) continue;
if(isDebug) std::cout << __LINE__ << std::endl;
Float_t tempMuPt_[nLep];
Float_t tempMuPhi_[nLep];
Float_t tempMuEta_[nLep];
Int_t tempMuChg_[nLep];
Float_t tempElePt_[nLep];
Float_t tempElePhi_[nLep];
Float_t tempEleEta_[nLep];
Int_t tempEleChg_[nLep];
for(Int_t lepIter = 0; lepIter < nLep; lepIter++){
lepPt_[lepIter] = -999;
lepPhi_[lepIter] = -999;
lepEta_[lepIter] = -999;
lepChg_[lepIter] = -999;
lepID_[lepIter] = -999;
}
for(Int_t lepIter = 0; lepIter < 2; lepIter++){
tempMuPt_[lepIter] = -999;
tempMuPhi_[lepIter] = -999;
tempMuEta_[lepIter] = -999;
tempMuChg_[lepIter] = -999;
tempElePt_[lepIter] = -999;
tempElePhi_[lepIter] = -999;
tempEleEta_[lepIter] = -999;
tempEleChg_[lepIter] = -999;
}
for(int ij = 0; ij<nMaxJets; ++ij) {
jtPt_[ij] = -999.;
jtEta_[ij] = -999.;
jtPhi_[ij] = -999.;
jtM_[ij] = -999.;
discr_csvV2_[ij] = -999.;
}
if(isDebug) std::cout << __LINE__ << std::endl;
const Int_t nMu = (Int_t)muPt_p->size();
const Int_t muTrkLayersCut = 5;
const Int_t muPixelHitsCut = 0;
//Find two leading muons
for(Int_t muIter = 0; muIter < nMu; muIter++){
if(TMath::Abs(muEta_p->at(muIter)) > muEtaCut) continue;
if(muPt_p->at(muIter) < muPtCut) continue;
if(muChi2NDF_p->at(muIter) >= muChi2NDFCut) continue;
if(TMath::Abs(muInnerD0_p->at(muIter)) > muInnerD0Cut) continue;
if(TMath::Abs(muInnerDz_p->at(muIter)) > muInnerDzCut) continue;
if(muMuonHits_p->at(muIter) <= muMuonHitsCut) continue;
if(muStations_p->at(muIter) <= muStationsCut) continue;
if(muTrkLayers_p->at(muIter) <= muTrkLayersCut) continue;
if(muPixelHits_p->at(muIter) <= muPixelHitsCut) continue;
if(muPt_p->at(muIter) > lepPt_[0]){
tempMuPt_[1] = tempMuPt_[0];
tempMuPhi_[1] = tempMuPhi_[0];
tempMuEta_[1] = tempMuEta_[0];
tempMuChg_[1] = tempMuChg_[0];
tempMuPt_[0] = muPt_p->at(muIter);
tempMuPhi_[0] = muPhi_p->at(muIter);
tempMuEta_[0] = muEta_p->at(muIter);
tempMuChg_[0] = muChg_p->at(muIter);
}
else if(muPt_p->at(muIter) > tempMuPt_[1]){
tempMuPt_[1] = muPt_p->at(muIter);
tempMuPhi_[1] = muPhi_p->at(muIter);
tempMuEta_[1] = muEta_p->at(muIter);
tempMuChg_[1] = muChg_p->at(muIter);
}
}
//Find two leading electrons
const Int_t nEle = (Int_t)elePt_p->size();
for(Int_t eleIter = 0; eleIter < nEle; eleIter++){
if(TMath::Abs(eleEta_p->at(eleIter)) > eleEtaCut) continue;
if(elePt_p->at(eleIter) < elePtCut) continue;
Int_t eleEtaCutPos = 0;
if(TMath::Abs(eleEta_p->at(eleIter)) > barrelEndcapEta) eleEtaCutPos = 1;
if(eleSigmaIEtaIEta_p->at(eleIter) > eleSigmaIEtaIEta_VetoCut[eleEtaCutPos]) continue;
if(TMath::Abs(eleDEtaAtVtx_p->at(eleIter)) > eleDEtaIn_VetoCut[eleEtaCutPos]) continue;
if(TMath::Abs(eleDPhiAtVtx_p->at(eleIter)) > eleDPhiIn_VetoCut[eleEtaCutPos]) continue;
if(eleHOverE_p->at(eleIter) > eleHOverE_VetoCut[eleEtaCutPos]) continue;
if(TMath::Abs(eleD0_p->at(eleIter)) > eleD0_VetoCut[eleEtaCutPos]) continue;
if(TMath::Abs(eleDz_p->at(eleIter)) > eleDZ_VetoCut[eleEtaCutPos]) continue;
if(elePt_p->at(eleIter) > tempElePt_[0]){
tempElePt_[1] = tempElePt_[0];
tempElePhi_[1] = tempElePhi_[0];
tempEleEta_[1] = tempEleEta_[0];
tempEleChg_[1] = tempEleChg_[0];
tempElePt_[0] = elePt_p->at(eleIter);
tempElePhi_[0] = elePhi_p->at(eleIter);
tempEleEta_[0] = eleEta_p->at(eleIter);
tempEleChg_[0] = eleChg_p->at(eleIter);
}
else if(elePt_p->at(eleIter) > tempElePt_[1]){
tempElePt_[1] = elePt_p->at(eleIter);
tempElePhi_[1] = elePhi_p->at(eleIter);
tempEleEta_[1] = eleEta_p->at(eleIter);
tempEleChg_[1] = eleChg_p->at(eleIter);
}
}
//store electrons and muons in out tree
int lepIter = 0;
for(Int_t muIter = 0; muIter < 2; muIter++){
if(tempMuPt_[muIter]<0.) continue;
lepPt_[lepIter] = tempMuPt_[muIter];
lepPhi_[lepIter] = tempMuPhi_[muIter];
lepEta_[lepIter] = tempMuEta_[muIter];
lepChg_[lepIter] = tempMuChg_[muIter];
lepID_[lepIter] = muID;
++lepIter;
}
for(Int_t eleIter = 0; eleIter < 2; eleIter++){
if(tempElePt_[eleIter]<0.) continue;
lepPt_[lepIter] = tempElePt_[eleIter];
lepPhi_[lepIter] = tempElePhi_[eleIter];
lepEta_[lepIter] = tempEleEta_[eleIter];
lepChg_[lepIter] = tempEleChg_[eleIter];
lepID_[lepIter] = eleID;
++lepIter;
}
if(lepIter<2) continue;
nLep_ = lepIter;
int njets = 0;
for(Int_t jetIter = 0; jetIter < nref; jetIter++){
if(jtpt[jetIter]<jetPtCut) continue;
jtPt_[njets] = jtpt[jetIter];
jtEta_[njets] = jteta[jetIter];
jtPhi_[njets] = jtphi[jetIter];
jtM_[njets] = jtm[jetIter];
discr_csvV2_[njets] = discr_csvV2[jetIter];
++njets;
}
nJt_ = njets;
skimTree_p->Fill();
}//entries loop
inFile_p->Close();
delete inFile_p;
}
outFile_p->cd();
TNamed pathStr1("pathStr1", outFileName.c_str());
pathStr1.Write("", TObject::kOverwrite);
TNamed pathStr2("pathStr2", inFileName.c_str());
pathStr2.Write("", TObject::kOverwrite);
skimTree_p->Write("", TObject::kOverwrite);
outFile_p->Close();
delete outFile_p;
return;
}
| gpl-3.0 |
deesoft/yii2-tools | Bootstrap.php | 427 | <?php
namespace dee\tools;
use Yii;
use yii\base\BootstrapInterface;
/**
* Description of Bootstrap
*
* @author Misbahul D Munir <misbahuldmunir@gmail.com>
* @since 1.0
*/
class Bootstrap implements BootstrapInterface
{
public function bootstrap($app)
{
Yii::$container->set('yii\caching\DbCache', 'dee\tools\DbCache');
Yii::$container->set('yii\web\DbSession', 'dee\tools\DbSession');
}
}
| gpl-3.0 |
home-climate-control/dz | dz3-servomaster/src/main/java/net/sf/dz3/device/actuator/servomaster/DamperFactory.java | 3913 | package net.sf.dz3.device.actuator.servomaster;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
import net.sf.dz3.device.actuator.Damper;
import net.sf.servomaster.device.model.ServoController;
/**
*
* @author Copyright © <a href="mailto:vt@homeclimatecontrol.com">Vadim Tkachenko</a> 2001-2018
*/
public class DamperFactory {
private final Logger logger = LogManager.getLogger(getClass());
private final ServoController theController;
public DamperFactory(String className, String portName) {
ThreadContext.push("DamperFactory()");
try {
Class<?> controllerClass = Class.forName(className);
logger.info("Found class: " + controllerClass.getCanonicalName());
if (!ServoController.class.isAssignableFrom(controllerClass)) {
throw new IllegalArgumentException("Not a servo controller: " + controllerClass.getName());
}
logger.info("new " + className + "()");
Object controllerObject = controllerClass.newInstance();
theController = (ServoController) controllerObject;
logger.info("Controller instantiated: " + theController.getMeta());
theController.init(portName);
} catch (ClassNotFoundException ex) {
throw new IllegalArgumentException("Can't find class for name '" + className + "'", ex);
} catch (SecurityException | InstantiationException | IllegalAccessException | IOException ex) {
throw new IllegalArgumentException("Don't know how to handle", ex);
} finally {
ThreadContext.pop();
}
}
/**
* Get an instance of a straight (not reversed) damper with no calibration.
*
* @param name Human readable name.
* @param id Controller specific servo ID.
*
* @return Damper instance.
* @throws IOException if things go wrong.
*/
public Damper getDamper(String name, String id) throws IOException {
return getDamper(name, id, false, null, null);
}
/**
* Get an instance of a damper with range calibration only.
*
* @param name Human readable name.
* @param id Controller specific servo ID.
* @param reverse {@code true} if the damper needs to be reversed.
* @param rangeCalibration Range calibration object.
*
* @return Damper instance.
* @throws IOException if things go wrong.
*/
public Damper getDamper(
String name,
String id,
boolean reverse,
RangeCalibration rangeCalibration) throws IOException {
return getDamper(name, id, reverse, rangeCalibration, null);
}
/**
* Get an instance of a damper with limit calibration only.
*
* @param name Human readable name.
* @param id Controller specific servo ID.
* @param reverse {@code true} if the damper needs to be reversed.
* @param limitCalibration Limit calibration object.
*
* @return Damper instance.
* @throws IOException if things go wrong.
*/
public Damper getDamper(
String name,
String id,
boolean reverse,
LimitCalibration limitCalibration) throws IOException {
return getDamper(name, id, reverse, null, limitCalibration);
}
private Damper getDamper(
String name,
String id,
boolean reverse,
RangeCalibration rangeCalibration,
LimitCalibration limitCalibration) throws IOException {
return new ServoDamper(name, theController.getServo(id), reverse, rangeCalibration, limitCalibration);
}
}
| gpl-3.0 |
kylethayer/bioladder | wiki/includes/revisiondelete/RevDelRevisionItem.php | 5825 | <?php
/**
* 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 RevisionDelete
*/
/**
* Item class for a live revision table row
*/
class RevDelRevisionItem extends RevDelItem {
/** @var Revision */
public $revision;
public function __construct( $list, $row ) {
parent::__construct( $list, $row );
$this->revision = static::initRevision( $list, $row );
}
/**
* Create revision object from $row sourced from $list
*
* @param RevisionListBase $list
* @param mixed $row
* @return Revision
*/
protected static function initRevision( $list, $row ) {
return new Revision( $row );
}
public function getIdField() {
return 'rev_id';
}
public function getTimestampField() {
return 'rev_timestamp';
}
public function getAuthorIdField() {
return 'rev_user';
}
public function getAuthorNameField() {
return 'rev_user_text';
}
public function getAuthorActorField() {
return 'rev_actor';
}
public function canView() {
return $this->revision->userCan( Revision::DELETED_RESTRICTED, $this->list->getUser() );
}
public function canViewContent() {
return $this->revision->userCan( Revision::DELETED_TEXT, $this->list->getUser() );
}
public function getBits() {
return $this->revision->getVisibility();
}
public function setBits( $bits ) {
$dbw = wfGetDB( DB_MASTER );
// Update revision table
$dbw->update( 'revision',
[ 'rev_deleted' => $bits ],
[
'rev_id' => $this->revision->getId(),
'rev_page' => $this->revision->getPage(),
'rev_deleted' => $this->getBits() // cas
],
__METHOD__
);
if ( !$dbw->affectedRows() ) {
// Concurrent fail!
return false;
}
// Update recentchanges table
$dbw->update( 'recentchanges',
[
'rc_deleted' => $bits,
'rc_patrolled' => RecentChange::PRC_AUTOPATROLLED
],
[
'rc_this_oldid' => $this->revision->getId(), // condition
// non-unique timestamp index
'rc_timestamp' => $dbw->timestamp( $this->revision->getTimestamp() ),
],
__METHOD__
);
return true;
}
public function isDeleted() {
return $this->revision->isDeleted( Revision::DELETED_TEXT );
}
public function isHideCurrentOp( $newBits ) {
return ( $newBits & Revision::DELETED_TEXT )
&& $this->list->getCurrent() == $this->getId();
}
/**
* Get the HTML link to the revision text.
* Overridden by RevDelArchiveItem.
* @return string
*/
protected function getRevisionLink() {
$date = $this->list->getLanguage()->userTimeAndDate(
$this->revision->getTimestamp(), $this->list->getUser() );
if ( $this->isDeleted() && !$this->canViewContent() ) {
return htmlspecialchars( $date );
}
return $this->getLinkRenderer()->makeKnownLink(
$this->list->title,
$date,
[],
[
'oldid' => $this->revision->getId(),
'unhide' => 1
]
);
}
/**
* Get the HTML link to the diff.
* Overridden by RevDelArchiveItem
* @return string
*/
protected function getDiffLink() {
if ( $this->isDeleted() && !$this->canViewContent() ) {
return $this->list->msg( 'diff' )->escaped();
} else {
return $this->getLinkRenderer()->makeKnownLink(
$this->list->title,
$this->list->msg( 'diff' )->text(),
[],
[
'diff' => $this->revision->getId(),
'oldid' => 'prev',
'unhide' => 1
]
);
}
}
/**
* @return string A HTML <li> element representing this revision, showing
* change tags and everything
*/
public function getHTML() {
$difflink = $this->list->msg( 'parentheses' )
->rawParams( $this->getDiffLink() )->escaped();
$revlink = $this->getRevisionLink();
$userlink = Linker::revUserLink( $this->revision );
$comment = Linker::revComment( $this->revision );
if ( $this->isDeleted() ) {
$revlink = "<span class=\"history-deleted\">$revlink</span>";
}
$content = "$difflink $revlink $userlink $comment";
$attribs = [];
$tags = $this->getTags();
if ( $tags ) {
list( $tagSummary, $classes ) = ChangeTags::formatSummaryRow(
$tags,
'revisiondelete',
$this->list->getContext()
);
$content .= " $tagSummary";
$attribs['class'] = implode( ' ', $classes );
}
return Xml::tags( 'li', $attribs, $content );
}
/**
* @return string Comma-separated list of tags
*/
public function getTags() {
return $this->row->ts_tags;
}
public function getApiData( ApiResult $result ) {
$rev = $this->revision;
$user = $this->list->getUser();
$ret = [
'id' => $rev->getId(),
'timestamp' => wfTimestamp( TS_ISO_8601, $rev->getTimestamp() ),
'userhidden' => (bool)$rev->isDeleted( Revision::DELETED_USER ),
'commenthidden' => (bool)$rev->isDeleted( Revision::DELETED_COMMENT ),
'texthidden' => (bool)$rev->isDeleted( Revision::DELETED_TEXT ),
];
if ( $rev->userCan( Revision::DELETED_USER, $user ) ) {
$ret += [
'userid' => $rev->getUser( Revision::FOR_THIS_USER ),
'user' => $rev->getUserText( Revision::FOR_THIS_USER ),
];
}
if ( $rev->userCan( Revision::DELETED_COMMENT, $user ) ) {
$ret += [
'comment' => $rev->getComment( Revision::FOR_THIS_USER ),
];
}
return $ret;
}
}
| gpl-3.0 |
valmynd/MediaFetcher | src/plugins/youtube_dl/youtube_dl/extractor/hketv.py | 5645 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
clean_html,
ExtractorError,
int_or_none,
merge_dicts,
parse_count,
str_or_none,
try_get,
unified_strdate,
urlencode_postdata,
urljoin,
)
class HKETVIE(InfoExtractor):
IE_NAME = 'hketv'
IE_DESC = '香港教育局教育電視 (HKETV) Educational Television, Hong Kong Educational Bureau'
_GEO_BYPASS = False
_GEO_COUNTRIES = ['HK']
_VALID_URL = r'https?://(?:www\.)?hkedcity\.net/etv/resource/(?P<id>[0-9]+)'
_TESTS = [{
'url': 'https://www.hkedcity.net/etv/resource/2932360618',
'md5': 'f193712f5f7abb208ddef3c5ea6ed0b7',
'info_dict': {
'id': '2932360618',
'ext': 'mp4',
'title': '喜閱一生(共享閱讀樂) (中、英文字幕可供選擇)',
'description': 'md5:d5286d05219ef50e0613311cbe96e560',
'upload_date': '20181024',
'duration': 900,
'subtitles': 'count:2',
},
'skip': 'Geo restricted to HK',
}, {
'url': 'https://www.hkedcity.net/etv/resource/972641418',
'md5': '1ed494c1c6cf7866a8290edad9b07dc9',
'info_dict': {
'id': '972641418',
'ext': 'mp4',
'title': '衣冠楚楚 (天使系列之一)',
'description': 'md5:10bb3d659421e74f58e5db5691627b0f',
'upload_date': '20070109',
'duration': 907,
'subtitles': {},
},
'params': {
'geo_verification_proxy': '<HK proxy here>',
},
'skip': 'Geo restricted to HK',
}]
_CC_LANGS = {
'中文(繁體中文)': 'zh-Hant',
'中文(简体中文)': 'zh-Hans',
'English': 'en',
'Bahasa Indonesia': 'id',
'\u0939\u093f\u0928\u094d\u0926\u0940': 'hi',
'\u0928\u0947\u092a\u093e\u0932\u0940': 'ne',
'Tagalog': 'tl',
'\u0e44\u0e17\u0e22': 'th',
'\u0627\u0631\u062f\u0648': 'ur',
}
_FORMAT_HEIGHTS = {
'SD': 360,
'HD': 720,
}
_APPS_BASE_URL = 'https://apps.hkedcity.net'
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
title = (
self._html_search_meta(
('ed_title', 'search.ed_title'), webpage, default=None) or
self._search_regex(
r'data-favorite_title_(?:eng|chi)=(["\'])(?P<id>(?:(?!\1).)+)\1',
webpage, 'title', default=None, group='url') or
self._html_search_regex(
r'<h1>([^<]+)</h1>', webpage, 'title', default=None) or
self._og_search_title(webpage)
)
file_id = self._search_regex(
r'post_var\[["\']file_id["\']\s*\]\s*=\s*(.+?);',
webpage, 'file ID')
curr_url = self._search_regex(
r'post_var\[["\']curr_url["\']\s*\]\s*=\s*"(.+?)";',
webpage, 'curr URL')
data = {
'action': 'get_info',
'curr_url': curr_url,
'file_id': file_id,
'video_url': file_id,
}
response = self._download_json(
self._APPS_BASE_URL + '/media/play/handler.php', video_id,
data=urlencode_postdata(data),
headers=merge_dicts({
'Content-Type': 'application/x-www-form-urlencoded'},
self.geo_verification_headers()))
result = response['result']
if not response.get('success') or not response.get('access'):
error = clean_html(response.get('access_err_msg'))
if 'Video streaming is not available in your country' in error:
self.raise_geo_restricted(
msg=error, countries=self._GEO_COUNTRIES)
else:
raise ExtractorError(error, expected=True)
formats = []
width = int_or_none(result.get('width'))
height = int_or_none(result.get('height'))
playlist0 = result['playlist'][0]
for fmt in playlist0['sources']:
file_url = urljoin(self._APPS_BASE_URL, fmt.get('file'))
if not file_url:
continue
# If we ever wanted to provide the final resolved URL that
# does not require cookies, albeit with a shorter lifespan:
# urlh = self._downloader.urlopen(file_url)
# resolved_url = urlh.geturl()
label = fmt.get('label')
h = self._FORMAT_HEIGHTS.get(label)
w = h * width // height if h and width and height else None
formats.append({
'format_id': label,
'ext': fmt.get('type'),
'url': file_url,
'width': w,
'height': h,
})
self._sort_formats(formats)
subtitles = {}
tracks = try_get(playlist0, lambda x: x['tracks'], list) or []
for track in tracks:
if not isinstance(track, dict):
continue
track_kind = str_or_none(track.get('kind'))
if not track_kind or not isinstance(track_kind, compat_str):
continue
if track_kind.lower() not in ('captions', 'subtitles'):
continue
track_url = urljoin(self._APPS_BASE_URL, track.get('file'))
if not track_url:
continue
track_label = track.get('label')
subtitles.setdefault(self._CC_LANGS.get(
track_label, track_label), []).append({
'url': self._proto_relative_url(track_url),
'ext': 'srt',
})
# Likes
emotion = self._download_json(
'https://emocounter.hkedcity.net/handler.php', video_id,
data=urlencode_postdata({
'action': 'get_emotion',
'data[bucket_id]': 'etv',
'data[identifier]': video_id,
}),
headers={'Content-Type': 'application/x-www-form-urlencoded'},
fatal=False) or {}
like_count = int_or_none(try_get(
emotion, lambda x: x['data']['emotion_data'][0]['count']))
return {
'id': video_id,
'title': title,
'description': self._html_search_meta(
'description', webpage, fatal=False),
'upload_date': unified_strdate(self._html_search_meta(
'ed_date', webpage, fatal=False), day_first=False),
'duration': int_or_none(result.get('length')),
'formats': formats,
'subtitles': subtitles,
'thumbnail': urljoin(self._APPS_BASE_URL, result.get('image')),
'view_count': parse_count(result.get('view_count')),
'like_count': like_count,
}
| gpl-3.0 |
fjn2/one4all | server/enums/status.js | 44 | module.exports = {
PLAY: 1,
STOP: 0,
};
| gpl-3.0 |
rmichela/GiantTrees | src/arbaro/java/net/sourceforge/arbaro/tree/StemTraversal.java | 1888 | /*
* This copy of Arbaro is redistributed to you under GPLv3 or (at your option)
* any later version. The original copyright notice is retained below.
*/
// #**************************************************************************
// #
// # Copyright (C) 2003-2006 Wolfram Diestel
// #
// # 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., 675 Mass Ave, Cambridge, MA 02139, USA.
// #
// # Send comments and bug fixes to diestel@steloj.de
// #
// #**************************************************************************/
package net.sourceforge.arbaro.tree;
/**
* An interface, for traversal of the segments and
* subsegments of a stem. (Compare Hierarchical Visitor Pattern)
*
*/
public interface StemTraversal {
boolean enterStem(Stem stem) throws TraversalException; // going into a Stem
boolean leaveStem(Stem stem) throws TraversalException; // coming out of a Stem
boolean enterSegment(Segment segment) throws TraversalException; // going into a Segment
boolean leaveSegment(Segment segment) throws TraversalException; // coming out of a Segment
boolean visitSubsegment(Subsegment subsegment) throws TraversalException; // process a Subsegment
}
| gpl-3.0 |
j1fig/nespera | nespera/models/page.py | 309 | from sqlalchemy import Column, Integer, String, ForeignKey, DateTime
from models import db
class Page(db.Base):
__tablename__ = 'page'
id = Column(Integer, primary_key=True)
site_id = Column(ForeignKey)
url = Column(String)
created = Column(DateTime)
last_parse = Column(DateTime)
| gpl-3.0 |
Gepardec/Hogarama | Hogajama/hogajama-interfaces/hogajama-interfaces-rs/src/main/java/com/gepardec/hogarama/rest/unitmanagement/dto/BaseDto.java | 320 | package com.gepardec.hogarama.rest.unitmanagement.dto;
public abstract class BaseDto {
protected Long id;
public BaseDto() {
}
protected BaseDto(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
| gpl-3.0 |
gohdan/DFC | known_files/hashes/bitrix/modules/vote/install/components/bitrix/voting.uf/templates/.default/edit.php | 63 | Bitrix 17.0.9 Business Demo = 4bc0f494c3d12da20ee5252dc0e5680a
| gpl-3.0 |
lcg833/Trebuchet | Trebuchet/src/main/java/com/android/launcher3/stats/util/Logger.java | 1575 | /*
* Copyright (c) 2015. The CyanogenMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.stats.util;
import android.text.TextUtils;
import android.util.Log;
/**
* <pre>
* Metrics debug logging
* </pre>
*/
public class Logger {
private static final String TAG = "TrebuchetStats";
/**
* Log a debug message
*
* @param tag {@link String}
* @param msg {@link String }
* @throws IllegalArgumentException {@link IllegalArgumentException}
*/
public static void logd(String tag, String msg) throws IllegalArgumentException {
if (TextUtils.isEmpty(tag)) {
throw new IllegalArgumentException("'tag' cannot be empty!");
}
if (TextUtils.isEmpty(msg)) {
throw new IllegalArgumentException("'msg' cannot be empty!");
}
if (isDebugging()) {
Log.d(TAG, tag + " [ " + msg + " ]");
}
}
private static boolean isDebugging() {
return Log.isLoggable(TAG, Log.DEBUG);
}
}
| gpl-3.0 |
bigace/bigace3 | library/Bigace/Search/Engine/Item.php | 7649 | <?php
/**
* Bigace - a PHP and MySQL based Web CMS.
*
* LICENSE
*
* This source file is subject to the new GNU General Public License
* that is bundled with this package in the file LICENSE.
* It is also available through the world-wide-web at this URL:
* http://www.bigace.de/license.html
*
* Bigace 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.
*
* @category Bigace
* @package Bigace_Search
* @subpackage Engine
* @copyright Copyright (c) 2009-2010 Keleo (http://www.keleo.de)
* @license http://www.bigace.de/license.html GNU Public License
* @version $Id: Service.php 152 2010-10-03 23:18:23Z kevin $
*/
/**
* Item search engine.
*
* It is important to know, that the search engine ONLY respects item permissions,
* when previously a Bigace_Principal was set using setUser().
*
* @category Bigace
* @package Bigace_Search
* @subpackage Engine
* @copyright Copyright (c) 2009-2010 Keleo (http://www.keleo.de)
* @license http://www.bigace.de/license.html GNU Public License
*/
class Bigace_Search_Engine_Item extends Bigace_Search_Engine_Abstract
{
/**
* The index that is used to store items.
*
* @var string
*/
const INDEX = 'items';
/**
* @see Bigace_Search_Engine_Abstract::addContent()
*
* @param Zend_Search_Lucene_Document $document
* @param mixed $object
* @return Zend_Search_Lucene_Document
*/
protected function addContent(Zend_Search_Lucene_Document $document, $object)
{
/* @var $object Bigace_Item */
if (!($object instanceof Bigace_Item)) {
throw new InvalidArgumentException('$object needs to be an Bigace_Item');
}
$type = Bigace_Item_Type_Registry::get($object->getItemType());
$cs = $type->getContentService();
$all = $cs->getAll($object);
$cnt = '';
/* @var $content Bigace_Content_Item */
foreach ($all as $content) {
$temp = $cs->getContentForIndex($content);
if ($temp !== null) {
// substitute the content over to the final document
$cnt .= ' ' . $temp;
}
}
$document->addField(
Zend_Search_Lucene_Field::unStored('content', $cnt, Bigace_Search_Engine::ENCODING)
);
// ----------- now add all meta fields --------------------
$indexEmpty = $this->getIndexEmptyFields();
$document->addField(
Zend_Search_Lucene_Field::text(
'title', $object->getName(), Bigace_Search_Engine::ENCODING
)
);
if ($indexEmpty || strlen(trim($object->getDescription())) > 0) {
$document->addField(
Zend_Search_Lucene_Field::text(
'teaser', $object->getDescription(), Bigace_Search_Engine::ENCODING
)
);
}
if ($indexEmpty || strlen(trim($object->getCatchwords())) > 0) {
$document->addField(
Zend_Search_Lucene_Field::text(
'keywords', $object->getCatchwords(), Bigace_Search_Engine::ENCODING
)
);
}
$document->addField(
Zend_Search_Lucene_Field::keyword(
'itemtype', $object->getItemType(), Bigace_Search_Engine::ENCODING
)
);
$document->addField(
Zend_Search_Lucene_Field::keyword(
'itemid', $object->getID(), Bigace_Search_Engine::ENCODING
)
);
$document->addField(
Zend_Search_Lucene_Field::keyword(
'language', $object->getLanguageID(), Bigace_Search_Engine::ENCODING
)
);
$document->addField(
Zend_Search_Lucene_Field::unIndexed(
'url', $object->getUniqueName(), Bigace_Search_Engine::ENCODING
)
);
$document->addField(
Zend_Search_Lucene_Field::keyword(
'hidden', (int)$object->isHidden(), Bigace_Search_Engine::ENCODING
)
);
return $document;
}
/**
* @see Bigace_Search_Engine_Abstract::getUniqueId()
*
* @param mixed $object
* @return string
*/
protected function getUniqueId($object)
{
/* @var $object Bigace_Item */
return $object->getItemType().'|'.$object->getID().'|'.$object->getLanguageID();
}
/**
* @see Bigace_Search_Engine_Abstract::filterResults()
*
* @param Bigace_Principal $user
* @param array(Bigace_Search_Result) $results
* @return array(Bigace_Search_Result)
*/
protected function filterResults(Bigace_Principal $user, array $results)
{
$all = array();
/* @var $result Bigace_Search_Result */
foreach ($results as $result) {
$perm = new Bigace_Acl_ItemPermission(
$result->getField('itemtype'),
$result->getField('itemid'),
$user->getID()
);
if ($perm->canRead()) {
$all[] = $result;
}
}
return $all;
}
/**
* @see Bigace_Search_Engine_Abstract::getIndexName()
*
* @return string
*/
protected function getIndexName()
{
return self::INDEX;
}
/**
* Reindex all items.
*
* Caution: This method is very expensive!
*/
public function indexAll($from = null, $amount = null)
{
// speed up the indexing of items
$this->getIndex()->setMaxBufferedDocs(50);
$this->getIndex()->setMaxMergeDocs(5000);
$this->getIndex()->setMergeFactor(50);
// delete and recreate the index if we reindex everything
// does not work if we only index a handful of items
if ($from === null && $amount === null) {
$this->search->recreateIndex();
}
$counter = 0;
$itemtypes = Bigace_Item_Type_Registry::getAll();
/* @var $type Bigace_Item_Type */
foreach ($itemtypes as $type) {
$request = new Bigace_Item_Request($type->getID());
if ($from !== null && $amount !== null) {
$request->setLimit($from, $amount);
}
$walker = new Bigace_Item_Walker($request);
$enum = new Bigace_Item_Enumeration($walker);
/* @var $item Bigace_Item */
foreach ($enum as $item) {
//echo PHP_EOL.$item->getID().'/'.$item->getLanguageID().PHP_EOL;
$document = $this->createDocument($item);
$this->addDocument($document);
$this->index($item);
$counter++;
}
}
$this->getIndex()->commit();
$this->getIndex()->optimize();
return $counter;
}
/**
* @see Bigace_Search_Engine::createQuery()
*
* @return Bigace_Search_Query_Item
*/
public function createQuery()
{
return new Bigace_Search_Query_Item();
}
/**
* Overwritten to returns specialized objects.
*
* @param array(Zend_Search_Lucene_Search_QueryHit) $hits
* @return array(Bigace_Search_Result)
*/
protected function convertHitsToResults(array $hits)
{
$all = array();
foreach ($hits as $hit) {
$all[] = new Bigace_Search_Result_Item($hit);
}
return $all;
}
} | gpl-3.0 |
openskip/skip | features/step_definitions/bookmark_steps.rb | 1365 | Given /^ブックマークレットのページをURL"(.*)"で表示する$/ do |url|
visit url_for(:controller => "bookmark", :action => "new", :url => url)
end
Given /^ブックマークの詳細ページをURL"(.*)"で表示する$/ do |url|
visit url_for(:controller => "bookmark", :action => "show", :url => url)
end
Given /^URLが"(.*)"で文字列が"(.*)"のリンクが存在すること$/ do |url, title|
Nokogiri::HTML(response.body).search("a[href=\"#{url}\"]").select{|a| a.text.include?(title) }.should_not be_empty
end
Given /^URLが"(.*)"タイトルが"(.*)"コメントが"(.*)"のブックマークを登録する$/ do |url, title, comment|
Given "ブックマークレットのページをURL\"#{url}\"で表示する"
Given "\"タイトル\"に\"#{title}\"と入力する"
Given "\"コメント\"に\"#{comment}\"と入力する"
Given "\"保存\"ボタンをクリックする"
end
Given /^以下のブックマークのリストを登録している:$/ do |bookmarks_table|
bookmarks_table.hashes.each do |hash|
uid = hash[:user] || 'a_user'
Given %!"#{uid}"がユーザ登録する! unless User.find_by_uid(uid)
Given %!"#{uid}"でログインする!
Given %!URLが"#{hash[:url]}"タイトルが"#{hash[:title]}"コメントが"#{hash[:comment]}"のブックマークを登録する!
end
end
| gpl-3.0 |
Juraji/Biliomi | core/src/main/java/nl/juraji/biliomi/io/api/twitch/v5/model/TwitchCommunity.java | 2879 | package nl.juraji.biliomi.io.api.twitch.v5.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Created by Juraji on 8-9-2017.
* Biliomi v3
*/
@XmlRootElement(name = "TwitchFollower")
@XmlAccessorType(XmlAccessType.FIELD)
public class TwitchCommunity {
@XmlElement(name = "_id")
private String id;
@XmlElement(name = "owner_id")
private Long ownerId;
@XmlElement(name = "name")
private String name;
@XmlElement(name = "avatar_image_url")
private String avatarImageUrl;
@XmlElement(name = "cover_image_url")
private String coverImageUrl;
@XmlElement(name = "description")
private String description;
@XmlElement(name = "description_html")
private String descriptionHtml;
@XmlElement(name = "rules")
private String rules;
@XmlElement(name = "rules_html")
private String rulesHtml;
@XmlElement(name = "language")
private String language;
@XmlElement(name = "summary")
private String summary;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Long getOwnerId() {
return ownerId;
}
public void setOwnerId(Long ownerId) {
this.ownerId = ownerId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAvatarImageUrl() {
return avatarImageUrl;
}
public void setAvatarImageUrl(String avatarImageUrl) {
this.avatarImageUrl = avatarImageUrl;
}
public String getCoverImageUrl() {
return coverImageUrl;
}
public void setCoverImageUrl(String coverImageUrl) {
this.coverImageUrl = coverImageUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescriptionHtml() {
return descriptionHtml;
}
public void setDescriptionHtml(String descriptionHtml) {
this.descriptionHtml = descriptionHtml;
}
public String getRules() {
return rules;
}
public void setRules(String rules) {
this.rules = rules;
}
public String getRulesHtml() {
return rulesHtml;
}
public void setRulesHtml(String rulesHtml) {
this.rulesHtml = rulesHtml;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
}
| gpl-3.0 |
Eartz/kml-polygon-to-svg | dist/index.js | 12247 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (kml, options) {
var view = {
minX: false,
maxX: false,
minY: false,
maxY: false
};
var updateView = function updateView(point) {
// Store the smallest and biggest coords to find out what the viewport is
if (view.minX === false || point[0] < view.minX) {
if (!isNaN(point[0])) {
view.minX = point[0];
}
}
if (view.maxX === false || point[0] > view.maxX) {
if (!isNaN(point[0])) {
view.maxX = point[0];
}
}
if (view.minY === false || point[1] < view.minY) {
if (!isNaN(point[1])) {
view.minY = point[1];
}
}
if (view.maxY === false || point[1] > view.maxY) {
if (!isNaN(point[1])) {
view.maxY = point[1];
}
}
};
var settings = _lodash2.default.extend({}, defaultOptions, options);
settings.precision = Number(settings.precision);
settings.simplificationTolerance = Number(settings.simplificationTolerance);
if (settings.precision < 0) {
settings.precision = 0; // avoid nasty bugs
}
var coordsTransform = function coordsTransform(points) {
return point;
};
if (typeof settings.coordsTransform === "function") {
coordsTransform = settings.coordsTransform;
}
// create a rounding function
var formatCoords = function (roundParam) {
if (settings.round === false) {
return function (coord) {
return coord;
}; // don't change anything
}
var precision = Number(roundParam);
return function (coord) {
return _lodash2.default.round(coord, precision);
};
}(settings.round);
// create a precision filter for a polygon
var createPrecisionFilter = function createPrecisionFilter(points) {
if (settings.precision === 0) {
return function () {
return true;
};
}
var meanX = _lodash2.default.mean(_lodash2.default.map(points, function (point) {
return point.x;
}));
var meanY = _lodash2.default.mean(_lodash2.default.map(points, function (point) {
return point.y;
}));
var acceptableDifferenceX = meanX * (settings.precision / 100);
var acceptableDifferenceY = meanY * (settings.precision / 100);
var prev = false;
return function (point) {
// if this is the first point, always return true
if (prev === false) {
prev = _lodash2.default.extend({}, point);
return true;
}
// if this is a moveTo point, always return true
if (point.type === "M") {
prev = _lodash2.default.extend({}, point);
return true;
}
// else if the difference in both X and Y is < acceptableDifference, don't use this point
if (Math.abs(prev.x - point.x) <= acceptableDifferenceX && Math.abs(prev.y - point.y) <= acceptableDifferenceY) {
return false;
}
// else, use the point
prev = _lodash2.default.extend({}, point);
return true;
};
};
var simplificater = function simplificater(points) {
if (!settings.simplification) {
return function (points) {
return points;
};
}
return function (points) {
return (0, _douglasPeucker2.default)(points, settings.simplificationTolerance);
};
};
var proj = _projections2.default[settings.projection];
var φ0 = settings.φ0;
var dataPrefix = settings.dataPrefix;
var dataTransform = function dataTransform(name, value) {
return { name: dataPrefix + name, value: value };
};
if (typeof settings.dataTransform === "function") {
dataTransform = settings.dataTransform;
}
var kmlPlacemarks = [];
var doc = _libxmljs2.default.parseXml(kml);
// Find polygons anywhere
var placemarks = doc.find('//kml:Placemark', { kml: "http://www.opengis.net/kml/2.2" });
// parse the kml and store it's content in plain objects
_lodash2.default.each(placemarks, function (placemark, indexPlacemark) {
var kmlPlacemark = {
polygons: [],
extendedData: []
};
// store polygon data
var polygons = placemark.find('.//kml:Polygon', { kml: "http://www.opengis.net/kml/2.2" });
if (polygons.length > 0) {
var _loop = function _loop() {
var tempKmlPolygon = {
points: []
};
// get coordinates
var coordsGroups = polygons[i].find(".//kml:coordinates", { kml: "http://www.opengis.net/kml/2.2" }).map(function (node) {
return node.text().trim();
});
_lodash2.default.each(coordsGroups, function (coords, groupIndex) {
var points = coords.replace(/\t+/gm, " ").replace(/\n+/gm, " ").split(' ');
for (var j = 0, pl = points.length; j < pl; j++) {
var point = points[j].split(',');
// Apply the projection
point[0] = proj.x(Number(point[0]), φ0);
point[1] = proj.y(Number(point[1]));
// 0: x, 1: y, 2: z
updateView(point); // update min/max X and Y
// LineTo ou MoveTo
var pointType = "L";
if (j <= 0) {
// if 1st point, moveTo
pointType = "M";
}
tempKmlPolygon.points.push({
x: point[0],
y: point[1],
z: Number(point[2]),
type: pointType,
groupId: "" + i + "_" + groupIndex // to fix missing MoveTos
});
}
});
kmlPlacemark.polygons.push(tempKmlPolygon);
};
for (var i = 0, l = polygons.length; i < l; i++) {
_loop();
}
}
// store extended data
var datas = placemark.find('.//kml:Data | .//kml:SimpleData', { kml: "http://www.opengis.net/kml/2.2" });
if (datas.length > 0) {
kmlPlacemark.extendedData = _lodash2.default.map(datas, function (data) {
return {
name: data.attr('name').value(),
content: _lodash2.default.trim(data.text(), " \r\n\t")
};
});
}
kmlPlacemarks.push(kmlPlacemark);
});
// Remove negative values, we want (0,0) to be the top left corner, not the center
var multiplier = 100; // work with bigger values
var Xdiff = 0;
if (view.minX < 0) {
Xdiff = 0 - view.minX;
} else if (view.minX > 0) {
Xdiff = 0 - view.minX;
}
var Ydiff = 0;
if (view.minY < 0) {
Ydiff = 0 - view.minY;
} else if (view.minY > 0) {
Ydiff = 0 - view.minY;
}
var newBoundaries = {
minX: (view.minX + Xdiff) * multiplier,
maxX: (view.maxX + Xdiff) * multiplier,
minY: (view.minY + Ydiff) * multiplier,
maxY: (view.maxY + Ydiff) * multiplier
};
_lodash2.default.each(kmlPlacemarks, function (kmlPlacemark) {
kmlPlacemark.polygons = _lodash2.default.map(kmlPlacemark.polygons, function (v) {
return {
points: v.points.map(function (vv) {
return {
x: formatCoords((vv.x + Xdiff) * multiplier),
y: formatCoords((vv.y + Ydiff) * multiplier),
z: vv.z,
type: vv.type,
groupId: vv.groupId
};
})
};
});
});
// output
var svg = new _libxmljs2.default.Document();
svg.setDtd('svg', "-//W3C//DTD SVG 1.0//EN", "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd");
var longest = newBoundaries.maxX;
if (newBoundaries.maxX < newBoundaries.maxY) {
longest = newBoundaries.maxY;
}
var g = svg.node("svg").attr({
version: "1.1",
id: "Calque_1",
xmlns: "http://www.w3.org/2000/svg",
"xmlns:xlink": "http://www.w3.org/1999/xlink",
overflow: "visible",
"xml:space": "preserve",
width: "" + longest,
height: "" + longest,
viewBox: "0 0 " + longest + " " + longest
}).node("g");
// write placemarks as <path> elements
_lodash2.default.each(kmlPlacemarks, function (placemark, k) {
var attrs = {};
_lodash2.default.each(_lodash2.default.filter(placemark.extendedData, settings.filterAttributes), function (data) {
var transformedData = dataTransform(data.name, data.content);
if (!!transformedData) {
attrs[transformedData.name] = transformedData.value;
}
});
// each polygon has all the placemark data... maybe group them in <g> ?
_lodash2.default.each(placemark.polygons, function (polygon, kk) {
var approximate = simplificater(polygon.points);
polygon.points = approximate(polygon.points); // use approximation algorithm
var precisionFilter = createPrecisionFilter(polygon.points); // create precision filter : skip a few points
var prevGroupId = false;
var pathData = _lodash2.default.reduce(_lodash2.default.filter(polygon.points, precisionFilter), function (path, point, index) {
var command = point.type;
if (prevGroupId !== point.groupId && command !== "M") {
// force moveTo
command = "M";
}
prevGroupId = point.groupId;
point = coordsTransform(point, newBoundaries, formatCoords);
return path + " " + command + " " + point.x + "," + point.y;
}, "") + " z";
var oAttributes = {};
if (!!settings.withId) {
_lodash2.default.extend(oAttributes, { id: "poly_" + k + "_" + kk });
}
_lodash2.default.extend(oAttributes, { d: pathData });
g.addChild(new _libxmljs2.default.Element(svg, "path").attr(_lodash2.default.extend({}, attrs, oAttributes)));
});
});
return svg.toString();
};
var _libxmljs = require("libxmljs");
var _libxmljs2 = _interopRequireDefault(_libxmljs);
var _projections = require("./projections.js");
var _projections2 = _interopRequireDefault(_projections);
var _douglasPeucker = require("./douglas-peucker.js");
var _douglasPeucker2 = _interopRequireDefault(_douglasPeucker);
var _lodash = require("lodash");
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var defaultOptions = {
φ0: 42, // used in equirectangular projection
projection: "mercator",
dataPrefix: "data-",
filterAttributes: function filterAttributes(data) {
// callback to filter which attributes are kept in the output
return true;
},
round: false, // Decimal precision of coordinates. use to reduce filesize if you don't need the precision.
withId: true, // disable if you don't want an automatic `id` attribute on each path in the output
precision: 0, // drops a few points in exchange for filesize. See the precisionFilter() internal function for details
simplification: false,
simplificationTolerance: 3,
dataTransform: false,
coordsTransform: function coordsTransform(points, view) {
return point;
} // use this to change coords on output, e.g. axial symmetry
};
; | gpl-3.0 |
KevinKazama/game | jeutennis/migrations/0025_auto_20151212_2244.py | 1069 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jeutennis', '0024_auto_20151209_1357'),
]
operations = [
migrations.CreateModel(
name='table_tournoi',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('nom', models.CharField(max_length=20)),
('participants', models.IntegerField(default=16)),
('date_tournoi', models.DateField()),
('winner', models.IntegerField(default=0)),
],
),
migrations.AddField(
model_name='table_joueurs',
name='idtournoi',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='table_match',
name='winner',
field=models.IntegerField(default=1),
preserve_default=False,
),
]
| gpl-3.0 |
shajoezhu/REMOVEplot | test_figure.cpp | 2084 | /*
* hybrid-Lambda is used to simulate gene trees given species network under
* coalescent process.
*
* Copyright (C) 2010 -- 2014 Sha (Joe) Zhu
*
* This file is part of hybrid-Lambda.
*
* hybrid-Lambda 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 <cppunit/TestCase.h>
#include <cppunit/extensions/HelperMacros.h>
#include "figure.hpp"
#pragma GCC diagnostic ignored "-Wwrite-strings"
class TestFigure : public CppUnit::TestCase {
CPPUNIT_TEST_SUITE( TestFigure );
CPPUNIT_TEST( good_CMD );
CPPUNIT_TEST( bad_CMD );
CPPUNIT_TEST_SUITE_END();
private:
void good_CMD() {
char* argv1[] = { "./plot", "-graph", "trees/7_tax_sp_nt1_para", "-dotF", "blah", "-branch", "-label" };
CPPUNIT_ASSERT_NO_THROW ( Figure( 6, argv1 ) );
CPPUNIT_ASSERT_NO_THROW ( Figure( 5, argv1 ) );
char* argv2[] = { "./plot", "-graph", "trees/7_tax_sp_nt1_para", "-dotF", "blah", "-label", "-branch" };
CPPUNIT_ASSERT_NO_THROW ( Figure( 6, argv1 ) );
CPPUNIT_ASSERT_NO_THROW ( Figure( 5, argv1 ) );
}
void bad_CMD(){
char* argv1[] = { "./plot", "-graph", "trees/7_tax_sp_nt1_para", "-dotF", "blah", "-branch", "-label" };
CPPUNIT_ASSERT_THROW ( Figure( 7, argv1 ) , std::invalid_argument ); // too many options
CPPUNIT_ASSERT_THROW ( Figure( 4, argv1 ) , std::invalid_argument ); // missing file name for -dotF
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( TestFigure );
| gpl-3.0 |
ajdiaz/mole | mole/output/serialize.py | 537 | #! /usr/bin/env python
# -*- encoding: utf-8 -*-
# vim:fenc=utf-8:
from mole.event import Event
from mole.output import Output
from mole.helper.netstring import NetString
try:
import cPickle as pickle
except ImportError:
import pickle
class OutputSerialize(Output):
def __call__(self, pipeline, heads=None):
for event in pipeline:
if isinstance(event, Event):
yield str(NetString(pickle.dumps(dict(event))))
else:
yield str(NetString(pickle.dumps(event)))
| gpl-3.0 |
estaban/pyload | module/plugins/crypter/C1neonCom.py | 386 | # -*- coding: utf-8 -*-
from module.plugins.internal.DeadCrypter import DeadCrypter
class C1neonCom(DeadCrypter):
__name__ = "C1neonCom"
__version__ = "0.05"
__type__ = "crypter"
__pattern__ = r'http://(?:www\.)?c1neon.com/.*?'
__description__ = """C1neon.com decrypter plugin"""
__author_name__ = "godofdream"
__author_mail__ = "soilfiction@gmail.com"
| gpl-3.0 |
macleginn/poetic-formula-extractor-python | src/PoeticAnalysisNew.py | 11087 | from DataStructures import LinkedList
from UsefulData import russianStopList as stopList
from UsefulData import russianAlphabet as alphabet
import math
# A bunch of helper methods.
def mean(valueList):
"""
Computes the mean from a list of numbers.
"""
return sum(valueList) / len(valueList)
def sd(valueList):
"""
Computes the standard deviation from a list of numbers.
"""
mu = mean(valueList)
return math.sqrt(
mean(
[(mu - value)**2 for value in valueList]
)
)
def clear(word):
"""
Reduces the word to its most basic form for the ease of comparison.
"""
word = word.lower()
redundantChars = '!?"№%:–,—.;()_+=»«“”…„“‘’\'[]`\u03010123456789<>'
for char in redundantChars:
word = word.replace(char, '')
word = word.replace('ё', 'е')
word = word.replace('г̇', 'г')
return word
def clearText(txt, alphabet):
"""
Removes all the non-word segments (dashes, numbers, etc.) from the text.
"""
txt = txt.replace('\ufeff', '')
txt = txt.replace('\u0301', '')
txt = txt.replace('\xab', '')
txt = txt.replace('\xbb', '')
txtClear = ''
lines = txt.splitlines()
for line in lines:
wordList = line.split()
wordListFiltered = []
for word in wordList:
for letter in word:
if letter in alphabet:
wordListFiltered.append(word)
break
for word in wordListFiltered:
txtClear += word.replace('[', '').replace(']', '').replace('(', '').replace(')', '').replace('<', '').replace('>', '') + ' '
txtClear = txtClear.strip()
txtClear = txtClear + '\n'
return txtClear
# Data-structures used for analysis.
class Word:
"""
The word furnished with its line number and its position in the line.
"""
def __init__(self, word, lineN, wordN):
self.word = word
self.line = lineN
self.index = wordN
def __str__(self):
return self.word
__repr__ = __str__
def __len__(self):
return len(self.word)
def __eq__(self, other):
return self.word == other.word
class NGram:
"""
An N-gram consisting of a Word-tuple of length N and a key.
"""
def __init__(self, wordList):
self.words = tuple(wordList)
key = ''
for word in self.words:
key += clear(word.word)[0:4]
self.key = key
def __str__(self):
out = ''
for word in self.words[:-1]:
out += word.word + ' '
out += self.words[-1].word
return out
__repr__ = __str__
def __len__(self):
return len(self.words)
def __eq__(self, other):
return self.key == other.key
class Poem:
"""
The main class. Computes all the necessary statistics on initialisation.
"""
def __init__(self, txt, userAlphabet = None, userStopList = None, verbose = False):
# Checking if user provided an alphabet and a stop-list. Both could be any iterables.
if userAlphabet == None:
self.alphabet = alphabet
else:
self.alphabet = userAlphabet
if userStopList == None:
self.stopList = stopList
else:
self.stopList = userStopList
self.verbose = verbose
txt = clearText(txt, self.alphabet)
# The main data structure: two associated 2-D arrays, one for the words themselves
# and the other to keep track of whether they form part of some formula.
poem = []
useMatrix = []
# Populating the arrays.
lines = txt.splitlines()
for i in range(len(lines)):
line = lines[i].split()
lineArr = []
useArr = []
for j in range(len(line)):
poeticWord = Word(line[j], i, j)
lineArr.append(poeticWord)
useArr.append(False)
poem.append(lineArr)
useMatrix.append(useArr)
self.poem = poem
self.useMatrix = useMatrix
self.formulas = self.makeFormulas()
# Start- and end-word indices of formula words for bracketing in the highlightFormulas method.
self.startWords = []
self.endWords = []
for item in self.formulas:
for formula in self.formulas[item]:
self.startWords.append((formula.words[0].line, formula.words[0].index))
self.endWords.append((formula.words[-1].line, formula.words[-1].index))
# Computing the formulaicDensity.
wordsTotal = 0
wordsInFormulas = 0
for line in poem:
for word in line:
wordsTotal += 1
if self.useMatrix[word.line][word.index]:
wordsInFormulas += 1
self.formulaicDensity = round((wordsInFormulas/wordsTotal)*100, 1)
def getFormulaicDensity(self):
"""
The getter method for formulaicDensity.
"""
return self.formulaicDensity
def makeFormulas(self):
"""
The main workhorse method, which extracts formulas from the text.
"""
formulaDict = {}
for i in reversed(range(2, 15)):
if self.verbose:
print('Поиск n-грамм длины ' + str(i))
Ngrams = []
for line in self.poem:
Ngrams += self.makeNGrams(line, i)
if self.verbose and len(Ngrams) > 0:
for item in Ngrams[:-1]:
print(item, end=' | ')
print(Ngrams[-1])
while True:
Ngrams = self.filter(Ngrams)
if len(Ngrams) > 1:
basis = Ngrams[0]
formulas2Be = LinkedList()
formulas2Be.add(basis)
for Ngram in Ngrams[1:]:
if Ngram == basis:
formulas2Be.add(Ngram)
for item in formulas2Be:
Ngrams.remove(item)
if len(formulas2Be) >= 2:
for item in formulas2Be:
for word in item.words:
self.useMatrix[word.line][word.index] = True
formulaDict[basis.key] = formulas2Be
else:
break
return formulaDict
def filter(self, arrOfNgrams):
"""
The method for removing N-grams with used words from the list.
"""
outNGrams = []
for item in arrOfNgrams:
addIt = True
for word in item.words:
if self.useMatrix[word.line][word.index]:
addIt = False
break
if addIt:
outNGrams.append(item)
return outNGrams
def makeNGrams(self, line, N):
"""
Extracts an array of N-grams of length N from a line, which is itself an array of Words.
"""
Ngrams = []
if N == 2:
for i in range(0, len(line)-1):
if clear(line[i].word) not in self.stopList and clear(line[i+1].word) not in self.stopList:
Ngrams.append(NGram([line[i], line[i+1]]))
else:
for i in range(0, len(line)-N+1):
NgramWords = []
for j in range(i, i+N):
NgramWords.append(line[j])
wordsFromStopList = 0
for word in NgramWords:
if clear(word.word) in self.stopList:
wordsFromStopList += 1
if len(NgramWords) - wordsFromStopList >= wordsFromStopList:
Ngram = NGram(NgramWords)
Ngrams.append(Ngram)
return Ngrams
def highlightFormulas(self, filename):
"""
Prints the poem to an html-file with formulas bracketed.
"""
outStr = """<html><meta charset="UTF-8"><body><p>"""
for line in self.poem:
for word in line:
if (word.line, word.index) in self.startWords:
outStr = outStr + '[' + word.word + ' '
elif (word.line, word.index) in self.endWords:
outStr = outStr + word.word + ']' + ' '
else:
outStr = outStr + word.word + ' '
outStr = outStr.strip() + '<br />'
outStr = outStr + """</p></body></html>"""
with open(filename + '.html', 'w', encoding='utf-8') as out:
out.write(outStr)
lastChar = ']'
for char in outStr:
if char != '[' and char != ']':
continue
elif char == '[' and lastChar == ']':
lastChar = '['
elif char == ']' and lastChar == '[':
lastChar = ']'
else:
print('Bracketing error!')
break
if lastChar == '[':
print('Bracketing error!')
def printFormulas(self):
"""
Prints all the formulas to the stdout in no particular order.
"""
for item in self.formulas:
print(self.formulas[item])
print()
def printFormulasToFile(self, filename):
"""
Prints all the formulas to the file in no particular order.
"""
with open(filename, 'w', encoding='utf-8') as out:
for item in self.formulas:
out.write(str(self.formulas[item]))
out.write('\n')
def computeFormulaicSpatialDensity(self):
"""
Returns a list of lengths of consecutive formulaic and non-formulaic fragments.
"""
if self.useMatrix[0][0]:
spatialDensities = [1]
else:
spatialDensities = [-1]
for item in self.useMatrix[0][1:]:
if item and spatialDensities[-1] > 0:
spatialDensities[-1] += 1
elif item and spatialDensities[-1] < 0:
spatialDensities.append(1)
elif not item and spatialDensities[-1] > 0:
spatialDensities.append(-1)
else:
spatialDensities[-1] -= 1
for row in self.useMatrix[1:]:
for item in row:
if item and spatialDensities[-1] > 0:
spatialDensities[-1] += 1
elif item and spatialDensities[-1] < 0:
spatialDensities.append(1)
elif not item and spatialDensities[-1] > 0:
spatialDensities.append(-1)
else:
spatialDensities[-1] -= 1
return spatialDensities
def computeSDOfNonFormulaicFrags(self):
"""
Computes the standard deviation of lengths of non-formulaic fragments.
"""
nonFormulaicFrags = [abs(value) for value in self.computeFormulaicSpatialDensity() if value < 0]
return sd(nonFormulaicFrags)
| gpl-3.0 |
KurzonDax/nZEDbetter | misc/testing/Dev_testing/clean_nzbs.php | 1419 | <?php
define('FS_ROOT', realpath(dirname(__FILE__)));
require_once(FS_ROOT."/../../../www/config.php");
require_once(WWW_DIR."lib/site.php");
require_once(WWW_DIR."lib/nzb.php");
$s = new Sites();
$site = $s->get();
$db = new DB();
$nzb = new NZB(true);
//
// This script removes all nzbs not found in the db.
//
if (isset($argv[1]) && $argv[1] === "true")
{
$dirItr = new RecursiveDirectoryIterator($site->nzbpath);
//$filterItr = new MyRecursiveFilterIterator($dirItr);
$itr = new RecursiveIteratorIterator($dirItr, RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($itr as $filePath) {
if (is_file($filePath))
{
$file = stristr($filePath->getFilename(), '.nzb.gz', true);
$res = $db->query(sprintf("SELECT * FROM `releases` where guid = %s", $db->escapeString($file)));
if ($res === false)
{
echo "$filePath\n";
echo $filePath->getFilename() . PHP_EOL;
}
}
}
$res = $db->queryDirect('SELECT ID, guid FROM `releases`');
while ($row = $db->fetchAssoc($res))
{
$nzbpath = $nzb->getNZBPath($row["guid"], $site->nzbpath, false, $site->nzbsplitlevel);
if (!file_exists($nzbpath))
{
echo "deleting ".$row['guid']."\n";
$db->query(sprintf("DELETE FROM `releases` WHERE `releases`.`ID` = %s", $row['ID']));
}
}
}
else
{
exit("This script removes all nzbs not found in the db.\nIf you are sure you want to run it, type php clean_nzbs.php true\n");
}
?>
| gpl-3.0 |
zzzzzzzzzzz0/zhscript | gjke4/new.cpp | 626 | /*
* new.cpp
*
* Created on: 2010-7-13
* Author: zzzzzzzzzzz
*/
#include "gjke.h"
#include "string.h"
#include "for_arg_.h"
dlle___ char* dlln___(new__)(int siz){
char* mem=new char[siz];
if(mem)
memset(mem,0,siz);
return mem;
}
dlle___ void dlln___(delete__)(int argc,...){
_for_args( argc )
delete (char*)x2lu__(s);
_next_args
}
//叫复制内存是因为内存还在,不是直接作用
dlle___ char* dlln___(dup__)(char* p){
return p;
}
dlle___ void* dlln___(pointer__)(char* p){
char***pp=new char**;
*pp=&p;
return (void*)pp;
}
dlle___ char* dlln___(pointer2__)(char*** p){
return **p;
}
| gpl-3.0 |
TheComet93/ponyban | dependencies/SFML-2.1-source/src/SFML/Window/Linux/InputImpl.cpp | 12325 | ////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window/Linux/InputImpl.hpp>
#include <SFML/Window/Window.hpp>
#include <SFML/Window/Linux/Display.hpp>
#include <X11/Xlib.h>
#include <X11/keysym.h>
namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
bool InputImpl::isKeyPressed(Keyboard::Key key)
{
// Get the corresponding X11 keysym
KeySym keysym = 0;
switch (key)
{
case Keyboard::A: keysym = XK_A; break;
case Keyboard::B: keysym = XK_B; break;
case Keyboard::C: keysym = XK_C; break;
case Keyboard::D: keysym = XK_D; break;
case Keyboard::E: keysym = XK_E; break;
case Keyboard::F: keysym = XK_F; break;
case Keyboard::G: keysym = XK_G; break;
case Keyboard::H: keysym = XK_H; break;
case Keyboard::I: keysym = XK_I; break;
case Keyboard::J: keysym = XK_J; break;
case Keyboard::K: keysym = XK_K; break;
case Keyboard::L: keysym = XK_L; break;
case Keyboard::M: keysym = XK_M; break;
case Keyboard::N: keysym = XK_N; break;
case Keyboard::O: keysym = XK_O; break;
case Keyboard::P: keysym = XK_P; break;
case Keyboard::Q: keysym = XK_Q; break;
case Keyboard::R: keysym = XK_R; break;
case Keyboard::S: keysym = XK_S; break;
case Keyboard::T: keysym = XK_T; break;
case Keyboard::U: keysym = XK_U; break;
case Keyboard::V: keysym = XK_V; break;
case Keyboard::W: keysym = XK_W; break;
case Keyboard::X: keysym = XK_X; break;
case Keyboard::Y: keysym = XK_Y; break;
case Keyboard::Z: keysym = XK_Z; break;
case Keyboard::Num0: keysym = XK_0; break;
case Keyboard::Num1: keysym = XK_1; break;
case Keyboard::Num2: keysym = XK_2; break;
case Keyboard::Num3: keysym = XK_3; break;
case Keyboard::Num4: keysym = XK_4; break;
case Keyboard::Num5: keysym = XK_5; break;
case Keyboard::Num6: keysym = XK_6; break;
case Keyboard::Num7: keysym = XK_7; break;
case Keyboard::Num8: keysym = XK_8; break;
case Keyboard::Num9: keysym = XK_9; break;
case Keyboard::Escape: keysym = XK_Escape; break;
case Keyboard::LControl: keysym = XK_Control_L; break;
case Keyboard::LShift: keysym = XK_Shift_L; break;
case Keyboard::LAlt: keysym = XK_Alt_L; break;
case Keyboard::LSystem: keysym = XK_Super_L; break;
case Keyboard::RControl: keysym = XK_Control_R; break;
case Keyboard::RShift: keysym = XK_Shift_R; break;
case Keyboard::RAlt: keysym = XK_Alt_R; break;
case Keyboard::RSystem: keysym = XK_Super_R; break;
case Keyboard::Menu: keysym = XK_Menu; break;
case Keyboard::LBracket: keysym = XK_bracketleft; break;
case Keyboard::RBracket: keysym = XK_bracketright; break;
case Keyboard::SemiColon: keysym = XK_semicolon; break;
case Keyboard::Comma: keysym = XK_comma; break;
case Keyboard::Period: keysym = XK_period; break;
case Keyboard::Quote: keysym = XK_dead_acute; break;
case Keyboard::Slash: keysym = XK_slash; break;
case Keyboard::BackSlash: keysym = XK_backslash; break;
case Keyboard::Tilde: keysym = XK_dead_grave; break;
case Keyboard::Equal: keysym = XK_equal; break;
case Keyboard::Dash: keysym = XK_minus; break;
case Keyboard::Space: keysym = XK_space; break;
case Keyboard::Return: keysym = XK_Return; break;
case Keyboard::BackSpace: keysym = XK_BackSpace; break;
case Keyboard::Tab: keysym = XK_Tab; break;
case Keyboard::PageUp: keysym = XK_Prior; break;
case Keyboard::PageDown: keysym = XK_Next; break;
case Keyboard::End: keysym = XK_End; break;
case Keyboard::Home: keysym = XK_Home; break;
case Keyboard::Insert: keysym = XK_Insert; break;
case Keyboard::Delete: keysym = XK_Delete; break;
case Keyboard::Add: keysym = XK_KP_Add; break;
case Keyboard::Subtract: keysym = XK_KP_Subtract; break;
case Keyboard::Multiply: keysym = XK_KP_Multiply; break;
case Keyboard::Divide: keysym = XK_KP_Divide; break;
case Keyboard::Left: keysym = XK_Left; break;
case Keyboard::Right: keysym = XK_Right; break;
case Keyboard::Up: keysym = XK_Up; break;
case Keyboard::Down: keysym = XK_Down; break;
case Keyboard::Numpad0: keysym = XK_KP_0; break;
case Keyboard::Numpad1: keysym = XK_KP_1; break;
case Keyboard::Numpad2: keysym = XK_KP_2; break;
case Keyboard::Numpad3: keysym = XK_KP_3; break;
case Keyboard::Numpad4: keysym = XK_KP_4; break;
case Keyboard::Numpad5: keysym = XK_KP_5; break;
case Keyboard::Numpad6: keysym = XK_KP_6; break;
case Keyboard::Numpad7: keysym = XK_KP_7; break;
case Keyboard::Numpad8: keysym = XK_KP_8; break;
case Keyboard::Numpad9: keysym = XK_KP_9; break;
case Keyboard::F1: keysym = XK_F1; break;
case Keyboard::F2: keysym = XK_F2; break;
case Keyboard::F3: keysym = XK_F3; break;
case Keyboard::F4: keysym = XK_F4; break;
case Keyboard::F5: keysym = XK_F5; break;
case Keyboard::F6: keysym = XK_F6; break;
case Keyboard::F7: keysym = XK_F7; break;
case Keyboard::F8: keysym = XK_F8; break;
case Keyboard::F9: keysym = XK_F9; break;
case Keyboard::F10: keysym = XK_F10; break;
case Keyboard::F11: keysym = XK_F11; break;
case Keyboard::F12: keysym = XK_F12; break;
case Keyboard::F13: keysym = XK_F13; break;
case Keyboard::F14: keysym = XK_F14; break;
case Keyboard::F15: keysym = XK_F15; break;
case Keyboard::Pause: keysym = XK_Pause; break;
default: keysym = 0; break;
}
// Open a connection with the X server
Display* display = OpenDisplay();
// Convert to keycode
KeyCode keycode = XKeysymToKeycode(display, keysym);
if (keycode != 0)
{
// Get the whole keyboard state
char keys[32];
XQueryKeymap(display, keys);
// Close the connection with the X server
CloseDisplay(display);
// Check our keycode
return (keys[keycode / 8] & (1 << (keycode % 8))) != 0;
}
else
{
// Close the connection with the X server
CloseDisplay(display);
return false;
}
}
////////////////////////////////////////////////////////////
bool InputImpl::isMouseButtonPressed(Mouse::Button button)
{
// Open a connection with the X server
Display* display = OpenDisplay();
// we don't care about these but they are required
::Window root, child;
int wx, wy;
int gx, gy;
unsigned int buttons = 0;
XQueryPointer(display, DefaultRootWindow(display), &root, &child, &gx, &gy, &wx, &wy, &buttons);
// Close the connection with the X server
CloseDisplay(display);
switch (button)
{
case Mouse::Left: return buttons & Button1Mask;
case Mouse::Right: return buttons & Button3Mask;
case Mouse::Middle: return buttons & Button2Mask;
case Mouse::XButton1: return false; // not supported by X
case Mouse::XButton2: return false; // not supported by X
default: return false;
}
return false;
}
////////////////////////////////////////////////////////////
Vector2i InputImpl::getMousePosition()
{
// Open a connection with the X server
Display* display = OpenDisplay();
// we don't care about these but they are required
::Window root, child;
int x, y;
unsigned int buttons;
int gx = 0;
int gy = 0;
XQueryPointer(display, DefaultRootWindow(display), &root, &child, &gx, &gy, &x, &y, &buttons);
// Close the connection with the X server
CloseDisplay(display);
return Vector2i(gx, gy);
}
////////////////////////////////////////////////////////////
Vector2i InputImpl::getMousePosition(const Window& relativeTo)
{
WindowHandle handle = relativeTo.getSystemHandle();
if (handle)
{
// Open a connection with the X server
Display* display = OpenDisplay();
// we don't care about these but they are required
::Window root, child;
int gx, gy;
unsigned int buttons;
int x = 0;
int y = 0;
XQueryPointer(display, handle, &root, &child, &gx, &gy, &x, &y, &buttons);
// Close the connection with the X server
CloseDisplay(display);
return Vector2i(x, y);
}
else
{
return Vector2i();
}
}
////////////////////////////////////////////////////////////
void InputImpl::setMousePosition(const Vector2i& position)
{
// Open a connection with the X server
Display* display = OpenDisplay();
XWarpPointer(display, None, DefaultRootWindow(display), 0, 0, 0, 0, position.x, position.y);
XFlush(display);
// Close the connection with the X server
CloseDisplay(display);
}
////////////////////////////////////////////////////////////
void InputImpl::setMousePosition(const Vector2i& position, const Window& relativeTo)
{
// Open a connection with the X server
Display* display = OpenDisplay();
WindowHandle handle = relativeTo.getSystemHandle();
if (handle)
{
XWarpPointer(display, None, handle, 0, 0, 0, 0, position.x, position.y);
XFlush(display);
}
// Close the connection with the X server
CloseDisplay(display);
}
} // namespace priv
} // namespace sf
| gpl-3.0 |
simonpatrick/stepbystep-java | hedwig-ut/src/main/java/com/hedwig/ut/samples/asserts/Transaction.java | 607 | package com.hedwig.ut.samples.asserts;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Transaction {
private final Date date;
private final int quantity;
public Transaction(String date, int quantity) throws ParseException {
this.date = new SimpleDateFormat("yyyy-MM-dd").parse(date);
this.quantity = quantity;
}
public Date getDate() {
return date;
}
public int getQuantity() {
return quantity;
}
@Override
public String toString() {
return "Transaction{" +
"date=" + date +
", quantity=" + quantity +
'}';
}
}
| gpl-3.0 |
drkpkg/artemisa | app/controllers/horario_controller.rb | 1223 | class HorarioController < ApplicationController
def list_all
@horarios = Horario.all
end
def create
horario = Horario.new
horario.horario_entrada = params[:hora_entrada]
horario.horario_salida = params[:hora_salida]
if horario.valid?
horario.save()
respond('200', 'En hora buena', 'Grupo creado satisfactoriamente', 'success', '/schedules/')
else
description = get_errors(horario)
respond('400', 'Error', description, 'error', '')
end
end
def modify
horario = Horario.find_by(id: params[:id])
param_hash = {horario_entrada: params[:hora_entrada], horario_salida: params[:hora_salida]}
if horario.update(param_hash)
respond('200', 'En hora buena', 'Grupo modificado satisfactoriamente', 'success', '/schedules/')
else
description = get_errors(horario)
respond('400', 'Error', description, 'error', '')
end
end
def delete
horario = Horario.find_by(id: params[:id])
if (horario.delete)
respond('200', 'En hora buena', 'grupo eliminado satisfactoriamente', 'success', '/schedules/')
else
description = get_errors(horario)
respond('400', 'Error', description, 'error', '')
end
end
end
| gpl-3.0 |
mpg2899/csc202 | csc202/bookfiles/bookFiles/ch03/ReverseStrings.java | 929 | //----------------------------------------------------------------------
// ReverseStrings.java by Dale/Joyce/Weems Chapter 3
//
// Sample use of stack. Outputs strings in reverse order of entry.
//----------------------------------------------------------------------
import ch03.stacks.*;
import java.util.Scanner;
public class ReverseStrings
{
public static void main(String[] args)
{
Scanner conIn = new Scanner(System.in);
BoundedStackInterface<String> stack;
stack = new ArrayStack<String>(3);
String line;
for (int i = 1; i <= 3; i++)
{
System.out.print("Enter a line of text > ");
line = conIn.nextLine();
stack.push(line);
}
System.out.println("\nReverse is:\n");
while (!stack.isEmpty())
{
line = stack.top();
stack.pop();
System.out.println(line);
}
}
} | gpl-3.0 |
estebansapiens/samplephpapp | views/forms/testimonial/update.php | 351 | <?php
// Settings Start
$dirname = "/views/forms/testimonial/";
$settingsfile = dirname(__FILE__).$dirname."config.php";
$settingscodehandle = fopen($settingsfile, "r");
$settingsdata = @fread($settingscodehandle, filesize($settingsfile));
eval(' ?>'.$settingsdata.'<?php ');
// Settings End
include_once('./views/forms/form-templates/update.php');
?> | gpl-3.0 |
colearnr/discuss | public/src/modules/composer.js | 12961 | define(['taskbar'], function(taskbar) {
var composer = {
initialized: false,
active: undefined,
taskbar: taskbar,
posts: {},
postContainer: undefined,
};
var uploadsInProgress = [];
var needToConfirm = false;
var lastUUID = null;
var anchor = null;
//window.onbeforeunload = confirmExit;
if ($.receiveMessage) {
$.receiveMessage(function (msg) {
if (msg && msg.data) {
try {
tmpanchor = JSON.parse(msg.data);
if (tmpanchor.lbit_id) {
anchor = tmpanchor;
}
} catch (e) {
}
}
});
}
var formatTime = function(secs) {
if (!secs || isNaN(parseInt(secs, 10))) {
return "";
}
var hh = Math.floor(secs / 3600);
var mm = Math.floor((secs - (hh * 3600))/60);
var ss = secs - (hh * 3600) - (mm * 60);
if (hh < 10) {hh = '0' + hh}
if (mm < 10) {mm = '0' + mm}
if (ss < 10) {ss = '0' + ss}
if (hh == '00') {
return mm + ':' + ss;
} else {
return hh + ':' + mm + ':' + ss;
}
};
function formatPage(page) {
if (page && !isNaN(parseInt(page, 10))) {
return 'Page ' + page;
}
}
function confirmExit() {
if (needToConfirm) {
var summernoteEditor = $("[data-edit=summernote]");
if (summernoteEditor && summernoteEditor.length) {
try {
var bodyVal = summernoteEditor.code();
if (bodyVal && bodyVal.length > 1 && bodyVal != '<p><br></p>' && bodyVal != '<br>' && bodyVal != '<p></p>') {
return "You are attempting to leave without posting your comment. Are you sure?"
}
} catch (e) {
}
}
}
}
function renderHTML(text) {
if (text) {
text = text.replace(new RegExp('(<p><br></p>)*$'), '');
text = text.replace(new RegExp('(<p></p>)*$'), '');
}
return text;
}
function createImagePlaceholder(img) {
var text = $('.post-window textarea').val(),
textarea = $('.post-window textarea'),
imgText = "";
text += imgText;
textarea.val(text + " ");
uploadsInProgress.push(1);
socket.emit("api:posts.uploadImage", img, function(err, data) {
var currentText = textarea.val();
imgText = "";
if(!err)
textarea.val(currentText.replace(imgText, ""));
else
textarea.val(currentText.replace(imgText, ""));
uploadsInProgress.pop();
});
}
function loadFile(file) {
var reader = new FileReader(),
dropDiv = $('.post-window .imagedrop'),
uuid = dropDiv.parents('[data-uuid]').attr('data-uuid');
$(reader).on('loadend', function(e) {
var bin = this.result;
bin = bin.split(',')[1];
var img = {
name: file.name,
data: bin
};
createImagePlaceholder(img);
dropDiv.hide();
});
reader.readAsDataURL(file);
}
function initializeFileReader() {
jQuery.event.props.push( "dataTransfer" );
var draggingDocument = false;
if(window.FileReader) {
var drop = $('.post-window .imagedrop'),
textarea = $('.post-window textarea');
$(document).on('dragstart', function(e) {
draggingDocument = true;
}).on('dragend', function(e) {
draggingDocument = false;
});
textarea.on('dragenter', function(e) {
if(draggingDocument)
return;
drop.css('top', textarea.position().top + 'px');
drop.show();
drop.on('dragleave', function(ev) {
drop.hide();
drop.off('dragleave');
});
});
function cancel(e) {
e.preventDefault();
return false;
}
drop.on('dragover', cancel);
drop.on('dragenter', cancel);
drop.on('drop', function(e) {
e.preventDefault();
var uuid = drop.parents('[data-uuid]').attr('data-uuid'),
dt = e.dataTransfer,
files = dt.files;
for (var i=0; i<files.length; i++) {
loadFile(files[i]);
}
if(!files.length)
drop.hide();
return false;
});
}
}
composer.init = function() {
if (!composer.initialized) {
var taskbar = document.getElementById('taskbar');
composer.postContainer = document.createElement('div');
composer.postContainer.className = 'post-window';
composer.postContainer.innerHTML = '<div class="post-div">' +
'<input type="text" class="commenttitle hide" tabIndex="1" placeholder="Enter your topic title here..." />' +
'<textarea id="commentarea" class="commentarea" data-edit="summernote" data-chat="true" tabIndex="2"></textarea>' +
'<div id="div_start"><button id="start_button" onclick="startButton(event)" title="Voice comment"><img alt="Voice comment" id="start_img" src="/images/mic.gif"></button></div>' +
'</div>';
document.body.insertBefore(composer.postContainer, taskbar);
socket.on('api:composer.push', function(threadData) {
if (!threadData.error) {
var uuid = utils.generateUUID();
if (lastUUID) {
composer.discard(lastUUID);
}
composer.taskbar.push('composer', uuid, {
title: (!threadData.cid ? (threadData.title || '') : 'New Topic'),
icon: threadData.picture
});
var defaultBody = '';
if (anchor && anchor.lbit_id != null && anchor.topic_id != null) {
if (anchor.currentTime) {
defaultBody = '<a class="btn btn-default" href="#t=' + anchor.currentTime + '">' + formatTime(anchor.currentTime) + '</a> ';
} else if (anchor.currentPage) {
defaultBody = '<a class="btn btn-default" href="#p=' + anchor.currentPage + '">' + formatPage(anchor.currentPage) + '</a> ';
}
}
composer.posts[uuid] = {
tid: threadData.tid,
cid: threadData.cid,
category_id: threadData.category_id,
pid: threadData.pid,
title: threadData.title || '',
body: threadData.body || defaultBody,
modified: false
};
composer.load(uuid);
lastUUID = uuid;
} else {
app.alert({
type: 'danger',
timeout: 5000,
alert_id: 'post_error',
title: 'Please Log In',
message: 'Posting is currently restricted to registered members only, click here to log in',
clickfn: function() {
ajaxify.go('login');
}
});
}
});
socket.on('api:composer.editCheck', function(editCheck) {
if (editCheck.titleEditable === true) composer.postContainer.querySelector('input').readOnly = false;
});
// Post Window events
var jPostContainer = $(composer.postContainer),
postContentEl = composer.postContainer.querySelector('textarea');
jPostContainer.on('change', 'input, textarea', function() {
var uuid = $(this).parents('.post-window')[0].getAttribute('data-uuid');
if (this.nodeName === 'INPUT') composer.posts[uuid].title = this.value;
else if (this.nodeName === 'TEXTAREA') composer.posts[uuid].body = this.value;
// Mark this post window as having been changed
composer.posts[uuid].modified = true;
});
jPostContainer.on('keyup', '.note-editable', function(e) {
if (e.which === 13 && !e.shiftKey) {
var uuid = $(this).parents('.post-window').attr('data-uuid');
composer.post(uuid);
}
});
jPostContainer.on('click', '.action-bar button', function() {
var action = this.getAttribute('data-action'),
uuid = $(this).parents('.post-window').attr('data-uuid');
switch(action) {
case 'post': composer.post(uuid); break;
case 'minimize': composer.minimize(uuid); break;
case 'discard':
composer.discard(uuid);
break;
}
});
window.addEventListener('resize', function() {
if (composer.active !== undefined) composer.reposition(composer.active);
});
summernoteEditorInit();
composer.initialized = true;
}
}
composer.push = function(tid, cid, pid, text) {
socket.emit('api:composer.push', {
tid: tid, // Replying
cid: cid, // Posting
pid: pid, // Editing
body: text // Predefined text
});
}
composer.load = function(post_uuid) {
var post_data = composer.posts[post_uuid],
titleEl = composer.postContainer.querySelector('input'),
bodyEl = composer.postContainer.querySelector('textarea');
composer.reposition(post_uuid);
composer.active = post_uuid;
composer.postContainer.setAttribute('data-uuid', post_uuid);
if (post_data.tid) {
titleEl.value = 'Replying to: ' + post_data.title;
titleEl.readOnly = true;
$(titleEl).addClass('hidden-sm').addClass('hidden-xs');
} else if (post_data.pid) {
titleEl.value = post_data.title;
titleEl.readOnly = true;
$(titleEl).addClass('hidden-sm').addClass('hidden-xs');
socket.emit('api:composer.editCheck', post_data.pid);
} else {
titleEl.value = post_data.title;
titleEl.readOnly = false;
$(titleEl).removeClass('hidden-sm').removeClass('hidden-xs');
}
//bodyEl.value = post_data.body;
$('#commentarea').code(post_data.body);
// Direct user focus to the correct element
if (post_data.cid) {
titleEl.focus();
} else {
$('.note-editable').get(0).focus();
}
$('.topic-main-buttons').addClass('compose-mode');
$('html, body').animate({ scrollTop: $('.topic-main-buttons').offset().top});
}
composer.reposition = function(post_uuid) {
var postWindowEl = composer.postContainer.querySelector('.post-div'),
taskbarBtn = document.querySelector('#taskbar [data-uuid="' + post_uuid + '"]'),
btnRect = taskbarBtn.getBoundingClientRect(),
taskbarRect = document.getElementById('taskbar').getBoundingClientRect(),
windowRect, leftPos;
composer.postContainer.style.display = 'block';
windowRect = postWindowEl.getBoundingClientRect();
leftPos = btnRect.left + btnRect.width - windowRect.width;
//postWindowEl.style.left = (leftPos > 0 ? leftPos : 30) + 'px';
postWindowEl.style.right = '0px';
//composer.postContainer.style.bottom = (taskbarRect.height || -60) + "px";
composer.postContainer.style.bottom = "0px";
}
composer.post = function(post_uuid) {
// Check title and post length
var postData = composer.posts[post_uuid],
titleEl = composer.postContainer.querySelector('input'),
bodyEl = composer.postContainer.querySelector('textarea');
titleEl.value = titleEl.value.trim();
//bodyEl.value = bodyEl.value.trim();
var summernoteEditor = $("[data-edit=summernote]");
var bodyVal = summernoteEditor.code();
var EMPTY_VALUES = ['', '<br>', ' ', '<div><br></div><div><br></div>', '<div><br></div>'];
if (!bodyVal || EMPTY_VALUES.indexOf(bodyVal) !== -1) {
return;
}
if(uploadsInProgress.length) {
return app.alert({
type: 'warning',
timeout: 2000,
title: 'Still uploading',
message: "Please wait for uploads to complete.",
alert_id: 'post_error'
});
}
// Still here? Let's post.
if (postData.cid) {
socket.emit('api:topics.post', {
'title' : titleEl.value,
'content' : renderHTML(bodyVal),
'category_id' : postData.cid,
'anchor': anchor
});
} else if (postData.tid) {
socket.emit('api:posts.reply', {
'topic_id' : postData.tid,
'category_id' : postData.category_id,
'content' : renderHTML(bodyVal),
'anchor': anchor
});
} else if (postData.pid) {
socket.emit('api:posts.edit', {
'pid': postData.pid,
'content': renderHTML(bodyVal),
'category_id' : postData.category_id,
'title': titleEl.value,
'anchor': anchor
});
}
composer.clear(post_uuid);
}
composer.clear = function(post_uuid) {
if (composer.posts[post_uuid]) {
$(composer.postContainer).find('.imagedrop').hide();
uploadsInProgress.length = 0;
var summernoteEditor = $("[data-edit=summernote]");
summernoteEditor.code(' ');
$('.note-editable').get(0).focus();
}
}
composer.discard = function(post_uuid) {
if (composer.posts[post_uuid]) {
$(composer.postContainer).find('.imagedrop').hide();
delete composer.posts[post_uuid];
uploadsInProgress.length = 0;
composer.minimize();
taskbar.discard('composer', post_uuid);
var summernoteEditor = $("[data-edit=summernote]");
summernoteEditor.code("");
$('.topic-main-buttons').removeClass('compose-mode');
}
}
composer.minimize = function(uuid) {
if (composer.posts && composer.posts[uuid]) {
var summernoteEditor = $("[data-edit=summernote]");
composer.posts[uuid].body = summernoteEditor.code();
composer.posts[uuid].modified = true;
}
composer.postContainer.style.display = 'none';
composer.active = undefined;
taskbar.minimize('composer', uuid);
$('.topic-main-buttons').removeClass('compose-mode');
}
composer.init();
return {
push: composer.push,
load: composer.load,
minimize: composer.minimize
};
});
| gpl-3.0 |
WhisperSystems/Signal-Android | libsignal/service/src/main/java/org/whispersystems/signalservice/api/messages/SignalServiceContent.java | 68993 | /*
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.whispersystems.signalservice.api.messages;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import org.signal.libsignal.metadata.ProtocolInvalidKeyException;
import org.signal.libsignal.metadata.ProtocolInvalidMessageException;
import org.signal.zkgroup.InvalidInputException;
import org.signal.zkgroup.groups.GroupMasterKey;
import org.whispersystems.libsignal.IdentityKey;
import org.whispersystems.libsignal.InvalidKeyException;
import org.whispersystems.libsignal.InvalidMessageException;
import org.whispersystems.libsignal.LegacyMessageException;
import org.whispersystems.libsignal.logging.Log;
import org.whispersystems.libsignal.protocol.DecryptionErrorMessage;
import org.whispersystems.libsignal.protocol.SenderKeyDistributionMessage;
import org.whispersystems.libsignal.util.guava.Optional;
import org.whispersystems.signalservice.api.InvalidMessageStructureException;
import org.whispersystems.signalservice.api.messages.calls.AnswerMessage;
import org.whispersystems.signalservice.api.messages.calls.BusyMessage;
import org.whispersystems.signalservice.api.messages.calls.HangupMessage;
import org.whispersystems.signalservice.api.messages.calls.IceUpdateMessage;
import org.whispersystems.signalservice.api.messages.calls.OfferMessage;
import org.whispersystems.signalservice.api.messages.calls.OpaqueMessage;
import org.whispersystems.signalservice.api.messages.calls.SignalServiceCallMessage;
import org.whispersystems.signalservice.api.messages.multidevice.BlockedListMessage;
import org.whispersystems.signalservice.api.messages.multidevice.ConfigurationMessage;
import org.whispersystems.signalservice.api.messages.multidevice.MessageRequestResponseMessage;
import org.whispersystems.signalservice.api.messages.multidevice.OutgoingPaymentMessage;
import org.whispersystems.signalservice.api.messages.multidevice.ReadMessage;
import org.whispersystems.signalservice.api.messages.multidevice.RequestMessage;
import org.whispersystems.signalservice.api.messages.multidevice.SentTranscriptMessage;
import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage;
import org.whispersystems.signalservice.api.messages.multidevice.StickerPackOperationMessage;
import org.whispersystems.signalservice.api.messages.multidevice.VerifiedMessage;
import org.whispersystems.signalservice.api.messages.multidevice.ViewOnceOpenMessage;
import org.whispersystems.signalservice.api.messages.multidevice.ViewedMessage;
import org.whispersystems.signalservice.api.messages.shared.SharedContact;
import org.whispersystems.signalservice.api.payments.Money;
import org.whispersystems.signalservice.api.push.SignalServiceAddress;
import org.whispersystems.signalservice.api.util.UuidUtil;
import org.whispersystems.signalservice.internal.push.SignalServiceProtos;
import org.whispersystems.signalservice.internal.push.UnsupportedDataMessageException;
import org.whispersystems.signalservice.internal.push.UnsupportedDataMessageProtocolVersionException;
import org.whispersystems.signalservice.internal.serialize.SignalServiceAddressProtobufSerializer;
import org.whispersystems.signalservice.internal.serialize.SignalServiceMetadataProtobufSerializer;
import org.whispersystems.signalservice.internal.serialize.protos.SignalServiceContentProto;
import org.whispersystems.util.FlagUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.whispersystems.signalservice.internal.push.SignalServiceProtos.GroupContext.Type.DELIVER;
public final class SignalServiceContent {
private static final String TAG = SignalServiceContent.class.getSimpleName();
private final SignalServiceAddress sender;
private final int senderDevice;
private final long timestamp;
private final long serverReceivedTimestamp;
private final long serverDeliveredTimestamp;
private final boolean needsReceipt;
private final SignalServiceContentProto serializedState;
private final String serverUuid;
private final Optional<byte[]> groupId;
private final Optional<SignalServiceDataMessage> message;
private final Optional<SignalServiceSyncMessage> synchronizeMessage;
private final Optional<SignalServiceCallMessage> callMessage;
private final Optional<SignalServiceReceiptMessage> readMessage;
private final Optional<SignalServiceTypingMessage> typingMessage;
private final Optional<SenderKeyDistributionMessage> senderKeyDistributionMessage;
private final Optional<DecryptionErrorMessage> decryptionErrorMessage;
private SignalServiceContent(SignalServiceDataMessage message,
Optional<SenderKeyDistributionMessage> senderKeyDistributionMessage,
SignalServiceAddress sender,
int senderDevice,
long timestamp,
long serverReceivedTimestamp,
long serverDeliveredTimestamp,
boolean needsReceipt,
String serverUuid,
Optional<byte[]> groupId,
SignalServiceContentProto serializedState)
{
this.sender = sender;
this.senderDevice = senderDevice;
this.timestamp = timestamp;
this.serverReceivedTimestamp = serverReceivedTimestamp;
this.serverDeliveredTimestamp = serverDeliveredTimestamp;
this.needsReceipt = needsReceipt;
this.serverUuid = serverUuid;
this.groupId = groupId;
this.serializedState = serializedState;
this.message = Optional.fromNullable(message);
this.synchronizeMessage = Optional.absent();
this.callMessage = Optional.absent();
this.readMessage = Optional.absent();
this.typingMessage = Optional.absent();
this.senderKeyDistributionMessage = senderKeyDistributionMessage;
this.decryptionErrorMessage = Optional.absent();
}
private SignalServiceContent(SignalServiceSyncMessage synchronizeMessage,
Optional<SenderKeyDistributionMessage> senderKeyDistributionMessage,
SignalServiceAddress sender,
int senderDevice,
long timestamp,
long serverReceivedTimestamp,
long serverDeliveredTimestamp,
boolean needsReceipt,
String serverUuid,
Optional<byte[]> groupId,
SignalServiceContentProto serializedState)
{
this.sender = sender;
this.senderDevice = senderDevice;
this.timestamp = timestamp;
this.serverReceivedTimestamp = serverReceivedTimestamp;
this.serverDeliveredTimestamp = serverDeliveredTimestamp;
this.needsReceipt = needsReceipt;
this.serverUuid = serverUuid;
this.groupId = groupId;
this.serializedState = serializedState;
this.message = Optional.absent();
this.synchronizeMessage = Optional.fromNullable(synchronizeMessage);
this.callMessage = Optional.absent();
this.readMessage = Optional.absent();
this.typingMessage = Optional.absent();
this.senderKeyDistributionMessage = senderKeyDistributionMessage;
this.decryptionErrorMessage = Optional.absent();
}
private SignalServiceContent(SignalServiceCallMessage callMessage,
Optional<SenderKeyDistributionMessage> senderKeyDistributionMessage,
SignalServiceAddress sender,
int senderDevice,
long timestamp,
long serverReceivedTimestamp,
long serverDeliveredTimestamp,
boolean needsReceipt,
String serverUuid,
Optional<byte[]> groupId,
SignalServiceContentProto serializedState)
{
this.sender = sender;
this.senderDevice = senderDevice;
this.timestamp = timestamp;
this.serverReceivedTimestamp = serverReceivedTimestamp;
this.serverDeliveredTimestamp = serverDeliveredTimestamp;
this.needsReceipt = needsReceipt;
this.serverUuid = serverUuid;
this.groupId = groupId;
this.serializedState = serializedState;
this.message = Optional.absent();
this.synchronizeMessage = Optional.absent();
this.callMessage = Optional.of(callMessage);
this.readMessage = Optional.absent();
this.typingMessage = Optional.absent();
this.senderKeyDistributionMessage = senderKeyDistributionMessage;
this.decryptionErrorMessage = Optional.absent();
}
private SignalServiceContent(SignalServiceReceiptMessage receiptMessage,
Optional<SenderKeyDistributionMessage> senderKeyDistributionMessage,
SignalServiceAddress sender,
int senderDevice,
long timestamp,
long serverReceivedTimestamp,
long serverDeliveredTimestamp,
boolean needsReceipt,
String serverUuid,
Optional<byte[]> groupId,
SignalServiceContentProto serializedState)
{
this.sender = sender;
this.senderDevice = senderDevice;
this.timestamp = timestamp;
this.serverReceivedTimestamp = serverReceivedTimestamp;
this.serverDeliveredTimestamp = serverDeliveredTimestamp;
this.needsReceipt = needsReceipt;
this.serverUuid = serverUuid;
this.groupId = groupId;
this.serializedState = serializedState;
this.message = Optional.absent();
this.synchronizeMessage = Optional.absent();
this.callMessage = Optional.absent();
this.readMessage = Optional.of(receiptMessage);
this.typingMessage = Optional.absent();
this.senderKeyDistributionMessage = senderKeyDistributionMessage;
this.decryptionErrorMessage = Optional.absent();
}
private SignalServiceContent(DecryptionErrorMessage errorMessage,
Optional<SenderKeyDistributionMessage> senderKeyDistributionMessage,
SignalServiceAddress sender,
int senderDevice,
long timestamp,
long serverReceivedTimestamp,
long serverDeliveredTimestamp,
boolean needsReceipt,
String serverUuid,
Optional<byte[]> groupId,
SignalServiceContentProto serializedState)
{
this.sender = sender;
this.senderDevice = senderDevice;
this.timestamp = timestamp;
this.serverReceivedTimestamp = serverReceivedTimestamp;
this.serverDeliveredTimestamp = serverDeliveredTimestamp;
this.needsReceipt = needsReceipt;
this.serverUuid = serverUuid;
this.groupId = groupId;
this.serializedState = serializedState;
this.message = Optional.absent();
this.synchronizeMessage = Optional.absent();
this.callMessage = Optional.absent();
this.readMessage = Optional.absent();
this.typingMessage = Optional.absent();
this.senderKeyDistributionMessage = senderKeyDistributionMessage;
this.decryptionErrorMessage = Optional.of(errorMessage);
}
private SignalServiceContent(SignalServiceTypingMessage typingMessage,
Optional<SenderKeyDistributionMessage> senderKeyDistributionMessage,
SignalServiceAddress sender,
int senderDevice,
long timestamp,
long serverReceivedTimestamp,
long serverDeliveredTimestamp,
boolean needsReceipt,
String serverUuid,
Optional<byte[]> groupId,
SignalServiceContentProto serializedState)
{
this.sender = sender;
this.senderDevice = senderDevice;
this.timestamp = timestamp;
this.serverReceivedTimestamp = serverReceivedTimestamp;
this.serverDeliveredTimestamp = serverDeliveredTimestamp;
this.needsReceipt = needsReceipt;
this.serverUuid = serverUuid;
this.groupId = groupId;
this.serializedState = serializedState;
this.message = Optional.absent();
this.synchronizeMessage = Optional.absent();
this.callMessage = Optional.absent();
this.readMessage = Optional.absent();
this.typingMessage = Optional.of(typingMessage);
this.senderKeyDistributionMessage = senderKeyDistributionMessage;
this.decryptionErrorMessage = Optional.absent();
}
private SignalServiceContent(SenderKeyDistributionMessage senderKeyDistributionMessage,
SignalServiceAddress sender,
int senderDevice,
long timestamp,
long serverReceivedTimestamp,
long serverDeliveredTimestamp,
boolean needsReceipt,
String serverUuid,
Optional<byte[]> groupId,
SignalServiceContentProto serializedState)
{
this.sender = sender;
this.senderDevice = senderDevice;
this.timestamp = timestamp;
this.serverReceivedTimestamp = serverReceivedTimestamp;
this.serverDeliveredTimestamp = serverDeliveredTimestamp;
this.needsReceipt = needsReceipt;
this.serverUuid = serverUuid;
this.groupId = groupId;
this.serializedState = serializedState;
this.message = Optional.absent();
this.synchronizeMessage = Optional.absent();
this.callMessage = Optional.absent();
this.readMessage = Optional.absent();
this.typingMessage = Optional.absent();
this.senderKeyDistributionMessage = Optional.of(senderKeyDistributionMessage);
this.decryptionErrorMessage = Optional.absent();
}
public Optional<SignalServiceDataMessage> getDataMessage() {
return message;
}
public Optional<SignalServiceSyncMessage> getSyncMessage() {
return synchronizeMessage;
}
public Optional<SignalServiceCallMessage> getCallMessage() {
return callMessage;
}
public Optional<SignalServiceReceiptMessage> getReceiptMessage() {
return readMessage;
}
public Optional<SignalServiceTypingMessage> getTypingMessage() {
return typingMessage;
}
public Optional<SenderKeyDistributionMessage> getSenderKeyDistributionMessage() {
return senderKeyDistributionMessage;
}
public Optional<DecryptionErrorMessage> getDecryptionErrorMessage() {
return decryptionErrorMessage;
}
public SignalServiceAddress getSender() {
return sender;
}
public int getSenderDevice() {
return senderDevice;
}
public long getTimestamp() {
return timestamp;
}
public long getServerReceivedTimestamp() {
return serverReceivedTimestamp;
}
public long getServerDeliveredTimestamp() {
return serverDeliveredTimestamp;
}
public boolean isNeedsReceipt() {
return needsReceipt;
}
public String getServerUuid() {
return serverUuid;
}
public Optional<byte[]> getGroupId() {
return groupId;
}
public byte[] serialize() {
return serializedState.toByteArray();
}
public static SignalServiceContent deserialize(byte[] data) {
try {
if (data == null) return null;
SignalServiceContentProto signalServiceContentProto = SignalServiceContentProto.parseFrom(data);
return createFromProto(signalServiceContentProto);
} catch (InvalidProtocolBufferException | ProtocolInvalidMessageException | ProtocolInvalidKeyException | UnsupportedDataMessageException | InvalidMessageStructureException e) {
// We do not expect any of these exceptions if this byte[] has come from serialize.
throw new AssertionError(e);
}
}
/**
* Takes internal protobuf serialization format and processes it into a {@link SignalServiceContent}.
*/
public static SignalServiceContent createFromProto(SignalServiceContentProto serviceContentProto)
throws ProtocolInvalidMessageException, ProtocolInvalidKeyException, UnsupportedDataMessageException, InvalidMessageStructureException
{
SignalServiceMetadata metadata = SignalServiceMetadataProtobufSerializer.fromProtobuf(serviceContentProto.getMetadata());
SignalServiceAddress localAddress = SignalServiceAddressProtobufSerializer.fromProtobuf(serviceContentProto.getLocalAddress());
if (serviceContentProto.getDataCase() == SignalServiceContentProto.DataCase.LEGACYDATAMESSAGE) {
SignalServiceProtos.DataMessage message = serviceContentProto.getLegacyDataMessage();
return new SignalServiceContent(createSignalServiceMessage(metadata, message),
Optional.absent(),
metadata.getSender(),
metadata.getSenderDevice(),
metadata.getTimestamp(),
metadata.getServerReceivedTimestamp(),
metadata.getServerDeliveredTimestamp(),
metadata.isNeedsReceipt(),
metadata.getServerGuid(),
metadata.getGroupId(),
serviceContentProto);
} else if (serviceContentProto.getDataCase() == SignalServiceContentProto.DataCase.CONTENT) {
SignalServiceProtos.Content message = serviceContentProto.getContent();
Optional<SenderKeyDistributionMessage> senderKeyDistributionMessage = Optional.absent();
if (message.hasSenderKeyDistributionMessage()) {
try {
senderKeyDistributionMessage = Optional.of(new SenderKeyDistributionMessage(message.getSenderKeyDistributionMessage().toByteArray()));
} catch (LegacyMessageException | InvalidMessageException e) {
Log.w(TAG, "Failed to parse SenderKeyDistributionMessage!", e);
}
}
if (message.hasDataMessage()) {
return new SignalServiceContent(createSignalServiceMessage(metadata, message.getDataMessage()),
senderKeyDistributionMessage,
metadata.getSender(),
metadata.getSenderDevice(),
metadata.getTimestamp(),
metadata.getServerReceivedTimestamp(),
metadata.getServerDeliveredTimestamp(),
metadata.isNeedsReceipt(),
metadata.getServerGuid(),
metadata.getGroupId(),
serviceContentProto);
} else if (message.hasSyncMessage() && localAddress.matches(metadata.getSender())) {
return new SignalServiceContent(createSynchronizeMessage(metadata, message.getSyncMessage()),
senderKeyDistributionMessage,
metadata.getSender(),
metadata.getSenderDevice(),
metadata.getTimestamp(),
metadata.getServerReceivedTimestamp(),
metadata.getServerDeliveredTimestamp(),
metadata.isNeedsReceipt(),
metadata.getServerGuid(),
metadata.getGroupId(),
serviceContentProto);
} else if (message.hasCallMessage()) {
return new SignalServiceContent(createCallMessage(message.getCallMessage()),
senderKeyDistributionMessage,
metadata.getSender(),
metadata.getSenderDevice(),
metadata.getTimestamp(),
metadata.getServerReceivedTimestamp(),
metadata.getServerDeliveredTimestamp(),
metadata.isNeedsReceipt(),
metadata.getServerGuid(),
metadata.getGroupId(),
serviceContentProto);
} else if (message.hasReceiptMessage()) {
return new SignalServiceContent(createReceiptMessage(metadata, message.getReceiptMessage()),
senderKeyDistributionMessage,
metadata.getSender(),
metadata.getSenderDevice(),
metadata.getTimestamp(),
metadata.getServerReceivedTimestamp(),
metadata.getServerDeliveredTimestamp(),
metadata.isNeedsReceipt(),
metadata.getServerGuid(),
metadata.getGroupId(),
serviceContentProto);
} else if (message.hasTypingMessage()) {
return new SignalServiceContent(createTypingMessage(metadata, message.getTypingMessage()),
senderKeyDistributionMessage,
metadata.getSender(),
metadata.getSenderDevice(),
metadata.getTimestamp(),
metadata.getServerReceivedTimestamp(),
metadata.getServerDeliveredTimestamp(),
false,
metadata.getServerGuid(),
metadata.getGroupId(),
serviceContentProto);
} else if (message.hasDecryptionErrorMessage()) {
return new SignalServiceContent(createDecryptionErrorMessage(metadata, message.getDecryptionErrorMessage()),
senderKeyDistributionMessage,
metadata.getSender(),
metadata.getSenderDevice(),
metadata.getTimestamp(),
metadata.getServerReceivedTimestamp(),
metadata.getServerDeliveredTimestamp(),
metadata.isNeedsReceipt(),
metadata.getServerGuid(),
metadata.getGroupId(),
serviceContentProto);
} else if (senderKeyDistributionMessage.isPresent()) {
return new SignalServiceContent(senderKeyDistributionMessage.get(),
metadata.getSender(),
metadata.getSenderDevice(),
metadata.getTimestamp(),
metadata.getServerReceivedTimestamp(),
metadata.getServerDeliveredTimestamp(),
false,
metadata.getServerGuid(),
metadata.getGroupId(),
serviceContentProto);
}
}
return null;
}
private static SignalServiceDataMessage createSignalServiceMessage(SignalServiceMetadata metadata,
SignalServiceProtos.DataMessage content)
throws UnsupportedDataMessageException, InvalidMessageStructureException
{
SignalServiceGroup groupInfoV1 = createGroupV1Info(content);
SignalServiceGroupV2 groupInfoV2 = createGroupV2Info(content);
Optional<SignalServiceGroupContext> groupContext;
try {
groupContext = SignalServiceGroupContext.createOptional(groupInfoV1, groupInfoV2);
} catch (InvalidMessageException e) {
throw new InvalidMessageStructureException(e);
}
List<SignalServiceAttachment> attachments = new LinkedList<>();
boolean endSession = ((content.getFlags() & SignalServiceProtos.DataMessage.Flags.END_SESSION_VALUE ) != 0);
boolean expirationUpdate = ((content.getFlags() & SignalServiceProtos.DataMessage.Flags.EXPIRATION_TIMER_UPDATE_VALUE) != 0);
boolean profileKeyUpdate = ((content.getFlags() & SignalServiceProtos.DataMessage.Flags.PROFILE_KEY_UPDATE_VALUE ) != 0);
boolean isGroupV2 = groupInfoV2 != null;
SignalServiceDataMessage.Quote quote = createQuote(content, isGroupV2);
List<SharedContact> sharedContacts = createSharedContacts(content);
List<SignalServiceDataMessage.Preview> previews = createPreviews(content);
List<SignalServiceDataMessage.Mention> mentions = createMentions(content.getBodyRangesList(), content.getBody(), isGroupV2);
SignalServiceDataMessage.Sticker sticker = createSticker(content);
SignalServiceDataMessage.Reaction reaction = createReaction(content);
SignalServiceDataMessage.RemoteDelete remoteDelete = createRemoteDelete(content);
SignalServiceDataMessage.GroupCallUpdate groupCallUpdate = createGroupCallUpdate(content);
if (content.getRequiredProtocolVersion() > SignalServiceProtos.DataMessage.ProtocolVersion.CURRENT_VALUE) {
throw new UnsupportedDataMessageProtocolVersionException(SignalServiceProtos.DataMessage.ProtocolVersion.CURRENT_VALUE,
content.getRequiredProtocolVersion(),
metadata.getSender().getIdentifier(),
metadata.getSenderDevice(),
groupContext);
}
SignalServiceDataMessage.Payment payment = createPayment(content);
if (content.getRequiredProtocolVersion() > SignalServiceProtos.DataMessage.ProtocolVersion.CURRENT.getNumber()) {
throw new UnsupportedDataMessageProtocolVersionException(SignalServiceProtos.DataMessage.ProtocolVersion.CURRENT.getNumber(),
content.getRequiredProtocolVersion(),
metadata.getSender().getIdentifier(),
metadata.getSenderDevice(),
groupContext);
}
for (SignalServiceProtos.AttachmentPointer pointer : content.getAttachmentsList()) {
attachments.add(createAttachmentPointer(pointer));
}
if (content.hasTimestamp() && content.getTimestamp() != metadata.getTimestamp()) {
throw new InvalidMessageStructureException("Timestamps don't match: " + content.getTimestamp() + " vs " + metadata.getTimestamp(),
metadata.getSender().getIdentifier(),
metadata.getSenderDevice());
}
return new SignalServiceDataMessage(metadata.getTimestamp(),
groupInfoV1, groupInfoV2,
attachments,
content.hasBody() ? content.getBody() : null,
endSession,
content.getExpireTimer(),
expirationUpdate,
content.hasProfileKey() ? content.getProfileKey().toByteArray() : null,
profileKeyUpdate,
quote,
sharedContacts,
previews,
mentions,
sticker,
content.getIsViewOnce(),
reaction,
remoteDelete,
groupCallUpdate,
payment);
}
private static SignalServiceSyncMessage createSynchronizeMessage(SignalServiceMetadata metadata,
SignalServiceProtos.SyncMessage content)
throws ProtocolInvalidKeyException, UnsupportedDataMessageException, InvalidMessageStructureException
{
if (content.hasSent()) {
Map<SignalServiceAddress, Boolean> unidentifiedStatuses = new HashMap<>();
SignalServiceProtos.SyncMessage.Sent sentContent = content.getSent();
SignalServiceDataMessage dataMessage = createSignalServiceMessage(metadata, sentContent.getMessage());
Optional<SignalServiceAddress> address = SignalServiceAddress.isValidAddress(sentContent.getDestinationUuid(), sentContent.getDestinationE164())
? Optional.of(new SignalServiceAddress(UuidUtil.parseOrNull(sentContent.getDestinationUuid()), sentContent.getDestinationE164()))
: Optional.<SignalServiceAddress>absent();
if (!address.isPresent() && !dataMessage.getGroupContext().isPresent()) {
throw new InvalidMessageStructureException("SyncMessage missing both destination and group ID!");
}
for (SignalServiceProtos.SyncMessage.Sent.UnidentifiedDeliveryStatus status : sentContent.getUnidentifiedStatusList()) {
if (SignalServiceAddress.isValidAddress(status.getDestinationUuid(), status.getDestinationE164())) {
SignalServiceAddress recipient = new SignalServiceAddress(UuidUtil.parseOrNull(status.getDestinationUuid()), status.getDestinationE164());
unidentifiedStatuses.put(recipient, status.getUnidentified());
} else {
Log.w(TAG, "Encountered an invalid UnidentifiedDeliveryStatus in a SentTranscript! Ignoring.");
}
}
return SignalServiceSyncMessage.forSentTranscript(new SentTranscriptMessage(address,
sentContent.getTimestamp(),
dataMessage,
sentContent.getExpirationStartTimestamp(),
unidentifiedStatuses,
sentContent.getIsRecipientUpdate()));
}
if (content.hasRequest()) {
return SignalServiceSyncMessage.forRequest(new RequestMessage(content.getRequest()));
}
if (content.getReadList().size() > 0) {
List<ReadMessage> readMessages = new LinkedList<>();
for (SignalServiceProtos.SyncMessage.Read read : content.getReadList()) {
if (SignalServiceAddress.isValidAddress(read.getSenderUuid(), read.getSenderE164())) {
SignalServiceAddress address = new SignalServiceAddress(UuidUtil.parseOrNull(read.getSenderUuid()), read.getSenderE164());
readMessages.add(new ReadMessage(address, read.getTimestamp()));
} else {
Log.w(TAG, "Encountered an invalid ReadMessage! Ignoring.");
}
}
return SignalServiceSyncMessage.forRead(readMessages);
}
if (content.getViewedList().size() > 0) {
List<ViewedMessage> viewedMessages = new LinkedList<>();
for (SignalServiceProtos.SyncMessage.Viewed viewed : content.getViewedList()) {
if (SignalServiceAddress.isValidAddress(viewed.getSenderUuid(), viewed.getSenderE164())) {
SignalServiceAddress address = new SignalServiceAddress(UuidUtil.parseOrNull(viewed.getSenderUuid()), viewed.getSenderE164());
viewedMessages.add(new ViewedMessage(address, viewed.getTimestamp()));
} else {
Log.w(TAG, "Encountered an invalid ReadMessage! Ignoring.");
}
}
return SignalServiceSyncMessage.forViewed(viewedMessages);
}
if (content.hasViewOnceOpen()) {
if (SignalServiceAddress.isValidAddress(content.getViewOnceOpen().getSenderUuid(), content.getViewOnceOpen().getSenderE164())) {
SignalServiceAddress address = new SignalServiceAddress(UuidUtil.parseOrNull(content.getViewOnceOpen().getSenderUuid()), content.getViewOnceOpen().getSenderE164());
ViewOnceOpenMessage timerRead = new ViewOnceOpenMessage(address, content.getViewOnceOpen().getTimestamp());
return SignalServiceSyncMessage.forViewOnceOpen(timerRead);
} else {
throw new InvalidMessageStructureException("ViewOnceOpen message has no sender!");
}
}
if (content.hasVerified()) {
if (SignalServiceAddress.isValidAddress(content.getVerified().getDestinationUuid(), content.getVerified().getDestinationE164())) {
try {
SignalServiceProtos.Verified verified = content.getVerified();
SignalServiceAddress destination = new SignalServiceAddress(UuidUtil.parseOrNull(verified.getDestinationUuid()), verified.getDestinationE164());
IdentityKey identityKey = new IdentityKey(verified.getIdentityKey().toByteArray(), 0);
VerifiedMessage.VerifiedState verifiedState;
if (verified.getState() == SignalServiceProtos.Verified.State.DEFAULT) {
verifiedState = VerifiedMessage.VerifiedState.DEFAULT;
} else if (verified.getState() == SignalServiceProtos.Verified.State.VERIFIED) {
verifiedState = VerifiedMessage.VerifiedState.VERIFIED;
} else if (verified.getState() == SignalServiceProtos.Verified.State.UNVERIFIED) {
verifiedState = VerifiedMessage.VerifiedState.UNVERIFIED;
} else {
throw new InvalidMessageStructureException("Unknown state: " + verified.getState().getNumber(),
metadata.getSender().getIdentifier(),
metadata.getSenderDevice());
}
return SignalServiceSyncMessage.forVerified(new VerifiedMessage(destination, identityKey, verifiedState, System.currentTimeMillis()));
} catch (InvalidKeyException e) {
throw new ProtocolInvalidKeyException(e, metadata.getSender().getIdentifier(), metadata.getSenderDevice());
}
} else {
throw new InvalidMessageStructureException("Verified message has no sender!");
}
}
if (content.getStickerPackOperationList().size() > 0) {
List<StickerPackOperationMessage> operations = new LinkedList<>();
for (SignalServiceProtos.SyncMessage.StickerPackOperation operation : content.getStickerPackOperationList()) {
byte[] packId = operation.hasPackId() ? operation.getPackId().toByteArray() : null;
byte[] packKey = operation.hasPackKey() ? operation.getPackKey().toByteArray() : null;
StickerPackOperationMessage.Type type = null;
if (operation.hasType()) {
switch (operation.getType()) {
case INSTALL: type = StickerPackOperationMessage.Type.INSTALL; break;
case REMOVE: type = StickerPackOperationMessage.Type.REMOVE; break;
}
}
operations.add(new StickerPackOperationMessage(packId, packKey, type));
}
return SignalServiceSyncMessage.forStickerPackOperations(operations);
}
if (content.hasBlocked()) {
List<String> numbers = content.getBlocked().getNumbersList();
List<String> uuids = content.getBlocked().getUuidsList();
List<SignalServiceAddress> addresses = new ArrayList<>(numbers.size() + uuids.size());
List<byte[]> groupIds = new ArrayList<>(content.getBlocked().getGroupIdsList().size());
for (String e164 : numbers) {
Optional<SignalServiceAddress> address = SignalServiceAddress.fromRaw(null, e164);
if (address.isPresent()) {
addresses.add(address.get());
}
}
for (String uuid : uuids) {
Optional<SignalServiceAddress> address = SignalServiceAddress.fromRaw(uuid, null);
if (address.isPresent()) {
addresses.add(address.get());
}
}
for (ByteString groupId : content.getBlocked().getGroupIdsList()) {
groupIds.add(groupId.toByteArray());
}
return SignalServiceSyncMessage.forBlocked(new BlockedListMessage(addresses, groupIds));
}
if (content.hasConfiguration()) {
Boolean readReceipts = content.getConfiguration().hasReadReceipts() ? content.getConfiguration().getReadReceipts() : null;
Boolean unidentifiedDeliveryIndicators = content.getConfiguration().hasUnidentifiedDeliveryIndicators() ? content.getConfiguration().getUnidentifiedDeliveryIndicators() : null;
Boolean typingIndicators = content.getConfiguration().hasTypingIndicators() ? content.getConfiguration().getTypingIndicators() : null;
Boolean linkPreviews = content.getConfiguration().hasLinkPreviews() ? content.getConfiguration().getLinkPreviews() : null;
return SignalServiceSyncMessage.forConfiguration(new ConfigurationMessage(Optional.fromNullable(readReceipts),
Optional.fromNullable(unidentifiedDeliveryIndicators),
Optional.fromNullable(typingIndicators),
Optional.fromNullable(linkPreviews)));
}
if (content.hasFetchLatest() && content.getFetchLatest().hasType()) {
switch (content.getFetchLatest().getType()) {
case LOCAL_PROFILE: return SignalServiceSyncMessage.forFetchLatest(SignalServiceSyncMessage.FetchType.LOCAL_PROFILE);
case STORAGE_MANIFEST: return SignalServiceSyncMessage.forFetchLatest(SignalServiceSyncMessage.FetchType.STORAGE_MANIFEST);
}
}
if (content.hasMessageRequestResponse()) {
MessageRequestResponseMessage.Type type;
switch (content.getMessageRequestResponse().getType()) {
case ACCEPT:
type = MessageRequestResponseMessage.Type.ACCEPT;
break;
case DELETE:
type = MessageRequestResponseMessage.Type.DELETE;
break;
case BLOCK:
type = MessageRequestResponseMessage.Type.BLOCK;
break;
case BLOCK_AND_DELETE:
type = MessageRequestResponseMessage.Type.BLOCK_AND_DELETE;
break;
default:
type = MessageRequestResponseMessage.Type.UNKNOWN;
break;
}
MessageRequestResponseMessage responseMessage;
if (content.getMessageRequestResponse().hasGroupId()) {
responseMessage = MessageRequestResponseMessage.forGroup(content.getMessageRequestResponse().getGroupId().toByteArray(), type);
} else {
Optional<SignalServiceAddress> address = SignalServiceAddress.fromRaw(content.getMessageRequestResponse().getThreadUuid(), content.getMessageRequestResponse().getThreadE164());
if (address.isPresent()) {
responseMessage = MessageRequestResponseMessage.forIndividual(address.get(), type);
} else {
throw new InvalidMessageStructureException("Message request response has an invalid thread identifier!");
}
}
return SignalServiceSyncMessage.forMessageRequestResponse(responseMessage);
}
if (content.hasOutgoingPayment()) {
SignalServiceProtos.SyncMessage.OutgoingPayment outgoingPayment = content.getOutgoingPayment();
switch (outgoingPayment.getPaymentDetailCase()) {
case MOBILECOIN: {
SignalServiceProtos.SyncMessage.OutgoingPayment.MobileCoin mobileCoin = outgoingPayment.getMobileCoin();
Money.MobileCoin amount = Money.picoMobileCoin(mobileCoin.getAmountPicoMob());
Money.MobileCoin fee = Money.picoMobileCoin(mobileCoin.getFeePicoMob());
ByteString address = mobileCoin.getRecipientAddress();
Optional<UUID> recipient = Optional.fromNullable(UuidUtil.parseOrNull(outgoingPayment.getRecipientUuid()));
return SignalServiceSyncMessage.forOutgoingPayment(new OutgoingPaymentMessage(recipient,
amount,
fee,
mobileCoin.getReceipt(),
mobileCoin.getLedgerBlockIndex(),
mobileCoin.getLedgerBlockTimestamp(),
address.isEmpty() ? Optional.absent() : Optional.of(address.toByteArray()),
Optional.of(outgoingPayment.getNote()),
mobileCoin.getOutputPublicKeysList(),
mobileCoin.getSpentKeyImagesList()));
}
default:
return SignalServiceSyncMessage.empty();
}
}
return SignalServiceSyncMessage.empty();
}
private static SignalServiceCallMessage createCallMessage(SignalServiceProtos.CallMessage content) {
boolean isMultiRing = content.getMultiRing();
Integer destinationDeviceId = content.hasDestinationDeviceId() ? content.getDestinationDeviceId() : null;
if (content.hasOffer()) {
SignalServiceProtos.CallMessage.Offer offerContent = content.getOffer();
return SignalServiceCallMessage.forOffer(new OfferMessage(offerContent.getId(), offerContent.hasSdp() ? offerContent.getSdp() : null, OfferMessage.Type.fromProto(offerContent.getType()), offerContent.hasOpaque() ? offerContent.getOpaque().toByteArray() : null), isMultiRing, destinationDeviceId);
} else if (content.hasAnswer()) {
SignalServiceProtos.CallMessage.Answer answerContent = content.getAnswer();
return SignalServiceCallMessage.forAnswer(new AnswerMessage(answerContent.getId(), answerContent.hasSdp() ? answerContent.getSdp() : null, answerContent.hasOpaque() ? answerContent.getOpaque().toByteArray() : null), isMultiRing, destinationDeviceId);
} else if (content.getIceUpdateCount() > 0) {
List<IceUpdateMessage> iceUpdates = new LinkedList<>();
for (SignalServiceProtos.CallMessage.IceUpdate iceUpdate : content.getIceUpdateList()) {
iceUpdates.add(new IceUpdateMessage(iceUpdate.getId(), iceUpdate.hasOpaque() ? iceUpdate.getOpaque().toByteArray() : null, iceUpdate.hasSdp() ? iceUpdate.getSdp() : null));
}
return SignalServiceCallMessage.forIceUpdates(iceUpdates, isMultiRing, destinationDeviceId);
} else if (content.hasLegacyHangup()) {
SignalServiceProtos.CallMessage.Hangup hangup = content.getLegacyHangup();
return SignalServiceCallMessage.forHangup(new HangupMessage(hangup.getId(), HangupMessage.Type.fromProto(hangup.getType()), hangup.getDeviceId(), content.hasLegacyHangup()), isMultiRing, destinationDeviceId);
} else if (content.hasHangup()) {
SignalServiceProtos.CallMessage.Hangup hangup = content.getHangup();
return SignalServiceCallMessage.forHangup(new HangupMessage(hangup.getId(), HangupMessage.Type.fromProto(hangup.getType()), hangup.getDeviceId(), content.hasLegacyHangup()), isMultiRing, destinationDeviceId);
} else if (content.hasBusy()) {
SignalServiceProtos.CallMessage.Busy busy = content.getBusy();
return SignalServiceCallMessage.forBusy(new BusyMessage(busy.getId()), isMultiRing, destinationDeviceId);
} else if (content.hasOpaque()) {
SignalServiceProtos.CallMessage.Opaque opaque = content.getOpaque();
return SignalServiceCallMessage.forOpaque(new OpaqueMessage(opaque.getData().toByteArray()), isMultiRing, destinationDeviceId);
}
return SignalServiceCallMessage.empty();
}
private static SignalServiceReceiptMessage createReceiptMessage(SignalServiceMetadata metadata, SignalServiceProtos.ReceiptMessage content) {
SignalServiceReceiptMessage.Type type;
if (content.getType() == SignalServiceProtos.ReceiptMessage.Type.DELIVERY) type = SignalServiceReceiptMessage.Type.DELIVERY;
else if (content.getType() == SignalServiceProtos.ReceiptMessage.Type.READ) type = SignalServiceReceiptMessage.Type.READ;
else if (content.getType() == SignalServiceProtos.ReceiptMessage.Type.VIEWED) type = SignalServiceReceiptMessage.Type.VIEWED;
else type = SignalServiceReceiptMessage.Type.UNKNOWN;
return new SignalServiceReceiptMessage(type, content.getTimestampList(), metadata.getTimestamp());
}
private static DecryptionErrorMessage createDecryptionErrorMessage(SignalServiceMetadata metadata, ByteString content) throws InvalidMessageStructureException {
try {
return new DecryptionErrorMessage(content.toByteArray());
} catch (InvalidMessageException e) {
throw new InvalidMessageStructureException(e, metadata.getSender().getIdentifier(), metadata.getSenderDevice());
}
}
private static SignalServiceTypingMessage createTypingMessage(SignalServiceMetadata metadata, SignalServiceProtos.TypingMessage content) throws InvalidMessageStructureException {
SignalServiceTypingMessage.Action action;
if (content.getAction() == SignalServiceProtos.TypingMessage.Action.STARTED) action = SignalServiceTypingMessage.Action.STARTED;
else if (content.getAction() == SignalServiceProtos.TypingMessage.Action.STOPPED) action = SignalServiceTypingMessage.Action.STOPPED;
else action = SignalServiceTypingMessage.Action.UNKNOWN;
if (content.hasTimestamp() && content.getTimestamp() != metadata.getTimestamp()) {
throw new InvalidMessageStructureException("Timestamps don't match: " + content.getTimestamp() + " vs " + metadata.getTimestamp(),
metadata.getSender().getIdentifier(),
metadata.getSenderDevice());
}
return new SignalServiceTypingMessage(action, content.getTimestamp(),
content.hasGroupId() ? Optional.of(content.getGroupId().toByteArray()) :
Optional.<byte[]>absent());
}
private static SignalServiceDataMessage.Quote createQuote(SignalServiceProtos.DataMessage content, boolean isGroupV2)
throws InvalidMessageStructureException
{
if (!content.hasQuote()) return null;
List<SignalServiceDataMessage.Quote.QuotedAttachment> attachments = new LinkedList<>();
for (SignalServiceProtos.DataMessage.Quote.QuotedAttachment attachment : content.getQuote().getAttachmentsList()) {
attachments.add(new SignalServiceDataMessage.Quote.QuotedAttachment(attachment.getContentType(),
attachment.getFileName(),
attachment.hasThumbnail() ? createAttachmentPointer(attachment.getThumbnail()) : null));
}
if (SignalServiceAddress.isValidAddress(content.getQuote().getAuthorUuid(), content.getQuote().getAuthorE164())) {
SignalServiceAddress address = new SignalServiceAddress(UuidUtil.parseOrNull(content.getQuote().getAuthorUuid()), content.getQuote().getAuthorE164());
return new SignalServiceDataMessage.Quote(content.getQuote().getId(),
address,
content.getQuote().getText(),
attachments,
createMentions(content.getQuote().getBodyRangesList(), content.getQuote().getText(), isGroupV2));
} else {
Log.w(TAG, "Quote was missing an author! Returning null.");
return null;
}
}
private static List<SignalServiceDataMessage.Preview> createPreviews(SignalServiceProtos.DataMessage content) throws InvalidMessageStructureException {
if (content.getPreviewCount() <= 0) return null;
List<SignalServiceDataMessage.Preview> results = new LinkedList<>();
for (SignalServiceProtos.DataMessage.Preview preview : content.getPreviewList()) {
SignalServiceAttachment attachment = null;
if (preview.hasImage()) {
attachment = createAttachmentPointer(preview.getImage());
}
results.add(new SignalServiceDataMessage.Preview(preview.getUrl(),
preview.getTitle(),
preview.getDescription(),
preview.getDate(),
Optional.fromNullable(attachment)));
}
return results;
}
private static List<SignalServiceDataMessage.Mention> createMentions(List<SignalServiceProtos.DataMessage.BodyRange> bodyRanges, String body, boolean isGroupV2)
throws InvalidMessageStructureException
{
if (bodyRanges == null || bodyRanges.isEmpty() || body == null) {
return null;
}
List<SignalServiceDataMessage.Mention> mentions = new LinkedList<>();
for (SignalServiceProtos.DataMessage.BodyRange bodyRange : bodyRanges) {
if (bodyRange.hasMentionUuid()) {
try {
mentions.add(new SignalServiceDataMessage.Mention(UuidUtil.parseOrThrow(bodyRange.getMentionUuid()), bodyRange.getStart(), bodyRange.getLength()));
} catch (IllegalArgumentException e) {
throw new InvalidMessageStructureException("Invalid body range!");
}
}
}
if (mentions.size() > 0 && !isGroupV2) {
throw new InvalidMessageStructureException("Mentions received in non-GV2 message");
}
return mentions;
}
private static SignalServiceDataMessage.Sticker createSticker(SignalServiceProtos.DataMessage content) throws InvalidMessageStructureException {
if (!content.hasSticker() ||
!content.getSticker().hasPackId() ||
!content.getSticker().hasPackKey() ||
!content.getSticker().hasStickerId() ||
!content.getSticker().hasData())
{
return null;
}
SignalServiceProtos.DataMessage.Sticker sticker = content.getSticker();
return new SignalServiceDataMessage.Sticker(sticker.getPackId().toByteArray(),
sticker.getPackKey().toByteArray(),
sticker.getStickerId(),
sticker.getEmoji(),
createAttachmentPointer(sticker.getData()));
}
private static SignalServiceDataMessage.Reaction createReaction(SignalServiceProtos.DataMessage content) {
if (!content.hasReaction() ||
!content.getReaction().hasEmoji() ||
!content.getReaction().hasTargetAuthorUuid() ||
!content.getReaction().hasTargetSentTimestamp())
{
return null;
}
SignalServiceProtos.DataMessage.Reaction reaction = content.getReaction();
UUID uuid = UuidUtil.parseOrNull(reaction.getTargetAuthorUuid());
if (uuid == null) {
Log.w(TAG, "Cannot parse author UUID on reaction");
return null;
}
return new SignalServiceDataMessage.Reaction(reaction.getEmoji(),
reaction.getRemove(),
new SignalServiceAddress(uuid),
reaction.getTargetSentTimestamp());
}
private static SignalServiceDataMessage.RemoteDelete createRemoteDelete(SignalServiceProtos.DataMessage content) {
if (!content.hasDelete() || !content.getDelete().hasTargetSentTimestamp()) {
return null;
}
SignalServiceProtos.DataMessage.Delete delete = content.getDelete();
return new SignalServiceDataMessage.RemoteDelete(delete.getTargetSentTimestamp());
}
private static SignalServiceDataMessage.GroupCallUpdate createGroupCallUpdate(SignalServiceProtos.DataMessage content) {
if (!content.hasGroupCallUpdate()) {
return null;
}
SignalServiceProtos.DataMessage.GroupCallUpdate groupCallUpdate = content.getGroupCallUpdate();
return new SignalServiceDataMessage.GroupCallUpdate(groupCallUpdate.getEraId());
}
private static SignalServiceDataMessage.Payment createPayment(SignalServiceProtos.DataMessage content) throws InvalidMessageStructureException {
if (!content.hasPayment()) {
return null;
}
SignalServiceProtos.DataMessage.Payment payment = content.getPayment();
switch (payment.getItemCase()) {
case NOTIFICATION: return new SignalServiceDataMessage.Payment(createPaymentNotification(payment));
default : throw new InvalidMessageStructureException("Unknown payment item");
}
}
private static SignalServiceDataMessage.PaymentNotification createPaymentNotification(SignalServiceProtos.DataMessage.Payment content)
throws InvalidMessageStructureException
{
if (!content.hasNotification() ||
content.getNotification().getTransactionCase() != SignalServiceProtos.DataMessage.Payment.Notification.TransactionCase.MOBILECOIN)
{
throw new InvalidMessageStructureException("Badly-formatted payment notification!");
}
SignalServiceProtos.DataMessage.Payment.Notification payment = content.getNotification();
return new SignalServiceDataMessage.PaymentNotification(payment.getMobileCoin().getReceipt().toByteArray(), payment.getNote());
}
private static List<SharedContact> createSharedContacts(SignalServiceProtos.DataMessage content) throws InvalidMessageStructureException {
if (content.getContactCount() <= 0) return null;
List<SharedContact> results = new LinkedList<>();
for (SignalServiceProtos.DataMessage.Contact contact : content.getContactList()) {
SharedContact.Builder builder = SharedContact.newBuilder()
.setName(SharedContact.Name.newBuilder()
.setDisplay(contact.getName().getDisplayName())
.setFamily(contact.getName().getFamilyName())
.setGiven(contact.getName().getGivenName())
.setMiddle(contact.getName().getMiddleName())
.setPrefix(contact.getName().getPrefix())
.setSuffix(contact.getName().getSuffix())
.build());
if (contact.getAddressCount() > 0) {
for (SignalServiceProtos.DataMessage.Contact.PostalAddress address : contact.getAddressList()) {
SharedContact.PostalAddress.Type type = SharedContact.PostalAddress.Type.HOME;
switch (address.getType()) {
case WORK: type = SharedContact.PostalAddress.Type.WORK; break;
case HOME: type = SharedContact.PostalAddress.Type.HOME; break;
case CUSTOM: type = SharedContact.PostalAddress.Type.CUSTOM; break;
}
builder.withAddress(SharedContact.PostalAddress.newBuilder()
.setCity(address.getCity())
.setCountry(address.getCountry())
.setLabel(address.getLabel())
.setNeighborhood(address.getNeighborhood())
.setPobox(address.getPobox())
.setPostcode(address.getPostcode())
.setRegion(address.getRegion())
.setStreet(address.getStreet())
.setType(type)
.build());
}
}
if (contact.getNumberCount() > 0) {
for (SignalServiceProtos.DataMessage.Contact.Phone phone : contact.getNumberList()) {
SharedContact.Phone.Type type = SharedContact.Phone.Type.HOME;
switch (phone.getType()) {
case HOME: type = SharedContact.Phone.Type.HOME; break;
case WORK: type = SharedContact.Phone.Type.WORK; break;
case MOBILE: type = SharedContact.Phone.Type.MOBILE; break;
case CUSTOM: type = SharedContact.Phone.Type.CUSTOM; break;
}
builder.withPhone(SharedContact.Phone.newBuilder()
.setLabel(phone.getLabel())
.setType(type)
.setValue(phone.getValue())
.build());
}
}
if (contact.getEmailCount() > 0) {
for (SignalServiceProtos.DataMessage.Contact.Email email : contact.getEmailList()) {
SharedContact.Email.Type type = SharedContact.Email.Type.HOME;
switch (email.getType()) {
case HOME: type = SharedContact.Email.Type.HOME; break;
case WORK: type = SharedContact.Email.Type.WORK; break;
case MOBILE: type = SharedContact.Email.Type.MOBILE; break;
case CUSTOM: type = SharedContact.Email.Type.CUSTOM; break;
}
builder.withEmail(SharedContact.Email.newBuilder()
.setLabel(email.getLabel())
.setType(type)
.setValue(email.getValue())
.build());
}
}
if (contact.hasAvatar()) {
builder.setAvatar(SharedContact.Avatar.newBuilder()
.withAttachment(createAttachmentPointer(contact.getAvatar().getAvatar()))
.withProfileFlag(contact.getAvatar().getIsProfile())
.build());
}
if (contact.hasOrganization()) {
builder.withOrganization(contact.getOrganization());
}
results.add(builder.build());
}
return results;
}
private static SignalServiceAttachmentPointer createAttachmentPointer(SignalServiceProtos.AttachmentPointer pointer) throws InvalidMessageStructureException {
return new SignalServiceAttachmentPointer(pointer.getCdnNumber(),
SignalServiceAttachmentRemoteId.from(pointer),
pointer.getContentType(),
pointer.getKey().toByteArray(),
pointer.hasSize() ? Optional.of(pointer.getSize()) : Optional.<Integer>absent(),
pointer.hasThumbnail() ? Optional.of(pointer.getThumbnail().toByteArray()): Optional.<byte[]>absent(),
pointer.getWidth(), pointer.getHeight(),
pointer.hasDigest() ? Optional.of(pointer.getDigest().toByteArray()) : Optional.<byte[]>absent(),
pointer.hasFileName() ? Optional.of(pointer.getFileName()) : Optional.<String>absent(),
(pointer.getFlags() & FlagUtil.toBinaryFlag(SignalServiceProtos.AttachmentPointer.Flags.VOICE_MESSAGE_VALUE)) != 0,
(pointer.getFlags() & FlagUtil.toBinaryFlag(SignalServiceProtos.AttachmentPointer.Flags.BORDERLESS_VALUE)) != 0,
(pointer.getFlags() & FlagUtil.toBinaryFlag(SignalServiceProtos.AttachmentPointer.Flags.GIF_VALUE)) != 0,
pointer.hasCaption() ? Optional.of(pointer.getCaption()) : Optional.<String>absent(),
pointer.hasBlurHash() ? Optional.of(pointer.getBlurHash()) : Optional.<String>absent(),
pointer.hasUploadTimestamp() ? pointer.getUploadTimestamp() : 0);
}
private static SignalServiceGroup createGroupV1Info(SignalServiceProtos.DataMessage content) throws InvalidMessageStructureException {
if (!content.hasGroup()) return null;
SignalServiceGroup.Type type;
switch (content.getGroup().getType()) {
case DELIVER: type = SignalServiceGroup.Type.DELIVER; break;
case UPDATE: type = SignalServiceGroup.Type.UPDATE; break;
case QUIT: type = SignalServiceGroup.Type.QUIT; break;
case REQUEST_INFO: type = SignalServiceGroup.Type.REQUEST_INFO; break;
default: type = SignalServiceGroup.Type.UNKNOWN; break;
}
if (content.getGroup().getType() != DELIVER) {
String name = null;
List<SignalServiceAddress> members = null;
SignalServiceAttachmentPointer avatar = null;
if (content.getGroup().hasName()) {
name = content.getGroup().getName();
}
if (content.getGroup().getMembersCount() > 0) {
members = new ArrayList<>(content.getGroup().getMembersCount());
for (SignalServiceProtos.GroupContext.Member member : content.getGroup().getMembersList()) {
if (SignalServiceAddress.isValidAddress(null, member.getE164())) {
members.add(new SignalServiceAddress(null, member.getE164()));
} else {
throw new InvalidMessageStructureException("GroupContext.Member had no address!");
}
}
} else if (content.getGroup().getMembersE164Count() > 0) {
members = new ArrayList<>(content.getGroup().getMembersE164Count());
for (String member : content.getGroup().getMembersE164List()) {
members.add(new SignalServiceAddress(null, member));
}
}
if (content.getGroup().hasAvatar()) {
SignalServiceProtos.AttachmentPointer pointer = content.getGroup().getAvatar();
avatar = new SignalServiceAttachmentPointer(pointer.getCdnNumber(),
SignalServiceAttachmentRemoteId.from(pointer),
pointer.getContentType(),
pointer.getKey().toByteArray(),
Optional.of(pointer.getSize()),
Optional.<byte[]>absent(), 0, 0,
Optional.fromNullable(pointer.hasDigest() ? pointer.getDigest().toByteArray() : null),
Optional.<String>absent(),
false,
false,
false,
Optional.<String>absent(),
Optional.<String>absent(),
pointer.hasUploadTimestamp() ? pointer.getUploadTimestamp() : 0);
}
return new SignalServiceGroup(type, content.getGroup().getId().toByteArray(), name, members, avatar);
}
return new SignalServiceGroup(content.getGroup().getId().toByteArray());
}
private static SignalServiceGroupV2 createGroupV2Info(SignalServiceProtos.DataMessage content) throws InvalidMessageStructureException {
if (!content.hasGroupV2()) return null;
SignalServiceProtos.GroupContextV2 groupV2 = content.getGroupV2();
if (!groupV2.hasMasterKey()) {
throw new InvalidMessageStructureException("No GV2 master key on message");
}
if (!groupV2.hasRevision()) {
throw new InvalidMessageStructureException("No GV2 revision on message");
}
SignalServiceGroupV2.Builder builder;
try {
builder = SignalServiceGroupV2.newBuilder(new GroupMasterKey(groupV2.getMasterKey().toByteArray()))
.withRevision(groupV2.getRevision());
} catch (InvalidInputException e) {
throw new InvalidMessageStructureException("Invalid GV2 input!");
}
if (groupV2.hasGroupChange() && !groupV2.getGroupChange().isEmpty()) {
builder.withSignedGroupChange(groupV2.getGroupChange().toByteArray());
}
return builder.build();
}
}
| gpl-3.0 |
lrleon/Aleph-w | tpl_tree_node.H | 35892 | /*
This file is part of Aleph-w library
Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018
Leandro Rabindranath Leon / Alejandro Mujica
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
<https://www.gnu.org/licenses/>.
*/
# ifndef TPL_TREE_H
# define TPL_TREE_H
# include <stdexcept>
# include <dlink.H>
# include <ahDry.H>
# include <ahIterator.H>
# include <ahFunction.H>
# include <ahFunctional.H>
# include <htlist.H>
# include <tpl_dynListStack.H>
# include <tpl_dynListQueue.H>
# include <tpl_binNode.H>
# define ISROOT(p) ((p)->is_root())
# define ISLEAF(p) ((p)->is_leaf())
# define ISLEFTMOST(p) ((p)->is_leftmost())
# define ISRIGHTMOST(p) ((p)->is_rightmost())
# define SIBLING_LIST(p) ((p)->get_sibling_list())
# define CHILD_LIST(p) ((p)->get_child_list())
# define SIBLING_LINK(p) ((p)->get_sibling_list())
# define LCHILD(p) ((p)->get_left_child())
# define RSIBLING(p) ((p)->get_right_sibling())
# define IS_UNIQUE_SIBLING(p) (RSIBLING(p) == (p))
namespace Aleph
{
/** Árboles m-rios genéricos.
La clase Tree_Node<Key> define árboles generales de cualquier
orden representados mediante listas enlazadas.
@param Key el tipo de dato que contiene cada nodo del árbol.
@ingroup Arboles
*/
template <class T>
class Tree_Node
{
T data;
Dlink child;
Dlink sibling;
struct Flags
{
unsigned int is_root : 1;
unsigned int is_leaf : 1;
unsigned int is_leftmost : 1;
unsigned int is_rightmost : 1;
Flags() noexcept
: is_root(1), is_leaf(1), is_leftmost(1), is_rightmost(1) {}
};
Flags flags;
LINKNAME_TO_TYPE(Tree_Node, child);
LINKNAME_TO_TYPE(Tree_Node, sibling);
Tree_Node * upper_link() const noexcept
{
return child_to_Tree_Node(child.get_prev());
}
Tree_Node * lower_link() const noexcept
{
return child_to_Tree_Node(child.get_next());
}
Tree_Node * left_link() const noexcept
{
return sibling_to_Tree_Node(sibling.get_prev());
}
Tree_Node * right_link() const noexcept
{
return sibling_to_Tree_Node(sibling.get_next());
}
public:
using Item_Type = Tree_Node*;
/// retorna referencia modificable al contenido del nodo.
T & get_key() noexcept { return get_data(); }
const T & get_key() const noexcept { return get_data(); }
/// retorna referencia modificable al contenido del nodo.
T & get_data() noexcept { return data; }
const T & get_data() const noexcept { return data; }
/// Tipo de dato genérico que contiene el nodo.
using key_type = T;
Dlink * get_child_list() noexcept { return &child; }
Dlink * get_sibling_list() noexcept { return &sibling; }
/// Retorna true si this es la raíz del árbol general.
bool is_root() const noexcept { return flags.is_root; }
/// Retorna true si this es un nodo hoja.
bool is_leaf() const noexcept { return flags.is_leaf; }
/// Retorna true si this es el nodo más a la izquierda de sus hermanos.
bool is_leftmost() const noexcept { return flags.is_leftmost; }
/// Retorna true si this es el nodo más a la derecha de sus hermanos.
bool is_rightmost() const noexcept { return flags.is_rightmost; }
void set_is_root(bool value) noexcept { flags.is_root = value; }
void set_is_leaf(bool value) noexcept { flags.is_leaf = value; }
void set_is_leftmost(bool value) noexcept { flags.is_leftmost = value; }
void set_is_rightmost(bool value) noexcept { flags.is_rightmost = value; }
/// Constructor vacío (clave indefinida).
Tree_Node() noexcept { /* empty */ }
/// Constructor con valor de dato __data
Tree_Node(const T & __data)
noexcept(std::is_nothrow_copy_constructible<T>::value)
: data(__data) { /* empty */ }
Tree_Node(T && __data)
noexcept(std::is_nothrow_move_constructible<T>::value)
: data(std::move(__data)) { /* empty */ }
/// Retorna hermano izquierdo de this.
Tree_Node * get_left_sibling() const noexcept
{
if (is_leftmost())
return nullptr;
return left_link();
}
/// Retorna hermano derecho de this.
Tree_Node * get_right_sibling() const noexcept
{
if (is_rightmost())
return nullptr;
return right_link();
}
/// retorna el hijo más a la izquierda de this.
Tree_Node * get_left_child() const noexcept
{
if (is_leaf())
return nullptr;
return lower_link();
}
/// retorna el hijo más a la derecha de this.
Tree_Node * get_right_child() const noexcept
{
if (is_leaf())
return nullptr;
Tree_Node * left_child = lower_link();
assert(ISLEFTMOST(left_child));
return left_child->left_link();
}
/** Retorna el i-ésimo hijo de this.
Retorna el i-ésimo hijo de this.
@param[in] i ordinal del hijo al que se desea acceder.
@return puntero al i-ésimo hijo de this; nullptr si no existe.
*/
Tree_Node * get_child(const size_t i) const noexcept
{
Tree_Node * c = get_left_child();
for (int j = 0; c != nullptr and j < i; ++j)
c = c->get_right_sibling();
return c;
}
/// Retorna el padre de this.
Tree_Node * get_parent() const noexcept
{
if (is_root())
return nullptr;
Tree_Node * p = const_cast<Tree_Node*>(this);
while (not ISLEFTMOST(p)) // baje hasta el nodo más a la izquierda
p = p->left_link();
assert(not ISROOT(p));
assert(not CHILD_LIST(p)->is_empty());
return p->upper_link();
}
/** Inserta p como hermano derecho de this.
Inserta p como hermano derecho de this.
@param[in] p nodo a insertar como hermano derecho.
*/
void insert_right_sibling(Tree_Node * p) noexcept
{
if (p == nullptr)
return;
assert(CHILD_LIST(p)->is_empty());
assert(SIBLING_LIST(p)->is_empty());
assert(p->is_rightmost() and p->is_leftmost() and p->is_root() and
p->is_leaf());
p->set_is_root(false);
p->set_is_leftmost(false);
Tree_Node * old_next_node = get_right_sibling();
if (old_next_node != nullptr)
{
assert(not this->is_rightmost());
p->set_is_rightmost(false);
}
else
{
assert(this->is_rightmost());
p->set_is_rightmost(true);
}
this->set_is_rightmost(false);
this->sibling.insert(SIBLING_LIST(p));
}
/** Inserta p como hermano izquierdo de this.
Inserta p como hermano izquierdo de this.
@param[in] p nodo a insertar como hermano izquierdo.
*/
void insert_left_sibling(Tree_Node * p)
{
if (p == nullptr)
return;
if (this->is_root())
throw std::domain_error("Cannot insert sibling of a root");
assert(CHILD_LIST(p)->is_empty());
assert(SIBLING_LIST(p)->is_empty());
assert(p->is_rightmost() and p->is_leftmost() and p->is_root() and
p->is_leaf());
p->set_is_root(false);
p->set_is_rightmost(false);
Tree_Node * old_prev_node = this->get_left_sibling();
if (old_prev_node != nullptr)
{
assert(not this->is_leftmost());
p->set_is_leftmost(false);
}
else
{ // this es más a la izq ==> p debe a ser primogénito
assert(this->is_leftmost());
Tree_Node * parent = this->get_parent();
// Busca la raíz del árbol. Para ello buscamnos la hoja de this
Tree_Node * leaf = this;
while (not leaf->is_leaf())
{
leaf = leaf->get_left_child();
assert(leaf != nullptr);
}
Tree_Node * root = leaf->lower_link();
assert(root != nullptr);
Dlink tree = CHILD_LIST(root)->cut_list(CHILD_LIST(this));
tree.del();
CHILD_LIST(parent)->insert(CHILD_LIST(p));
p->set_is_leftmost(true);
assert(p->get_parent() == parent);
}
this->set_is_leftmost(false);
this->sibling.append(SIBLING_LIST(p));
}
/** Inserta p como el hijo más a la izquierda de this.
Inserta p como el hijo más a la izquierda de this.
@param[in] p nodo a insertar.
*/
void insert_leftmost_child(Tree_Node * p) noexcept
{
if (p == nullptr)
return;
assert(CHILD_LIST(p)->is_empty());
assert(SIBLING_LIST(p)->is_empty());
assert(p->is_rightmost() and p->is_leftmost() and p->is_root() and
p->is_leaf());
p->set_is_root(false);
if (this->is_leaf())
{
this->set_is_leaf(false);
CHILD_LIST(this)->insert(CHILD_LIST(p));
}
else
{
Tree_Node * old_left_child = this->lower_link();
Tree_Node * leaf = old_left_child;
while (not leaf->is_leaf())
leaf = leaf->get_left_child();
Tree_Node * root = leaf->lower_link();
Dlink subtree = CHILD_LIST(root)->cut_list(CHILD_LIST(old_left_child));
subtree.del();
CHILD_LIST(this)->insert(CHILD_LIST(p));
SIBLING_LIST(old_left_child)->append(SIBLING_LIST(p));
old_left_child->set_is_leftmost(false);
p->set_is_rightmost(false);
assert(p->get_right_sibling() == old_left_child);
assert(old_left_child->get_left_sibling() == p);
}
assert(p->is_leftmost());
}
/** Inserta p como el hijo más a la derecho de this.
Inserta p como el hijo más a la derecho de this.
@param[in] p nodo a insertar.
*/
void insert_rightmost_child(Tree_Node * p) noexcept
{
if (p == nullptr)
return;
assert(CHILD_LIST(p)->is_empty());
assert(SIBLING_LIST(p)->is_empty());
assert(p->is_rightmost() and p->is_leftmost() and p->is_root() and
p->is_leaf());
p->set_is_root(false);
if (this->is_leaf())
{
this->set_is_leaf(false);
CHILD_LIST(this)->insert(CHILD_LIST(p));
}
else
{
Tree_Node * old_right_child_node = this->lower_link()->left_link();
old_right_child_node->set_is_rightmost(false);
p->set_is_leftmost(false);
SIBLING_LIST(old_right_child_node)->insert(SIBLING_LIST(p));
}
}
/// join `tree` as subtree of root `this`
Tree_Node * join(Tree_Node * tree)
{
assert(this->is_root());
assert(tree != nullptr);
assert(tree->is_root() and tree->is_leftmost() and tree->is_rightmost());
tree->set_is_root(false);
if (this->is_leaf())
{
assert(CHILD_LIST(this)->is_empty() and SIBLING_LIST(this)->is_empty());
this->set_is_leaf(false);
CHILD_LIST(this)->splice(CHILD_LIST(tree));
}
else
{
Tree_Node * right_child = this->lower_link()->left_link();
right_child->set_is_rightmost(false);
tree->set_is_leftmost(false);
SIBLING_LINK(right_child)->splice(SIBLING_LINK(tree));
}
return this;
}
/** Insert `tree` to the right of `this`
Assuming that `this` is part of a forrest, this method
insert `tree` to the right of this.
Be careful with the fact that `tree` will not always be
inserted as the rightmost tree, but as the tree to right of
`this`.
@param[in] tree the tree to insert
@throw domain_error if tree is not root
*/
void insert_tree_to_right(Tree_Node * tree)
{
if (tree == nullptr)
return;
if (not this->is_root())
throw std::domain_error("\"this\" is not root");
tree->set_is_leftmost(false);
Tree_Node * old_next_tree = this->get_right_tree();
if (old_next_tree != nullptr)
{
assert(not this->is_rightmost());
tree->set_is_rightmost(false);
}
this->set_is_rightmost(false);
SIBLING_LIST(this)->insert(SIBLING_LIST(tree));
}
/// Retorna el árbol a la izquierda de this.
Tree_Node * get_left_tree() const noexcept
{
if (is_leftmost())
return nullptr;
assert(not is_leftmost());
return left_link();
}
/// Retorna el árbol a la derecha de this.
Tree_Node * get_right_tree() const noexcept
{
if (is_rightmost())
return nullptr;
assert(not is_rightmost());
return right_link();
}
/// Retorna el árbol más a la derecha de la arborescencia
/// this. Dispara excepción range_error si this no es el árbol más a
/// la izquierda de toda la arborescencia.
Tree_Node * get_last_tree() const
{
if (not is_leftmost())
throw std::range_error("\"this\" is not the leftmost tree in the forest");
return left_link();
}
/// Return a list with all trees belonging to the forrest
template <template <typename> class Container = DynList>
Container<Tree_Node*> trees() const
{
Container<Tree_Node*> ret;
for (auto t = const_cast<Tree_Node*>(this); t != nullptr;
t = t->get_right_tree())
ret.append(t);
return ret;
}
/// Visita cada hijo de this y ejecuta la operación operation sobre el
/// nodo hijo
template <typename Operation>
void for_each_child(Operation & op) const
{
for (Tree_Node * child = get_left_child(); child != nullptr;
child = child->get_right_sibling())
op(child);
}
template <typename Operation>
void for_each_child(Operation && op = Operation()) const
{
for_each_child<Operation>(op);
}
/// Retorna una lista de los nodos hijos de this
template <template <typename> class Container = DynList>
Container<Tree_Node*> children_nodes() const
{
Container<Tree_Node*> ret_val;
this->for_each_child([&ret_val] (Tree_Node * p) { ret_val.append(p); });
return ret_val;
}
/// Retorna una lista de los contenidos de los hijos de this.
template <template <typename> class Container = DynList>
Container<T> children() const
{
Container<T> ret_val;
this->for_each_child([&ret_val] (Tree_Node * p)
{
ret_val.append(p->get_key());
});
return ret_val;
}
private:
template <class Operation> static
bool preorder(const Tree_Node * root, Operation & op)
{
if (root == nullptr)
return true;
if (not op(root))
return false;
for (Tree_Node * child = root->get_left_child(); child != nullptr;
child = child->get_right_sibling())
if (not preorder(child, op))
return false;
return true;
}
public:
/// Recorre en prefijo todos los nodos y ejecuta op
template <class Operation>
bool traverse(Operation op)
{
return preorder(this, op);
}
template <class Operation>
bool traverse(Operation op) const
{
return const_cast<Tree_Node*>(this)->traverse(op);
}
template <class Op> bool level_traverse(Op op)
{
DynListQueue<Tree_Node*> q;
q.put(this);
while (not q.is_empty())
{
Tree_Node * p = q.get();
if (not op(p))
return false;
p->for_each_child([&q] (auto cptr) { q.put(cptr); });
}
return false;
}
template <class Op> bool level_traverse(Op op) const
{
return const_cast<Tree_Node*>(this)->level_traverse(op);
}
Functional_Methods(Tree_Node*);
/** Iterator sobre los hijos de this
*/
class Children_Iterator
{
Tree_Node * curr = nullptr;
public:
Children_Iterator(const Tree_Node & p) noexcept
: curr(p.get_left_child()) {}
Children_Iterator(Tree_Node & p) noexcept
: curr(p.get_left_child()) {}
Children_Iterator(Tree_Node * p) noexcept
: curr(p->get_left_child()) {}
Children_Iterator(const Children_Iterator & it) noexcept
: curr(const_cast<Children_Iterator&>(it).curr) {}
bool has_curr() const noexcept { return curr != nullptr; }
Tree_Node * get_curr() const
{
if (curr == nullptr)
throw std::overflow_error("Children_Iterator::get_curr()");
return curr;
}
void next()
{
if (curr == nullptr)
throw std::overflow_error("Children_Iterator::next()");
curr = curr->get_right_sibling();
}
};
Children_Iterator children_it() const
{
return Children_Iterator(*this);
}
struct Children_Set // truco para usar Pair_Iterator
{
Children_Set(const Tree_Node &&) {}
Children_Set(const Tree_Node &) {}
struct Iterator : public Children_Iterator
{
using Children_Iterator::Children_Iterator;
};
};
class Iterator
{
Tree_Node * root = nullptr;
Tree_Node * curr = nullptr;
long pos = 0;
DynListStack<Tree_Node*> s;
public:
using Item_Type = Tree_Node*;
void swap(Iterator & it)
{
std::swap(root, it.root);
std::swap(curr, it.curr);
std::swap(pos, it.pos);
s.swap(it.s);
}
Iterator(Tree_Node * __root = nullptr) noexcept
: root(__root), curr(root)
{
// empty
}
Iterator(Tree_Node & root) : Iterator(&root) {}
Iterator(const Iterator & it)
: root(it.root), curr(it.curr), pos(it.pos), s(it.s)
{
// empty
}
Iterator(Iterator && it) { swap(it); }
Iterator & operator = (const Iterator & it)
{
if (this == &it)
return *this;
root = it.root;
curr = it.curr;
pos = it.pos;
s = it.s;
return *this;
}
Iterator & operator = (Iterator && it)
{
swap(it);
return *this;
}
void reset_first() noexcept
{
s.empty();
curr = root;
}
bool has_curr() const noexcept { return curr != nullptr; }
bool has_current() const noexcept { return has_curr(); }
Tree_Node * get_curr() const
{
if (not has_curr())
throw std::overflow_error("Iterator overflow");
return curr;
}
auto get_current() const { return get_curr(); }
void next()
{
if (not has_curr())
throw std::overflow_error("Iterator overflow");
++pos;
Tree_Node * lchild = curr->get_left_child();
if (lchild == nullptr)
{
if (s.is_empty())
curr = nullptr;
else
curr = s.pop();
return;
}
for (auto p = curr->get_right_child(); p != lchild;
p = p->get_left_sibling())
s.push(p);
curr = lchild;
}
void end()
{
curr = nullptr;
s.empty();
pos = -1;
}
/// Return the current position of iterator. Only valid if
// has_curr() == true
size_t get_pos() const { return pos; }
};
Iterator get_it() const
{
return Iterator(const_cast<Tree_Node*>(this));
}
STL_ALEPH_ITERATOR(Tree_Node);
};
template <typename T>
struct Tree_Node_Vtl : public Tree_Node<T>
{
virtual ~Tree_Node_Vtl() {}
};
template <class Node> static inline
void clone_tree(Node * src, Node * tgt)
{
using It = typename Node::Children_Iterator;
for (It it(src); it.has_curr(); it.next())
tgt->insert_rightmost_child(new Node(it.get_curr()->get_key()));
using PItor = Pair_Iterator<It>;
for (PItor itor{It(*src), It(*tgt)}; itor.has_curr(); itor.next())
{
auto p = itor.get_curr();
clone_tree(p.first, p.second);
}
}
template <class Node>
Node * clone_tree(Node * root)
{
if (root == nullptr)
return nullptr;
Node * ret = new Node(root->get_key());
clone_tree(root, ret);
return ret;
}
template <class Node> static inline
void __tree_preorder_traversal(Node * root, const int & level,
const int & child_index,
void (*visitFct)(Node *, int, int))
{
(*visitFct)(root, level, child_index);
Node * child = root->get_left_child();
for (int i = 0; child != nullptr; ++i, child = child->get_right_sibling())
__tree_preorder_traversal(child, level + 1, i, visitFct);
}
/** Recorre en prefijo un árbol.
tree_preorder_traversal((root,visit) realiza un recorrido prefijo
sobre el árbol con raíz root. Si visitFct es especificado,
entonces, por cada nodo visitado, se invoca la función.
La función de vista tiene la siguiente especificación:
void (*visitFct)(Node* p, int level, int pos)
Donde:
-# p: puntero al nodo actualmente visitado.
-# level: el nivel de p en el árbol.
-# child_index: índice de p dentro de sus hermanos.
@param[in] root raíz del árbol a visitar.
@param[in] visitFct puntero a la función de visita.
@see forest_preorder_traversal() tree_postorder_traversal()
@see forest_postorder_traversal()
@throw domain_error si root no es un nodo raíz de un árbol.
@ingroup Arboles
*/
template <class Node> inline
void tree_preorder_traversal(Node * root, void (*visitFct)(Node *, int, int))
{
if (not root->is_root())
throw std::domain_error("root is not root");
__tree_preorder_traversal(root, 0, 0, visitFct);
}
/** Recorre en prefijo una arborescencia.
forest_preorder_traversal((root,visit) realiza un recorrido prefijo
sobre la arborescencia root. Si visitFct es especificado,
entonces, por cada nodo visitado, se invoca la función.
La función de vista tiene la siguiente especificación:
void (*visitFct)(Node* p, int level, int pos)
Donde:
-# p: puntero al nodo actualmente visitado.
-# level: el nivel de p en el árbol.
-# child_index: índice de p dentro de sus hermanos.
@param[in] root raíz del árbol primer árbol en la arborescencia.
@param[in] visitFct puntero a la función de visita.
@throw domain_error si root no es un nodo raíz de un árbol.
@see tree_preorder_traversal() tree_postorder_traversal()
@see forest_postorder_traversal()
@ingroup Arboles
*/
template <class Node> inline
void forest_preorder_traversal(Node * root, void (*visitFct)(Node *, int, int))
{
if (not root->is_root())
throw std::domain_error("root is not root");
for (/* nada */; root != nullptr; root = root->get_right_tree())
{
assert(root->is_root());
__tree_preorder_traversal(root, 0, 0, visitFct);
}
}
template <class Node> static inline
void __tree_postorder_traversal(Node * node, const int & level,
const int & child_index,
void (*visitFct)(Node *, int, int))
{
Node * child = node->get_left_child();
for (int i = 0; child not_eq nullptr; i++, child = child->get_right_sibling())
__tree_postorder_traversal(child, level + 1, i, visitFct);
(*visitFct)(node, level, child_index);
}
/** Recorre en sufijo un árbol.
tree_postorder_traversal((root,visit) realiza un recorrido prefijo
sobre el árbol con raíz root. Si visitFct es especificado,
entonces, por cada nodo visitado, se invoca la función.
La función de vista tiene la siguiente especificación:
void (*visitFct)(Node* p, int level, int pos)
Donde:
-# p: puntero al nodo actualmente visitado.
-# level: el nivel de p en el árbol.
-# child_index: índice de p dentro de sus hermanos.
@param[in] root raíz del árbol a visitar.
@param[in] visitFct puntero a la función de visita.
@see forest_preorder_traversal() tree_preorder_traversal()
@see forest_postorder_traversal()
@ingroup Arboles
*/
template <class Node> inline
void tree_postorder_traversal(Node * root, void (*visitFct)(Node *, int, int))
{
__tree_postorder_traversal(root, 0, 0, visitFct);
}
/** Recorre en sufijo una arborescencia.
forest_postorder_traversal((root,visit) realiza un recorrido sufijo
sobre el árbol con raíz root. Si visitFct es especificado,
entonces, por cada nodo visitado, se invoca la función.
La función de vista tiene la siguiente especificación:
void (*visitFct)(Node* p, int level, int pos)
Donde:
-# p: puntero al nodo actualmente visitado.
-# level: el nivel de p en el árbol.
-# child_index: índice de p dentro de sus hermanos.
@param[in] root raíz del árbol a visitar.
@param[in] visitFct puntero a la función de visita.
@see forest_preorder_traversal() tree_preorder_traversal()
@see tree_postorder_traversal()
@throw domain_error si root no es nodo raíz del árbol más a la
izquierda de la arborescencia.
@ingroup Arboles
*/
template <class Node> inline
void forest_postorder_traversal(Node * root, void (*visitFct)(Node *, int, int))
{
if (not root->is_leftmost())
throw std::domain_error("root is not the leftmost node of forest");
if (not root->is_root())
throw std::domain_error("root is not root");
for (/* nada */; root not_eq nullptr; root = root->get_right_sibling())
{
assert(root->is_root());
__tree_postorder_traversal(root, 0, 0, visitFct);
}
}
/** Retorna true si t1 es igual a t2
@ingroup Arboles
*/
template <class Node, class Eq>
inline bool are_tree_equal(Node * t1, Node * t2, Eq & eq)
noexcept(noexcept(eq(t1->get_key(), t2->get_key())))
{
if (t1 == nullptr)
return t2 == nullptr;
if (t2 == nullptr)
return false;
if (not eq(t1->get_key(), t2->get_key()))
return false;
try
{
return zipEq(t1->children_nodes(), t2->children_nodes()).all([] (auto p)
{
return are_tree_equal(p.first, p.second);
});
}
catch (std::length_error)
{
return false;
}
}
template <class Node,
class Eq = std::equal_to<typename Node::key_type>>
inline bool are_tree_equal(Node * t1, Node * t2, Eq && eq = Eq())
noexcept(noexcept(are_tree_equal<Node, Eq>(t1, t2, eq)))
{
return are_tree_equal<Node, Eq>(t1, t2, eq);
}
/** Destruye (libera memoria) el árbol cuya raíz es root.
destroy_tree(root) libera toda la memoria ocupada por el
árbol cuya raíz es root.
@param[in] root raíz del árbol que se desea liberar.
@ingroup Arboles
*/
template <class Node> inline
void destroy_tree(Node * root)
{
if (root == nullptr)
return;
if (not IS_UNIQUE_SIBLING(root))
SIBLING_LIST(root)->del(); // no ==> sacarlo de lista hermanos
// recorrer los subárboles de derecha a izquierda
for (Node * p = (Node*) root->get_right_child(); p != nullptr; /* nada */)
{
Node * to_delete = p; // respaldar subárbol a borrar p
p = (Node*) p->get_left_sibling(); // Avanzar p a hermano izquierdo
destroy_tree(to_delete); // eliminar recursivamente árbol
}
if (root->is_leftmost()) // ¿sacar lista hijos?
CHILD_LIST(root)->del();
delete root;
}
/** Destruye (libera memoria) la arborescencia cuya primer
árbol es root.
destroy_forest(root) libera toda la memoria ocupada por el
la arborescencia cuyo primer árbol tiene raíz root.
@param[in] root raíz del primer árbol de la arborescencia
que se desea destruir.
@throw domain_error si root no es nodo raíz del árbol más a la
izquierda de la arborescencia.
@ingroup Arboles
*/
template <class Node> inline
void destroy_forest(Node * root)
{
if (root == nullptr)
return;
if (not root->is_leftmost())
throw std::domain_error("root is not the leftmost tree of forest");
if (not root->is_root())
throw std::domain_error("root is not root");
while (root != nullptr) // recorre los árboles de izquierda a derecha
{
Node * to_delete = root; // respalda raíz
root = root->get_right_sibling(); // avanza a siguiente árbol
SIBLING_LIST(to_delete)->del(); // elimine de lista árboles
destroy_tree(to_delete); // Borre el árbol
}
}
/** Calcula la altura del árbol root.
@param[in] root raíz del árbol.
@return altura del árbol en raíz root.
@ingroup Arboles
*/
template <class Node>
size_t compute_height(Node * root)
{
if (root == nullptr)
return 0;
size_t temp_h, max_h = 0;
for (Node * aux = root->get_left_child(); aux != nullptr;
aux = aux->get_right_sibling())
if ((temp_h = compute_height(aux)) > max_h)
max_h = temp_h;
return max_h + 1;
}
template <class Node> static inline
Node * __deway_search(Node * node, int path [],
const int & idx, const size_t & size)
{
if (node == nullptr)
return nullptr;
if (idx > size)
throw std::out_of_range("index out of maximum range");
if (path[idx] < 0) // verifique si se ha alcanzado el nodo
return node;
// avance hasta el próximo hijo path[0]
Node * child = node->get_left_child();
for (int i = 0; i < path[idx] and child != nullptr; ++i)
child = child->get_right_sibling();
return __deway_search(child, path, idx + 1, size); // próximo nivel
}
/** Retorna un nodo de una arborescencia dado su número de Deway.
deway_search(root,path,size) toma el número de Deway guardado
en path, de longitud size y busca en la arborescencia cuyo primer
árbol es root un nodo que se corresponda con el número de Deway dado.
@param[in] root raíz del primer árbol de la arborescencia.
@param[in] path arreglo que contiene el número de Deway.
@param[in] size tamaño del número de deway.
@return puntero al nodo correspondiente al número de Deway
dado; nullptr si no existe,
@ingroup Arboles
*/
template <class Node> inline
Node * deway_search(Node * root, int path [], const size_t & size)
{
for (int i = 0; root != nullptr; i++, root = root->get_right_sibling())
if (path[0] == i)
return __deway_search(root, path, 1, size);
return nullptr;
}
template <class Node, class Equal> inline static
Node * __search_deway(Node * root, const typename Node::key_type & key,
const size_t & current_level, int deway [],
const size_t & size, size_t & n);
/** Busca key en arborescencia y calcula el número de Deway del
nodo contentivo de la clave key.
search_deway(root,key,deway,n) busca en la arborescencia
cuyo primer árbol es root un nodo que contenga la clave key.
Si el nodo es encontrado, entonces la rutina guarda en deway[]
el número de Deway del nodo encontrado.
La búsqueda se realiza con criterio de igualdad Equal()().
@param[in] root raíz del primer árbol de la arborescencia.
@param[in] key clave a buscar
@param[out] deway arreglo que contiene el número de Deway.
@param[in] size tamaño máximo del número de deway.
@param[out] n tamaño del número de Deway calculado (si se
encuentra el nodo).
@return puntero al nodo contentivo de la clave key;
nullptr si no existe ningún nodo con clave key,
@throw overflow_error si size no es suficiente para almacenar la
secuencia de Deway.
@ingroup Arboles
*/
template <class Node,
class Equal = Aleph::equal_to<typename Node::key_type> > inline
Node * search_deway(Node * root, const typename Node::key_type & key,
int deway [], const size_t & size, size_t & n)
{
n = 1; // valor inicial de longitud de número de Deway
if (size < n)
throw std::overflow_error("there is no enough space for deway array");
for (int i = 0; root != nullptr; i++, root = root->get_right_sibling())
{
deway[0] = i;
Node * result =
__search_deway <Node, Equal> (root, key, 0, deway, size, n);
if (result != nullptr)
return result;
}
return nullptr;
}
template <class Node, class Equal> inline static
Node * __search_deway(Node * root,
const typename Node::key_type & key,
const size_t & current_level, int deway [],
const size_t & size, size_t & n)
{
if (current_level >= size)
throw std::overflow_error("there is no enough space for deway array");
if (root == nullptr)
return nullptr;
if (Equal()(root->get_key(), key))
{
n = current_level + 1; // longitud del arreglo deway
return root;
}
Node * child = root->get_left_child();
for (int i = 0; child != nullptr;
i++, child = child->get_right_sibling())
{
deway[current_level + 1] = i;
Node * result = __search_deway <Node, Equal>
(child, key, current_level + 1, deway, size, n);
if (result!= nullptr)
return result;
}
return nullptr;
}
/** Convierte una arborescencia a su árbol binario equivalente.
forest_to_bin(root) toma una arborescencia derivada de Tree_Node
y lo convierte a su equivalente árbol binario.
La rutina maneja dos parámetros tipo:
-# TNode: tipo de árbol basado en Tree_Node.
-# BNode: tipo de árbol binario basado en BinNode.
El procedimiento asume que ambos tipos comparten el mismo
tipo de clave.
@param[in] root raíz del primer árbol perteneciente a
la arborescencia a convertir.
@return raíz del árbol binario equivalente a la arborescencia
dada.
@throw bad_alloc si no hay suficiente memoria.
@see bin_to_forest()
@ingroup Arboles
*/
template <class TNode, class BNode>
BNode * forest_to_bin(TNode * root)
{
if (root == nullptr)
return BNode::NullPtr;
BNode * result = new BNode (root->get_key());
LLINK(result) = forest_to_bin<TNode,BNode>(root->get_left_child());
RLINK(result) = forest_to_bin<TNode,BNode>(root->get_right_sibling());
return result;
}
template <class TNode, class BNode> inline static
void insert_child(BNode * lnode, TNode * tree_node)
{
if (lnode == BNode::NullPtr)
return;
TNode * child = new TNode(KEY(lnode));
tree_node->insert_leftmost_child(child);
}
template <class TNode, class BNode> inline static
void insert_sibling(BNode * rnode, TNode * tree_node)
{
if (rnode == BNode::NullPtr)
return;
TNode * sibling = new TNode(KEY(rnode));
tree_node->insert_right_sibling(sibling);
}
template <class TNode, class BNode> inline static
void bin_to_tree(BNode * broot, TNode * troot)
{
if (broot == BNode::NullPtr)
return;
insert_child(LLINK(broot), troot);
TNode * left_child = troot->get_left_child();
bin_to_tree(LLINK(broot), left_child);
insert_sibling(RLINK(broot), troot);
TNode * right_sibling = troot->get_right_sibling();
bin_to_tree(RLINK(broot), right_sibling);
}
/** Convierte un árbol binario a su arborescencia equivalente.
bin_to_forest(root) toma un árbol binario derivado de BinNode
y lo convierte a su arborescencia equivalente.
La rutina maneja dos parámetros tipo:
-# TNode: tipo de árbol basado en Tree_Node.
-# BNode: tipo de árbol binario basado en BinNode.
El procedimiento asume que ambos tipos comparten el mismo
tipo de clave.
@param[in] broot raíz del árbol binario a convertir.
@return raíz del primer árbol equivalente a árbol binario
dado.
@throw bad_alloc si no hay suficiente memoria.
@see forest_to_bin()
@ingroup Arboles
*/
template <class TNode, class BNode> inline
TNode * bin_to_forest(BNode * broot)
{
if (broot == BNode::NullPtr)
return nullptr;
TNode * troot = new TNode (KEY(broot));
bin_to_tree(broot, troot);
return troot;
}
} // fin namespace Aleph
# endif // TPL_TREE_H
| gpl-3.0 |
HellionCommunity/HellionExtendedServer | HellionExtendedServer/HESGui.cs | 20413 | using HellionExtendedServer.Common;
using HellionExtendedServer.GUI.Objects;
using HellionExtendedServer.Managers;
using HellionExtendedServer.Modules;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using ZeroGravity.Network;
using ZeroGravity.Objects;
namespace HellionExtendedServer
{
public partial class HESGui : Form
{
private Timer ObjectManipulationRefreshTimer = new Timer();
private Timer PlayersRefreshTimer = new Timer();
private bool isRunning;
public HESGui()
{
InitializeComponent();
DisableControls();
ServerInstance.Instance.OnServerRunning += Instance_OnServerRunning;
ServerInstance.Instance.OnServerStopped += Instance_OnServerStopped;
ServerInstance.Instance.GameServerConfig.Load();
serverconfig_properties.SelectedObject = ServerInstance.Instance.GameServerConfig;
hesconfig_properties.SelectedObject = Config.Instance.Settings;
serverconfig_properties.Refresh();
if (Config.Instance.Settings.EnableDevelopmentVersion)
{
var result = MessageBox.Show(
"Development Versions have been enabled.\r\n\r\n" +
"You have selected to use HES's Development Versions",
"Development Versions Enabled",
System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Exclamation);
if (result == System.Windows.Forms.DialogResult.OK)
{
}
}
UpdateManager.Instance.OnUpdateChecked += new UpdateManager.UpdateEventHandler(Instance_OnUpdateChecked);
UpdateManager.Instance.OnUpdateDownloaded += new UpdateManager.UpdateEventHandler(Instance_OnUpdateDownloaded);
UpdateManager.Instance.OnUpdateApplied += new UpdateManager.UpdateEventHandler(Instance_OnUpdateApplied);
server_hesNewsLabel.Text =
@"Welcome to HES! Auto updates have now been implemented!" +
"Check out the enabled Options under HES Config!";
isRunning = ServerInstance.Instance.IsRunning;
}
private void DisableControls(bool disable = true)
{
cpc_chat_list.ReadOnly = true;
cpc_chat_list.BackColor = System.Drawing.SystemColors.Window;
cpc_messagebox.Enabled = !disable;
cpc_chat_send.Enabled = !disable;
pc_banplayer.Enabled = !disable;
pc_kickplayer.Enabled = !disable;
sc_playerslist_listview.Enabled = !disable;
server_config_stopserver.Enabled = !disable;
server_config_startserver.Enabled = disable;
objectManipulation_grid.Enabled = !disable;
objectManipulation_treeview.Enabled = !disable;
cpc_chat_list.AppendText("Waiting for server to start..\r\n");
}
#region Events
private void Instance_OnServerStopped(ZeroGravity.Server server)
{
StatusBar.Text = "Server Stopped";
this.Invoke(new MethodInvoker(delegate
{
DisableControls();
ObjectManipulationRefreshTimer.Stop();
ObjectManipulationRefreshTimer.Enabled = false;
PlayersRefreshTimer.Stop();
PlayersRefreshTimer.Enabled = false;
this.Refresh();
}));
}
public void UpdateChatPlayers()
{
try
{
if (ServerInstance.Instance.Server == null)
return;
if (NetworkManager.Instance == null)
return;
if (!ZeroGravity.Server.IsRunning)
return;
sc_onlineplayers_label.Text = NetworkManager.Instance.ClientList.Count.ToString();
foreach (KeyValuePair<long, NetworkController.Client> client in NetworkManager.Instance.ClientList)
{
if (client.Value == null)
continue;
if (client.Value.Player == null)
continue;
var player = client.Value.Player;
var item = new ListViewItem();
item.Name = player.GUID.ToString();
item.Tag = client.Value;
item.Text = $"{player.Name} ({player.SteamId})";
if (!sc_playerslist_listview.Items.ContainsKey(item.Name))
sc_playerslist_listview.Items.Add(item);
if (!pc_players_listview.Items.ContainsKey(item.Name))
pc_players_listview.Items.Add(item);
}
// chat players
foreach (ListViewItem item in sc_playerslist_listview.Items)
{
var _client = item.Tag as NetworkController.Client;
var _player = _client.Player;
if (!NetworkManager.Instance.ClientList.Values.Contains(_client))
{
if (sc_playerslist_listview.Items.ContainsKey(item.Name))
sc_playerslist_listview.Items.RemoveByKey(item.Name);
}
}
// player control players
foreach (ListViewItem item in pc_players_listview.Items)
{
var _client = item.Tag as NetworkController.Client;
var _player = _client.Player;
if (!NetworkManager.Instance.ClientList.Values.Contains(_client))
{
if (pc_players_listview.Items.ContainsKey(_player.GUID.ToString()))
pc_players_listview.Items.RemoveByKey(_player.GUID.ToString());
}
}
}
catch (Exception ex)
{
Log.Instance.Error(ex, "Ignore this for now, dont report it!");
}
}
private void Instance_OnServerRunning(ZeroGravity.Server server)
{
StatusBar.Text = "Server Started!";
Invoke(new MethodInvoker(delegate
{
DisableControls(false);
UpdatePlayersTree();
UpdateChatPlayers();
this.Refresh();
}));
ObjectManipulationRefreshTimer.Interval = (1000); // 1 secs
ObjectManipulationRefreshTimer.Tick += delegate (object sender, EventArgs e)
{
UpdatePlayersTree();
};
PlayersRefreshTimer.Interval = (10000); // 1 secs
PlayersRefreshTimer.Tick += delegate (object sender, EventArgs e)
{
UpdateChatPlayers();
};
}
#endregion Events
#region Object Manipulation
public List<MyPlayer> MyPlayers = new List<MyPlayer>();
public void UpdatePlayersTree()
{
if (ServerInstance.Instance.Server == null)
return;
if (NetworkManager.Instance == null)
return;
if (!ZeroGravity.Server.IsRunning)
return;
var treeNodeList = objectManipulation_treeview.Nodes[0].Nodes;
// Convert the Games Players into something the GUI can use
var playersList = NetworkManager.Instance.ClientList;
foreach (var client in NetworkManager.Instance.ClientList)
{
var player = client.Value.Player;
if (!MyPlayers.Exists(x => x.GUID == player.GUID))
MyPlayers.Add(new MyPlayer(player));
}
// Remove the player
foreach (var _player in MyPlayers)
{
Player player = _player.CurrentPlayer;
if (player == null)
{
if (MyPlayers.Exists(x => x.GUID == _player.GUID))
MyPlayers.Remove(_player);
if (treeNodeList.ContainsKey(_player.GUID.ToString()))
treeNodeList.RemoveByKey(_player.GUID.ToString());
objectManipulation_treeview.Refresh();
objectManipulation_grid.Refresh();
continue;
}
TreeNode node = new TreeNode
{
Name = player.GUID.ToString(),
Text = player.Name + $" ({player.SteamId})",
Tag = _player
};
if (!treeNodeList.ContainsKey(node.Name))
treeNodeList.Add(node);
}
foreach (TreeNode node in treeNodeList)
{
MyPlayer tag = node.Tag as MyPlayer;
if (tag == null)
continue;
var player = GetPlayerFromGuid(tag.GUID);
if (player == null)
{
treeNodeList.Remove(node);
}
}
objectManipulation_treeview.Refresh();
objectManipulation_grid.Refresh();
}
private void objectManipulation_treeview_AfterSelect(object sender, TreeViewEventArgs e)
{
var node = e.Node;
if (node == null)
return;
if (node.Tag == null)
return;
objectManipulation_grid.SelectedObject = node.Tag as MyPlayer;
objectManipulation_grid.Refresh();
}
private void objectManipulation_treeview_Click(object sender, EventArgs e)
{
UpdatePlayersTree();
}
public ZeroGravity.Objects.Player GetPlayerFromGuid(long guid)
{
foreach (var player in ServerInstance.Instance.Server.AllPlayers)
{
if (player.GUID == guid) return player;
}
return null;
}
#endregion Object Manipulation
#region Server Control
private void server_config_save_Click(object sender, EventArgs e)
{
if (server_server_Tabs.SelectedTab.Name == "ServerConfig")
{
if (ServerInstance.Instance.GameServerConfig.Save())
{
StatusBar.Text = "Config Saved.";
}
}
else if (server_server_Tabs.SelectedTab.Name == "HESConfig")
{
if (Config.Instance.SaveConfiguration())
{
StatusBar.Text = "HES Config Saved.";
}
}
}
private void server_config_cancel_Click(object sender, EventArgs e)
{
if (server_server_Tabs.SelectedTab.Name == "ServerConfig")
{
ServerInstance.Instance.GameServerConfig.Load();
serverconfig_properties.SelectedObject = ServerInstance.Instance.GameServerConfig;
serverconfig_properties.Refresh();
StatusBar.Text = "Reloaded the config from the GameServer.ini.";
}
else if (server_server_Tabs.SelectedTab.Name == "HESConfig")
{
if (Config.Instance.LoadConfiguration())
{
hesconfig_properties.SelectedObject = Config.Instance.Settings;
hesconfig_properties.Refresh();
StatusBar.Text = "Reloaded the config from the GameServer.ini.";
}
}
}
private void server_config_setdefaults_Click(object sender, EventArgs e)
{
if (server_server_Tabs.SelectedTab.Name == "ServerConfig")
{
DialogResult result = MessageBox.Show("Are you sure you want to load the default settings?",
"Server Config Settings",
MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
if (result == DialogResult.Yes)
{
ServerInstance.Instance.GameServerConfig.LoadDefaults();
serverconfig_properties.SelectedObject = ServerInstance.Instance.GameServerConfig;
serverconfig_properties.Refresh();
StatusBar.Text = "Config defaults loaded. Don't forget to save!";
}
}
else if (server_server_Tabs.SelectedTab.Name == "HESConfig")
{
Config.Instance.Settings = new Settings();
hesconfig_properties.SelectedObject = Config.Instance.Settings;
hesconfig_properties.Refresh();
StatusBar.Text = "HES Config Defaults loaded. Don't forget to save!";
}
}
private void server_config_reload_Click(object sender, EventArgs e)
{
if (server_server_Tabs.SelectedTab.Name == "ServerConfig")
{
DialogResult result = MessageBox.Show("Are you sure you want to reload the settings from the GameServer.Ini?",
"2. Server Settings Error",
MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
if (result == DialogResult.Yes)
{
ServerInstance.Instance.GameServerConfig.Load();
serverconfig_properties.SelectedObject = ServerInstance.Instance.GameServerConfig;
serverconfig_properties.Refresh();
StatusBar.Text = "Config reloaded from GameServer.ini";
}
}
else if (server_server_Tabs.SelectedTab.Name == "HESConfig")
{
if (Config.Instance.LoadConfiguration())
{
hesconfig_properties.SelectedObject = Config.Instance.Settings;
hesconfig_properties.Refresh();
StatusBar.Text = "Reloaded HES Config from Config.xml.";
}
}
}
private void server_config_startserver_Click(object sender, EventArgs e)
{
try
{
CheckForIllegalCrossThreadCalls = false;
if (!ServerInstance.Instance.IsRunning)
{
StatusBar.Text = "Server Starting";
HES.KeyPressSimulator("/s");
AddChatLine("Starting Server!");
}
else
StatusBar.Text = "The server is already started!";
}
catch (Exception)
{
}
}
private void server_config_stopserver_Click(object sender, EventArgs e)
{
try
{
if (ServerInstance.Instance.IsRunning)
{
StatusBar.Text = "Server Stopping";
HES.KeyPressSimulator("/ss");
}
else
StatusBar.Text = "The server is already stopped!";
}
catch (Exception)
{
}
}
#endregion Server Control
#region Chat And Players
public void AddChatLine(string line)
{
if (cpc_chat_list.InvokeRequired)
{
cpc_chat_list.Invoke(new MethodInvoker(delegate
{
cpc_chat_list.AppendText(line + Environment.NewLine);
}));
return;
}
else
cpc_chat_list.AppendText(line + Environment.NewLine);
}
private void cpc_players_kick_Click(object sender, EventArgs e)
{
}
private void cpc_players_ban_Click(object sender, EventArgs e)
{
}
private void cpc_messagebox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter & !String.IsNullOrEmpty(cpc_messagebox.Text))
{
NetworkManager.Instance.MessageAllClients(cpc_messagebox.Text, true, true);
cpc_messagebox.Text = "";
e.Handled = e.SuppressKeyPress = true;
}
}
private void cpc_chat_send_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(cpc_messagebox.Text))
{
NetworkManager.Instance.MessageAllClients(cpc_messagebox.Text, true, true);
cpc_messagebox.Text = "";
}
}
#endregion Chat And Players
private void Default_SettingsSaving(object sender, CancelEventArgs e)
{
StatusBar.Text = "GUI Settings Changed";
}
private void objectManipulation_grid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
}
private void Tabs_Selected(object sender, TabControlEventArgs e)
{
ObjectManipulationRefreshTimer.Enabled = false;
PlayersRefreshTimer.Enabled = false;
switch (e.TabPageIndex)
{
case 0:
break;
case 1:
PlayersRefreshTimer.Enabled = true;
break;
case 2:
PlayersRefreshTimer.Enabled = true;
break;
case 3:
ObjectManipulationRefreshTimer.Enabled = true;
break;
default:
break;
}
}
private async void serverconfig_checkForUpdates_Click(object sender, EventArgs e)
{
StatusBar.Text = "Checking for updates...";
UpdateManager.GUIMode = true;
await UpdateManager.Instance.GetLatestReleaseInfo();
UpdateManager.Instance.CheckVersion(false);
}
private void Instance_OnUpdateChecked(Octokit.Release release)
{
if (!UpdateManager.HasUpdate)
{
StatusBar.Text = $"You are running the latest version!";
return;
}
ServerInstance.Instance.Save(true);
var result = MessageBox.Show(
$"A new version has been detected: { UpdateManager.NewVersionNumber }\r\n" +
$"\r\n Release Information:\r\n" +
$"Release Name: {release.Name}\r\n" +
$"Download Count: {release.Assets.FirstOrDefault().DownloadCount}\r\n" +
$"Release Published {release.Assets.First().CreatedAt.ToLocalTime()}\r\n" +
$"Release Description:\r\n\r\n" +
$"{release.Body}\r\n\r\n" +
$"Would you like to update now?",
"HES Updater",
MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
UpdateManager.Instance.DownloadLatestRelease(Config.Instance.Settings.EnableDevelopmentVersion);
}
else
{
StatusBar.Text = "The Update has been canceled.";
}
}
private void Instance_OnUpdateDownloaded(Octokit.Release release)
{
if (UpdateManager.GUIMode)
{
StatusBar.Text = "The Update is being applied..";
UpdateManager.Instance.ApplyUpdate();
}
}
private void Instance_OnUpdateApplied(Octokit.Release release)
{
var result = MessageBox.Show(
$"You must restart before the update can be completed!\r\n\r\n" +
$"Would you like to restart now?\r\n" +
$"Note: The server was saved after downloading this release.",
"HES Updater",
MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
if (result == DialogResult.Yes)
{
HES.Restart();
}
else
{
StatusBar.Text = "HES needs to be restarted before you can use the new features!";
}
}
}
} | gpl-3.0 |
sklarman/grakn | grakn-test/src/test/java/ai/grakn/factory/GraknSessionMock.java | 1520 | /*
* Grakn - A Distributed Semantic Database
* Copyright (C) 2016 Grakn Labs Limited
*
* Grakn 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.
*
* Grakn 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 Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>.
*/
package ai.grakn.factory;
import ai.grakn.GraknComputer;
import ai.grakn.util.REST;
import org.apache.tinkerpop.gremlin.structure.Graph;
/**
*
*/
public class GraknSessionMock extends GraknSessionImpl {
private final String keyspace;
private final String uri;
public GraknSessionMock(String keyspace, String uri) {
super(keyspace.toLowerCase(), uri);
this.keyspace = keyspace;
this.uri = uri;
}
public GraknComputer getGraphComputer(int numberOfWorkers) {
ConfiguredFactory configuredFactory = configureGraphFactory(keyspace, uri, REST.GraphConfig.COMPUTER);
Graph graph = configuredFactory.factory.getTinkerPopGraph(false);
return new GraknComputerMock(graph, configuredFactory.graphComputer, numberOfWorkers);
}
}
| gpl-3.0 |
nickkolok/chas-ege | zdn/misc_log/M2/main.js | 101 | window.nomer=sl(1,14);
window.comment='Дробные и отрицательные степени';
| gpl-3.0 |