code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
#!/usr/bin/env python
#
# 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. See http://www.gnu.org/copyleft/gpl.html for
# the full text of the license.
# query.py: Perform a few varieties of queries
from __future__ import print_function
import time
import bugzilla
# public test instance of bugzilla.redhat.com. It's okay to make changes
URL = "partner-bugzilla.redhat.com"
bzapi = bugzilla.Bugzilla(URL)
# build_query is a helper function that handles some bugzilla version
# incompatibility issues. All it does is return a properly formatted
# dict(), and provide friendly parameter names. The param names map
# to those accepted by XMLRPC Bug.search:
# https://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#search-bugs
query = bzapi.build_query(
product="Fedora",
component="python-bugzilla")
# Since 'query' is just a dict, you could set your own parameters too, like
# if your bugzilla had a custom field. This will set 'status' for example,
# but for common opts it's better to use build_query
query["status"] = "CLOSED"
# query() is what actually performs the query. it's a wrapper around Bug.search
t1 = time.time()
bugs = bzapi.query(query)
t2 = time.time()
print("Found %d bugs with our query" % len(bugs))
print("Query processing time: %s" % (t2 - t1))
# Depending on the size of your query, you can massively speed things up
# by telling bugzilla to only return the fields you care about, since a
# large chunk of the return time is transmitting the extra bug data. You
# tweak this with include_fields:
# https://wiki.mozilla.org/Bugzilla:BzAPI#Field_Control
# Bugzilla will only return those fields listed in include_fields.
query = bzapi.build_query(
product="Fedora",
component="python-bugzilla",
include_fields=["id", "summary"])
t1 = time.time()
bugs = bzapi.query(query)
t2 = time.time()
print("Quicker query processing time: %s" % (t2 - t1))
# bugzilla.redhat.com, and bugzilla >= 5.0 support queries using the same
# format as is used for 'advanced' search URLs via the Web UI. For example,
# I go to partner-bugzilla.redhat.com -> Search -> Advanced Search, select
# Classification=Fedora
# Product=Fedora
# Component=python-bugzilla
# Unselect all bug statuses (so, all status values)
# Under Custom Search
# Creation date -- is less than or equal to -- 2010-01-01
#
# Run that, copy the URL and bring it here, pass it to url_to_query to
# convert it to a dict(), and query as usual
query = bzapi.url_to_query("https://partner-bugzilla.redhat.com/"
"buglist.cgi?classification=Fedora&component=python-bugzilla&"
"f1=creation_ts&o1=lessthaneq&order=Importance&product=Fedora&"
"query_format=advanced&v1=2010-01-01")
query["include_fields"] = ["id", "summary"]
bugs = bzapi.query(query)
print("The URL query returned 22 bugs... "
"I know that without even checking because it shouldn't change!... "
"(count is %d)" % len(bugs))
# One note about querying... you can get subtley different results if
# you are not logged in. Depending on your bugzilla setup it may not matter,
# but if you are dealing with private bugs, check bzapi.logged_in setting
# to ensure your cached credentials are up to date. See update.py for
# an example usage
| abn/python-bugzilla | examples/query.py | Python | gpl-2.0 | 3,441 |
/* Initialize
*/
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
jQuery(document).ready(function ($) {
// Bootstrap Init
$("[rel=tooltip]").tooltip();
$('[data-toggle=tooltip]').tooltip();
$("[rel=popover]").popover();
$('#authorTab a').click(function (e) {e.preventDefault(); $(this).tab('show'); });
$('.sc_tabs a').click(function (e) {e.preventDefault(); $(this).tab('show'); });
$(".videofit").fitVids();
$(".embed-youtube").fitVids();
$('.kad-select').customSelect();
$('.woocommerce-ordering select').customSelect();
$('.collapse-next').click(function (e) {
//e.preventDefault();
var $target = $(this).siblings('.sf-dropdown-menu');
if($target.hasClass('in') ) {
$target.collapse('toggle');
$(this).removeClass('toggle-active');
} else {
$target.collapse('toggle');
$(this).addClass('toggle-active');
}
});
// Lightbox
function kt_check_images( index, element ) {
return /(png|jpg|jpeg|gif|tiff|bmp)$/.test(
$( element ).attr( 'href' ).toLowerCase().split( '?' )[0].split( '#' )[0]
);
}
function kt_find_images() {
$( 'a[href]' ).filter( kt_check_images ).attr( 'data-rel', 'lightbox' );
}
kt_find_images();
$.extend(true, $.magnificPopup.defaults, {
tClose: '',
tLoading: light_load, // Text that is displayed during loading. Can contain %curr% and %total% keys
gallery: {
tPrev: '', // Alt text on left arrow
tNext: '', // Alt text on right arrow
tCounter: light_of // Markup for "1 of 7" counter
},
image: {
tError: light_error, // Error message when image could not be loaded
titleSrc: function(item) {
return item.el.find('img').attr('alt');
}
}
});
$("a[rel^='lightbox']").magnificPopup({type:'image'});
$("a[data-rel^='lightbox']").magnificPopup({type:'image'});
$('.kad-light-gallery').each(function(){
$(this).find('a[rel^="lightbox"]').magnificPopup({
type: 'image',
gallery: {
enabled:true
},
image: {
titleSrc: 'title'
}
});
});
$('.kad-light-gallery').each(function(){
$(this).find("a[data-rel^='lightbox']").magnificPopup({
type: 'image',
gallery: {
enabled:true
},
image: {
titleSrc: 'title'
}
});
});
$('.kad-light-wp-gallery').each(function(){
$(this).find('a[rel^="lightbox"]').magnificPopup({
type: 'image',
gallery: {
enabled:true
},
image: {
titleSrc: function(item) {
return item.el.find('img').attr('alt');
}
}
});
});
$('.kad-light-wp-gallery').each(function(){
$(this).find("a[data-rel^='lightbox']").magnificPopup({
type: 'image',
gallery: {
enabled:true
},
image: {
titleSrc: function(item) {
return item.el.find('img').attr('alt');
}
}
});
});
//Superfish Menu
$('ul.sf-menu').superfish({
delay: 200, // one second delay on mouseout
animation: {opacity:'show',height:'show'}, // fade-in and slide-down animation
speed: 'fast' // faster animation speed
});
function kad_fullwidth_panel() {
var margins = $(window).width() - $('#content').width();
$('.panel-row-style-wide-feature').each(function(){
$(this).css({'padding-left': margins/2 + 'px'});
$(this).css({'padding-right': margins/2 + 'px'});
$(this).css({'margin-left': '-' + margins/2 + 'px'});
$(this).css({'margin-right': '-' + margins/2 + 'px'});
$(this).css({'visibility': 'visible'});
});
}
kad_fullwidth_panel();
$(window).on("debouncedresize", function( event ) {kad_fullwidth_panel();});
//init Flexslider
$('.kt-flexslider').each(function(){
var flex_speed = $(this).data('flex-speed'),
flex_animation = $(this).data('flex-animation'),
flex_animation_speed = $(this).data('flex-anim-speed'),
flex_auto = $(this).data('flex-auto');
$(this).flexslider({
animation:flex_animation,
animationSpeed: flex_animation_speed,
slideshow: flex_auto,
slideshowSpeed: flex_speed,
start: function ( slider ) {
slider.removeClass( 'loading' );
}
});
});
//init masonry
$('.init-masonry').each(function(){
var masonrycontainer = $(this),
masonry_selector = $(this).data('masonry-selector');
masonrycontainer.imagesLoadedn( function(){
masonrycontainer.masonry({itemSelector: masonry_selector});
});
});
//init carousel
jQuery('.initcaroufedsel').each(function(){
var container = jQuery(this);
var wcontainerclass = container.data('carousel-container'),
cspeed = container.data('carousel-speed'),
ctransition = container.data('carousel-transition'),
cauto = container.data('carousel-auto'),
carouselid = container.data('carousel-id'),
ss = container.data('carousel-ss'),
xs = container.data('carousel-xs'),
sm = container.data('carousel-sm'),
md = container.data('carousel-md');
var wcontainer = jQuery(wcontainerclass);
function getUnitWidth() {var width;
if(jQuery(window).width() <= 540) {
width = wcontainer.width() / ss;
} else if(jQuery(window).width() <= 768) {
width = wcontainer.width() / xs;
} else if(jQuery(window).width() <= 990) {
width = wcontainer.width() / sm;
} else {
width = wcontainer.width() / md;
}
return width;
}
function setWidths() {
var unitWidth = getUnitWidth() -1;
container.children().css({ width: unitWidth });
}
setWidths();
function initCarousel() {
container.carouFredSel({
scroll: {items:1, easing: "swing", duration: ctransition, pauseOnHover : true},
auto: {play: cauto, timeoutDuration: cspeed},
prev: '#prevport-'+carouselid, next: '#nextport-'+carouselid, pagination: false, swipe: true, items: {visible: null}
});
}
container.imagesLoadedn( function(){
initCarousel();
});
wcontainer.animate({'opacity' : 1});
jQuery(window).on("debouncedresize", function( event ) {
container.trigger("destroy");
setWidths();
initCarousel();
});
});
//init carouselslider
jQuery('.initcarouselslider').each(function(){
var container = jQuery(this);
var wcontainerclass = container.data('carousel-container'),
cspeed = container.data('carousel-speed'),
ctransition = container.data('carousel-transition'),
cauto = container.data('carousel-auto'),
carouselid = container.data('carousel-id'),
carheight = container.data('carousel-height'),
align = 'center';
var wcontainer = jQuery(wcontainerclass);
function setWidths() {
var unitWidth = container.width();
container.children().css({ width: unitWidth });
if(jQuery(window).width() <= 768) {
carheight = null;
container.children().css({ height: 'auto' });
}
}
setWidths();
function initCarouselslider() {
container.carouFredSel({
width: '100%',
height: carheight,
align: align,
auto: {play: cauto, timeoutDuration: cspeed},
scroll: {items : 1,easing: 'quadratic'},
items: {visible: 1,width: 'variable'},
prev: '#prevport-'+carouselid,
next: '#nextport-'+carouselid,
swipe: {onMouse: false,onTouch: true},
});
}
container.imagesLoadedn( function(){
initCarouselslider();
wcontainer.animate({'opacity' : 1});
wcontainer.css({ height: 'auto' });
wcontainer.parent().removeClass('loading');
});
jQuery(window).on("debouncedresize", function( event ) {
container.trigger("destroy");
setWidths();
initCarouselslider();
});
});
});
if( isMobile.any() ) {
jQuery(document).ready(function ($) {
$('.caroufedselclass').tswipe({
excludedElements:"button, input, select, textarea, .noSwipe",
tswipeLeft: function() {
$('.caroufedselclass').trigger('next', 1);
},
tswipeRight: function() {
$('.caroufedselclass').trigger('prev', 1);
},
tap: function(event, target) {
window.open(jQuery(target).closest('.grid_item').find('a').attr('href'), '_self');
}
});
});
}
| BellarmineBTDesigns/mashariki | wp-content/themes/pinnacle/assets/js/kt_main.js | JavaScript | gpl-2.0 | 9,445 |
<?php
/**
* sh404SEF - SEO extension for Joomla!
*
* @author Yannick Gaultier
* @copyright (c) Yannick Gaultier 2014
* @package sh404SEF
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @version 4.4.0.1725
* @date 2014-04-09
*/
// Security check to ensure this file is being included by a parent file.
if (!defined('_JEXEC')) die('Direct Access to this location is not allowed.');
$title = JText::_('COM_SH404SEF_ANALYTICS_REPORT_SOURCES') . '::' . JText::_('COM_SH404SEF_ANALYTICS_DATA_SOURCES_DESC_RAW');
?>
<div class="hasAnalyticsTip width-100" title="<?php echo $title; ?>">
<fieldset class="adminform">
<legend>
<?php echo JText::_('COM_SH404SEF_ANALYTICS_REPORT_SOURCES') . JText::_( 'COM_SH404SEF_ANALYTICS_REPORT_BY_LABEL') . Sh404sefHelperAnalytics::getDataTypeTitle(); ?>
</legend>
<ul class="adminformlist">
<li>
<div class="analytics-report-image"><img src="<?php echo $this->analytics->analyticsData->images['sources']; ?>" /></div>
</li>
</ul>
</fieldset>
</div> | LarsMog/elesbjerg.dk | administrator/components/com_sh404sef/views/analytics/tmpl/default_j2_sources.php | PHP | gpl-2.0 | 1,165 |
using System.IO;
using Nequeo.Cryptography.Key.Utilities.IO;
namespace Nequeo.Cryptography.Key.Asn1
{
public class BerGenerator
: Asn1Generator
{
private bool _tagged = false;
private bool _isExplicit;
private int _tagNo;
protected BerGenerator(
Stream outStream)
: base(outStream)
{
}
public BerGenerator(
Stream outStream,
int tagNo,
bool isExplicit)
: base(outStream)
{
_tagged = true;
_isExplicit = isExplicit;
_tagNo = tagNo;
}
public override void AddObject(
Asn1Encodable obj)
{
new BerOutputStream(Out).WriteObject(obj);
}
public override Stream GetRawOutputStream()
{
return Out;
}
public override void Close()
{
WriteBerEnd();
}
private void WriteHdr(
int tag)
{
Out.WriteByte((byte) tag);
Out.WriteByte(0x80);
}
protected void WriteBerHeader(
int tag)
{
if (_tagged)
{
int tagNum = _tagNo | Asn1Tags.Tagged;
if (_isExplicit)
{
WriteHdr(tagNum | Asn1Tags.Constructed);
WriteHdr(tag);
}
else
{
if ((tag & Asn1Tags.Constructed) != 0)
{
WriteHdr(tagNum | Asn1Tags.Constructed);
}
else
{
WriteHdr(tagNum);
}
}
}
else
{
WriteHdr(tag);
}
}
protected void WriteBerBody(
Stream contentStream)
{
Streams.PipeAll(contentStream, Out);
}
protected void WriteBerEnd()
{
Out.WriteByte(0x00);
Out.WriteByte(0x00);
if (_tagged && _isExplicit) // write extra end for tag header
{
Out.WriteByte(0x00);
Out.WriteByte(0x00);
}
}
}
}
| drazenzadravec/nequeo | Source/Components/Cryptography/Nequeo.Cryptography/Nequeo.Cryptography.Key/asn1/BERGenerator.cs | C# | gpl-2.0 | 2,356 |
<div class="wrap shopp">
<div class="icon32"></div>
<?php
shopp_admin_screen_tabs();
do_action('shopp_admin_notices');
?>
<?php if (count(shopp_setting('target_markets')) == 0) echo '<div class="error"><p>'.__('No target markets have been selected in your store setup.','Shopp').'</p></div>'; ?>
<?php $this->taxes_menu(); ?>
<form action="<?php echo esc_url($this->url); ?>" id="taxrates" method="post" enctype="multipart/form-data" accept="text/plain,text/xml">
<div>
<?php wp_nonce_field('shopp-settings-taxrates'); ?>
</div>
<div class="tablenav">
<div class="actions">
<button type="submit" name="addrate" id="addrate" class="button-secondary" tabindex="9999" <?php if (empty($countries)) echo 'disabled="disabled"'; ?>><?php _e('Add Tax Rate','Shopp'); ?></button>
</div>
</div>
<script id="property-menu" type="text/x-jquery-tmpl"><?php
$propertymenu = array(
'product-name' => __('Product name is','Shopp'),
'product-tags' => __('Product is tagged','Shopp'),
'product-category' => __('Product in category','Shopp'),
'customer-type' => __('Customer type is','Shopp')
);
echo Shopp::menuoptions($propertymenu,false,true);
?></script>
<script id="countries-menu" type="text/x-jquery-tmpl"><?php
echo Shopp::menuoptions($countries,false,true);
?></script>
<script id="conditional" type="text/x-jquery-tmpl">
<?php ob_start(); ?>
<li>
<?php echo ShoppUI::button('delete','deleterule'); ?>
<select name="settings[taxrates][${id}][rules][${ruleid}][p]" class="property">${property_menu}</select> <input type="text" name="settings[taxrates][${id}][rules][${ruleid}][v]" size="25" class="value" value="${rulevalue}" />
<?php echo ShoppUI::button('add','addrule'); ?></li>
<?php $conditional = ob_get_contents(); ob_end_clean(); echo str_replace(array("\n","\t"),'',$conditional); ?>
</script>
<script id="localrate" type="text/x-jquery-tmpl">
<?php ob_start(); ?>
<li><label title="${localename}"><input type="text" name="settings[taxrates][${id}][locals][${localename}]" size="6" value="${localerate}" /> ${localename}</label></li>
<?php $localrateui = ob_get_contents(); ob_end_clean(); echo $localrateui; ?>
</script>
<script id="editor" type="text/x-jquery-tmpl">
<?php ob_start(); ?>
<tr class="inline-edit-row ${classnames}" id="${id}">
<td colspan="5"><input type="hidden" name="id" value="${id}" /><input type="hidden" name="editing" value="true" />
<table id="taxrate-editor">
<tr>
<td scope="row" valign="top" class="rate"><input type="text" name="settings[taxrates][${id}][rate]" id="tax-rate" value="${rate}" size="7" class="selectall" tabindex="1" /><br /><label for="tax-rate"><?php _e('Tax Rate','Shopp'); ?></label><br />
<input type="hidden" name="settings[taxrates][${id}][compound]" value="off" /><label><input type="checkbox" id="tax-compound" name="settings[taxrates][${id}][compound]" value="on" ${compounded} tabindex="4" /> <?php Shopp::_e('Compound'); ?></label></td>
<td scope="row" class="conditions">
<select name="settings[taxrates][${id}][country]" class="country" tabindex="2">${countries}</select><select name="settings[taxrates][${id}][zone]" class="zone no-zones" tabindex="3">${zones}</select>
<?php echo ShoppUI::button('add','addrule'); ?>
<?php
$options = array('any' => Shopp::__('any'), 'all' => strtolower(Shopp::__('All')));
$menu = '<select name="settings[taxrates][${id}][logic]" class="logic">'.menuoptions($options,false,true).'</select>';
?>
<div class="conditionals no-conditions">
<p><label><?php printf(__('Apply tax rate when %s of the following conditions match','Shopp'),$menu); ?>:</label></p>
<ul>
${conditions}
</ul>
</div>
</td>
<td>
<div class="local-rates panel subpanel no-local-rates">
<div class="label"><label><?php _e('Local Rates','Shopp'); echo ShoppAdmin()->boxhelp('settings-taxes-localrates'); ?> <span class="counter"></span><input type="hidden" name="settings[taxrates][${id}][haslocals]" value="${haslocals}" class="has-locals" /></label></div>
<div class="ui">
<p class="instructions"><?php Shopp::_e('No local regions have been setup for this location. Local regions can be specified by uploading a formatted local rates file.'); ?></p>
${errors}
<ul>${localrates}</ul>
<div class="upload">
<h3><?php Shopp::_e('Upload Local Tax Rates'); ?></h3>
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
<input type="file" name="ratefile" class="hide-if-js" />
<button type="submit" name="upload" class="button-secondary upload"><?php Shopp::_e('Upload'); ?></button>
</div>
</div>
</div>
</td>
</tr>
<tr>
<td colspan="3">
<p class="textright">
<a href="<?php echo $this->url; ?>" class="button-secondary cancel alignleft"><?php Shopp::_e('Cancel'); ?></a>
<button type="submit" name="add-locals" class="button-secondary locals-toggle add-locals has-local-rates"><?php Shopp::_e('Add Local Rates'); ?></button>
<button type="submit" name="remove-locals" class="button-secondary locals-toggle rm-locals no-local-rates"><?php Shopp::_e('Remove Local Rates'); ?></button>
<input type="submit" class="button-primary" name="submit" value="<?php Shopp::_e('Save Changes'); ?>" />
</p>
</td>
</tr>
</table>
</td>
</tr>
<?php $editor = ob_get_contents(); ob_end_clean(); echo str_replace(array("\n","\t"),'',$editor); ?>
</script>
<table class="widefat" cellspacing="0">
<thead>
<tr><?php print_column_headers('shopp_page_shopp-settings-taxrates'); ?></tr>
</thead>
<tfoot>
<tr><?php print_column_headers('shopp_page_shopp-settings-taxrates',false); ?></tr>
</tfoot>
<tbody id="taxrates-table" class="list">
<?php
if ($edit !== false && !isset($rates[$edit])) {
$defaults = array(
'rate' => 0,
'country' => false,
'zone' => false,
'rules' => array(),
'locals' => array(),
'haslocals' => false,
'compound' => false
);
extract($defaults);
echo ShoppUI::template($editor,array(
'${id}' => $edit,
'${rate}' => percentage($rate,array('precision'=>4)),
'${countries}' => menuoptions($countries,$country,true),
'${zones}' => !empty($zones[$country])?menuoptions($zones[$country],$zone,true):'',
'${conditions}' => join('',$conditions),
'${haslocals}' => $haslocals,
'${localrates}' => join('',$localrates),
'${instructions}' => $localerror ? '<p class="error">'.$localerror.'</p>' : $instructions,
'${compounded}' => Shopp::str_true($compound) ? 'checked="checked"' : ''
));
}
if (count($rates) == 0 && $edit === false): ?>
<tr id="no-taxrates"><td colspan="5"><?php _e('No tax rates, yet.','Shopp'); ?></td></tr>
<?php
endif;
$hidden = get_hidden_columns('shopp_page_shopp-settings-taxrates');
$even = false;
foreach ($rates as $index => $taxrate):
$defaults = array(
'rate' => 0,
'country' => false,
'zone' => false,
'rules' => array(),
'locals' => array(),
'haslocals' => false
);
$taxrate = array_merge($defaults,$taxrate);
extract($taxrate);
$rate = Shopp::percentage(Shopp::floatval($rate), array('precision'=>4));
$location = $countries[ $country ];
if (isset($zone) && !empty($zone))
$location = $zones[$country][$zone].", $location";
$editurl = wp_nonce_url(add_query_arg(array('id'=>$index),$this->url));
$deleteurl = wp_nonce_url(add_query_arg(array('delete'=>$index),$this->url),'shopp_delete_taxrate');
$classes = array();
if (!$even) $classes[] = 'alternate'; $even = !$even;
if ($edit !== false && $edit === $index) {
$conditions = array();
foreach ($rules as $ruleid => $rule) {
$condition_template_data = array(
'${id}' => $edit,
'${ruleid}' => $ruleid,
'${property_menu}' => menuoptions($propertymenu,$rule['p'],true),
'${rulevalue}' => esc_attr($rule['v'])
);
$conditions[] = str_replace(array_keys($condition_template_data),$condition_template_data,$conditional);
}
$localrates = array();
foreach ($locals as $localename => $localerate) {
$localrateui_data = array(
'${id}' => $edit,
'${localename}' => $localename,
'${localerate}' => (float)$localerate,
);
$localrates[] = str_replace(array_keys($localrateui_data),$localrateui_data,$localrateui);
}
$data = array(
'${id}' => $edit,
'${rate}' => $rate,
'${countries}' => menuoptions($countries,$country,true),
'${zones}' => !empty($zones[$country])?menuoptions(array_merge(array(''=>''),$zones[$country]),$zone,true):'',
'${conditions}' => join('',$conditions),
'${haslocals}' => $haslocals,
'${localrates}' => join('',$localrates),
'${errors}' => $localerror ? '<p class="error">'.$localerror.'</p>' : '',
'${compounded}' => Shopp::str_true($compound) ? 'checked="checked"' : '',
'${cancel_href}' => $this->url
);
if ($conditions) $data['no-conditions'] = '';
if (!empty($zones[$country])) $data['no-zones'] = '';
if ($haslocals) $data['no-local-rates'] = '';
else $data['has-local-rates'] = '';
if (count($locals) > 0) $data['instructions'] = 'hidden';
echo ShoppUI::template($editor,$data);
if ($edit === $index) continue;
}
$label = "$rate — $location";
?>
<tr class="<?php echo join(' ',$classes); ?>" id="taxrates-<?php echo $index; ?>">
<td class="name column-name"><a href="<?php echo esc_url($editurl); ?>" title="<?php _e('Edit','Shopp'); ?> "<?php echo esc_attr($rate); ?>"" class="edit row-title"><?php echo esc_html($label); ?></a>
<div class="row-actions">
<span class='edit'><a href="<?php echo esc_url($editurl); ?>" title="<?php _e('Edit','Shopp'); ?> "<?php echo esc_attr($label); ?>"" class="edit"><?php _e('Edit','Shopp'); ?></a> | </span><span class='delete'><a href="<?php echo esc_url($deleteurl); ?>" title="<?php _e('Delete','Shopp'); ?> "<?php echo esc_attr($label); ?>"" class="delete"><?php _e('Delete','Shopp'); ?></a></span>
</div>
</td>
<td class="local column-local">
<div class="checkbox <?php if ( $haslocals ) echo 'checked'; ?>"> </div>
</td>
<td class="conditional column-conditional">
<div class="checkbox <?php if ( count($rules) > 0 ) echo 'checked'; ?>"> </div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</form>
</div>
<script type="text/javascript">
/* <![CDATA[ */
var suggurl = '<?php echo wp_nonce_url(admin_url('admin-ajax.php'),'wp_ajax_shopp_suggestions'); ?>',
rates = <?php echo json_encode($rates); ?>,
base = <?php echo json_encode($base); ?>,
zones = <?php echo json_encode($zones); ?>,
localities = <?php echo json_encode(Lookup::localities()); ?>,
taxrates = [];
/* ]]> */
</script>
| sharpmachine/greaterworkshealing.com | wp-content/plugins/shopp/core/ui/settings/taxrates.php | PHP | gpl-2.0 | 10,968 |
/******************************************************************************/
/* Mednafen Fast SNES Emulation Module */
/******************************************************************************/
/* input.cpp:
** Copyright (C) 2015-2019 Mednafen Team
**
** 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.
*/
#include "snes.h"
#include "input.h"
namespace MDFN_IEN_SNES_FAUST
{
class InputDevice
{
public:
InputDevice() MDFN_COLD;
virtual ~InputDevice() MDFN_COLD;
virtual void Power(void) MDFN_COLD;
virtual void MDFN_FASTCALL UpdatePhysicalState(const uint8* data);
virtual uint8 MDFN_FASTCALL Read(bool IOB) MDFN_HOT;
virtual void MDFN_FASTCALL SetLatch(bool state) MDFN_HOT;
virtual void StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix);
};
InputDevice::InputDevice()
{
}
InputDevice::~InputDevice()
{
}
void InputDevice::Power(void)
{
}
void InputDevice::UpdatePhysicalState(const uint8* data)
{
}
uint8 InputDevice::Read(bool IOB)
{
return 0;
}
void InputDevice::SetLatch(bool state)
{
}
void InputDevice::StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix)
{
}
class InputDevice_MTap final : public InputDevice
{
public:
InputDevice_MTap() MDFN_COLD;
virtual ~InputDevice_MTap() override MDFN_COLD;
virtual void Power(void) override MDFN_COLD;
virtual uint8 MDFN_FASTCALL Read(bool IOB) override MDFN_HOT;
virtual void MDFN_FASTCALL SetLatch(bool state) override MDFN_HOT;
virtual void StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix) override;
void SetSubDevice(const unsigned mport, InputDevice* device);
private:
InputDevice* MPorts[4];
bool pls;
};
void InputDevice_MTap::Power(void)
{
for(unsigned mport = 0; mport < 4; mport++)
MPorts[mport]->Power();
}
void InputDevice_MTap::StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix)
{
SFORMAT StateRegs[] =
{
SFVAR(pls),
SFEND
};
char sname[64] = "MT_";
strncpy(sname + 3, sname_prefix, sizeof(sname) - 3);
sname[sizeof(sname) - 1] = 0;
if(!MDFNSS_StateAction(sm, load, data_only, StateRegs, sname, true) && load)
Power();
else
{
for(unsigned mport = 0; mport < 4; mport++)
{
sname[2] = '0' + mport;
MPorts[mport]->StateAction(sm, load, data_only, sname);
}
if(load)
{
}
}
}
InputDevice_MTap::InputDevice_MTap()
{
for(unsigned mport = 0; mport < 4; mport++)
MPorts[mport] = nullptr;
pls = false;
}
InputDevice_MTap::~InputDevice_MTap()
{
}
uint8 InputDevice_MTap::Read(bool IOB)
{
uint8 ret;
ret = ((MPorts[(!IOB << 1) + 0]->Read(false) & 0x1) << 0) | ((MPorts[(!IOB << 1) + 1]->Read(false) & 0x1) << 1);
if(pls)
ret = 0x2;
return ret;
}
void InputDevice_MTap::SetLatch(bool state)
{
for(unsigned mport = 0; mport < 4; mport++)
MPorts[mport]->SetLatch(state);
pls = state;
}
void InputDevice_MTap::SetSubDevice(const unsigned mport, InputDevice* device)
{
MPorts[mport] = device;
}
class InputDevice_Gamepad final : public InputDevice
{
public:
InputDevice_Gamepad() MDFN_COLD;
virtual ~InputDevice_Gamepad() override MDFN_COLD;
virtual void Power(void) override MDFN_COLD;
virtual void MDFN_FASTCALL UpdatePhysicalState(const uint8* data) override;
virtual uint8 MDFN_FASTCALL Read(bool IOB) override MDFN_HOT;
virtual void MDFN_FASTCALL SetLatch(bool state) override MDFN_HOT;
virtual void StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix) override;
private:
uint16 buttons;
uint32 latched;
bool pls;
};
InputDevice_Gamepad::InputDevice_Gamepad()
{
pls = false;
buttons = 0;
}
InputDevice_Gamepad::~InputDevice_Gamepad()
{
}
void InputDevice_Gamepad::StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix)
{
SFORMAT StateRegs[] =
{
SFVAR(buttons),
SFVAR(latched),
SFVAR(pls),
SFEND
};
char sname[64] = "GP_";
strncpy(sname + 3, sname_prefix, sizeof(sname) - 3);
sname[sizeof(sname) - 1] = 0;
//printf("%s\n", sname);
if(!MDFNSS_StateAction(sm, load, data_only, StateRegs, sname, true) && load)
Power();
else if(load)
{
}
}
void InputDevice_Gamepad::Power(void)
{
latched = ~0U;
}
void InputDevice_Gamepad::UpdatePhysicalState(const uint8* data)
{
buttons = MDFN_de16lsb(data);
if(pls)
latched = buttons | 0xFFFF0000;
}
uint8 InputDevice_Gamepad::Read(bool IOB)
{
uint8 ret = latched & 1;
if(!pls)
latched = (int32)latched >> 1;
return ret;
}
void InputDevice_Gamepad::SetLatch(bool state)
{
if(pls && !state)
latched = buttons | 0xFFFF0000;
pls = state;
}
//
//
//
//
//
static struct
{
InputDevice_Gamepad gamepad;
} PossibleDevices[8];
static InputDevice NoneDevice;
static InputDevice_MTap PossibleMTaps[2];
static bool MTapEnabled[2];
// Mednafen virtual
static InputDevice* Devices[8];
static uint8* DeviceData[8];
// SNES physical
static InputDevice* Ports[2];
static uint8 WRIO;
static bool JoyLS;
static uint8 JoyARData[8];
static DEFREAD(Read_JoyARData)
{
if(MDFN_UNLIKELY(DBG_InHLRead))
{
return JoyARData[A & 0x7];
}
CPUM.timestamp += MEMCYC_FAST;
//printf("Read: %08x\n", A);
return JoyARData[A & 0x7];
}
static DEFREAD(Read_4016)
{
if(MDFN_UNLIKELY(DBG_InHLRead))
{
return CPUM.mdr & 0xFC; // | TODO!
}
CPUM.timestamp += MEMCYC_XSLOW;
uint8 ret = CPUM.mdr & 0xFC;
ret |= Ports[0]->Read(WRIO & (0x40 << 0));
//printf("Read 4016: %02x\n", ret);
return ret;
}
static DEFWRITE(Write_4016)
{
CPUM.timestamp += MEMCYC_XSLOW;
JoyLS = V & 1;
for(unsigned sport = 0; sport < 2; sport++)
Ports[sport]->SetLatch(JoyLS);
//printf("Write 4016: %02x\n", V);
}
static DEFREAD(Read_4017)
{
if(MDFN_UNLIKELY(DBG_InHLRead))
{
return (CPUM.mdr & 0xE0) | 0x1C; // | TODO!
}
CPUM.timestamp += MEMCYC_XSLOW;
uint8 ret = (CPUM.mdr & 0xE0) | 0x1C;
ret |= Ports[1]->Read(WRIO & (0x40 << 1));
//printf("Read 4017: %02x\n", ret);
return ret;
}
static DEFWRITE(Write_WRIO)
{
CPUM.timestamp += MEMCYC_FAST;
WRIO = V;
}
static DEFREAD(Read_4213)
{
if(MDFN_UNLIKELY(DBG_InHLRead))
{
return WRIO;
}
CPUM.timestamp += MEMCYC_FAST;
return WRIO;
}
void INPUT_AutoRead(void)
{
for(unsigned sport = 0; sport < 2; sport++)
{
Ports[sport]->SetLatch(true);
Ports[sport]->SetLatch(false);
unsigned ard[2] = { 0 };
for(unsigned b = 0; b < 16; b++)
{
uint8 rv = Ports[sport]->Read(WRIO & (0x40 << sport));
ard[0] = (ard[0] << 1) | ((rv >> 0) & 1);
ard[1] = (ard[1] << 1) | ((rv >> 1) & 1);
}
for(unsigned ai = 0; ai < 2; ai++)
MDFN_en16lsb(&JoyARData[sport * 2 + ai * 4], ard[ai]);
}
JoyLS = false;
}
static MDFN_COLD void MapDevices(void)
{
for(unsigned sport = 0, vport = 0; sport < 2; sport++)
{
if(MTapEnabled[sport])
{
Ports[sport] = &PossibleMTaps[sport];
for(unsigned mport = 0; mport < 4; mport++)
PossibleMTaps[sport].SetSubDevice(mport, Devices[vport++]);
}
else
Ports[sport] = Devices[vport++];
}
}
void INPUT_Init(void)
{
for(unsigned bank = 0x00; bank < 0x100; bank++)
{
if(bank <= 0x3F || (bank >= 0x80 && bank <= 0xBF))
{
Set_A_Handlers((bank << 16) | 0x4016, Read_4016, Write_4016);
Set_A_Handlers((bank << 16) | 0x4017, Read_4017, OBWrite_XSLOW);
Set_A_Handlers((bank << 16) | 0x4201, OBRead_FAST, Write_WRIO);
Set_A_Handlers((bank << 16) | 0x4213, Read_4213, OBWrite_FAST);
Set_A_Handlers((bank << 16) | 0x4218, (bank << 16) | 0x421F, Read_JoyARData, OBWrite_FAST);
}
}
for(unsigned vport = 0; vport < 8; vport++)
{
DeviceData[vport] = nullptr;
Devices[vport] = &NoneDevice;
}
for(unsigned sport = 0; sport < 2; sport++)
for(unsigned mport = 0; mport < 4; mport++)
PossibleMTaps[sport].SetSubDevice(mport, &NoneDevice);
MTapEnabled[0] = MTapEnabled[1] = false;
MapDevices();
}
void INPUT_SetMultitap(const bool (&enabled)[2])
{
for(unsigned sport = 0; sport < 2; sport++)
{
if(enabled[sport] != MTapEnabled[sport])
{
PossibleMTaps[sport].SetLatch(JoyLS);
PossibleMTaps[sport].Power();
MTapEnabled[sport] = enabled[sport];
}
}
MapDevices();
}
void INPUT_Kill(void)
{
}
void INPUT_Reset(bool powering_up)
{
JoyLS = false;
for(unsigned sport = 0; sport < 2; sport++)
Ports[sport]->SetLatch(JoyLS);
memset(JoyARData, 0x00, sizeof(JoyARData));
if(powering_up)
{
WRIO = 0xFF;
for(unsigned sport = 0; sport < 2; sport++)
Ports[sport]->Power();
}
}
void INPUT_Set(unsigned vport, const char* type, uint8* ptr)
{
InputDevice* nd = &NoneDevice;
DeviceData[vport] = ptr;
if(!strcmp(type, "gamepad"))
nd = &PossibleDevices[vport].gamepad;
else if(strcmp(type, "none"))
abort();
if(Devices[vport] != nd)
{
Devices[vport] = nd;
Devices[vport]->SetLatch(JoyLS);
Devices[vport]->Power();
}
MapDevices();
}
void INPUT_StateAction(StateMem* sm, const unsigned load, const bool data_only)
{
SFORMAT StateRegs[] =
{
SFVAR(JoyARData),
SFVAR(JoyLS),
SFVAR(WRIO),
SFEND
};
MDFNSS_StateAction(sm, load, data_only, StateRegs, "INPUT");
for(unsigned sport = 0; sport < 2; sport++)
{
char sprefix[32] = "PORTn";
sprefix[4] = '0' + sport;
Ports[sport]->StateAction(sm, load, data_only, sprefix);
}
}
void INPUT_UpdatePhysicalState(void)
{
for(unsigned vport = 0; vport < 8; vport++)
Devices[vport]->UpdatePhysicalState(DeviceData[vport]);
}
static const IDIISG GamepadIDII =
{
IDIIS_ButtonCR("b", "B (center, lower)", 7, NULL),
IDIIS_ButtonCR("y", "Y (left)", 6, NULL),
IDIIS_Button("select", "SELECT", 4, NULL),
IDIIS_Button("start", "START", 5, NULL),
IDIIS_Button("up", "UP ↑", 0, "down"),
IDIIS_Button("down", "DOWN ↓", 1, "up"),
IDIIS_Button("left", "LEFT ←", 2, "right"),
IDIIS_Button("right", "RIGHT →", 3, "left"),
IDIIS_ButtonCR("a", "A (right)", 9, NULL),
IDIIS_ButtonCR("x", "X (center, upper)", 8, NULL),
IDIIS_Button("l", "Left Shoulder", 10, NULL),
IDIIS_Button("r", "Right Shoulder", 11, NULL),
};
static const std::vector<InputDeviceInfoStruct> InputDeviceInfo =
{
// None
{
"none",
"none",
NULL,
IDII_Empty
},
// Gamepad
{
"gamepad",
"Gamepad",
NULL,
GamepadIDII
},
};
const std::vector<InputPortInfoStruct> INPUT_PortInfo =
{
{ "port1", "Virtual Port 1", InputDeviceInfo, "gamepad" },
{ "port2", "Virtual Port 2", InputDeviceInfo, "gamepad" },
{ "port3", "Virtual Port 3", InputDeviceInfo, "gamepad" },
{ "port4", "Virtual Port 4", InputDeviceInfo, "gamepad" },
{ "port5", "Virtual Port 5", InputDeviceInfo, "gamepad" },
{ "port6", "Virtual Port 6", InputDeviceInfo, "gamepad" },
{ "port7", "Virtual Port 7", InputDeviceInfo, "gamepad" },
{ "port8", "Virtual Port 8", InputDeviceInfo, "gamepad" }
};
}
| libretro-mirrors/mednafen-git | src/snes_faust/input.cpp | C++ | gpl-2.0 | 11,450 |
<?php
class woocsvImport
{
public $importLog;
public $options;
public $header;
public $message;
public $options_default = array (
'seperator'=>',',
'skipfirstline'=>1,
'upload_dir' => '/csvimport/',
'blocksize' => 1,
'language' => 'EN',
'add_to_gallery' => 1,
'merge_products'=>1,
'add_to_categories'=>1,
'debug'=>0,
'match_by' => 'sku',
'roles' => array('shop_manager'),
'match_author_by' => 'login',
);
public $fields = array (
0 => 'sku',
1 => 'post_name',
2 => 'post_status',
3 => 'post_title',
4 => 'post_content',
5 => 'post_excerpt',
6 => 'category',
7 => 'tags',
8 => 'stock',
9 => 'price', /* ! 2.0.0 deprecated. Use regular_price or/and sale_price */
10 => 'regular_price',
11 => 'sale_price',
12 => 'weight' ,
13 => 'length',
14 => 'width' ,
15 => 'height' ,
//2.1.0 16 => 'images', //deprecated since 1.2.0, will be removed in 1.4.0
17 => 'tax_status',
18 => 'tax_class' ,
19 => 'stock_status', // instock, outofstock
20 => 'visibility', // visible, catelog, search, hidden
21 => 'backorders', // yes,no
22 => 'featured', // yes,no
23 => 'manage_stock', // yes,no
24 => 'featured_image',
25 => 'product_gallery',
26 => 'shipping_class',
27 => 'comment_status', //closed, open
28 => 'change_stock', // +1 -1 + 5 -8
29 =>'ID',
30 =>'ping_status',
31 => 'menu_order', // open,closed
32 => 'post_author', //user name or nice name of an user
);
public function __construct()
{
// activation hook
register_activation_hook( __FILE__, array($this, 'install' ));
//check install
$this->checkInstall();
//load options
$this->checkOptions();
//fill header
$this->fillHeader();
}
/* !1.2.7 plugins url */
public function plugin_url() {
if ( $this->plugin_url ) return $this->plugin_url;
return $this->plugin_url = untrailingslashit( plugins_url( '/', __FILE__ ) );
}
public function install()
{
$upload_dir = wp_upload_dir();
$dir = $upload_dir['basedir'] .'/csvimport/';
@mkdir($dir);
}
public function fillHeader() {
$header = get_option('woocsv-header');
if (!empty($header))
$this->header = $header;
}
public function checkOptions()
{
$update = false;
$options = get_option('woocsv-options');
$options_default = $this->options_default;
foreach ($options_default as $key=>$value) {
if (!isset($options[$key])) {
$options[$key] = $value;
$update = true;
}
}
if ($update) {
update_option('woocsv-options',$options);
}
$options = get_option('woocsv-options');
$this->options = $options;
}
public function checkInstall()
{
$message = $this->message;
if (!get_option('woocsv-options'))
$message .= __('Please save your settings!','woocsv-import');
$upload_dir = wp_upload_dir();
$dir = $upload_dir['basedir'] .'/csvimport/';
if (!is_dir($dir))
@mkdir($dir);
if (!is_writable($upload_dir['basedir'] .'/csvimport/'))
$message .= __('Upload directory is not writable, please check you permissions','woocsv-import');
$this->message = $message;
if ($message)
add_action( 'admin_notices', array($this, 'showWarning'));
}
public function showWarning()
{
global $current_screen;
if ($current_screen->parent_base == 'woocsv_import' )
echo '<div class="error"><p>'.$this->message.'</p></div>';
}
} | ilfungo/bts | wp-content/plugins/woocommerce-csvimport/include/class-woocsv-csvimport.php | PHP | gpl-2.0 | 3,360 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form\Tests\Extension\Core\Type;
use Symfony\Component\Form\ChoiceList\View\ChoiceView;
use Symfony\Component\Form\FormError;
use Symfony\Component\Intl\Util\IntlTestHelper;
class DateTypeTest extends BaseTypeTest
{
const TESTED_TYPE = 'date';
private $defaultTimezone;
protected function setUp()
{
parent::setUp();
$this->defaultTimezone = date_default_timezone_get();
}
protected function tearDown()
{
date_default_timezone_set($this->defaultTimezone);
\Locale::setDefault('en');
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testInvalidWidgetOption()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'fake_widget',
));
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testInvalidInputOption()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'input' => 'fake_input',
));
}
public function testSubmitFromSingleTextDateTimeWithDefaultFormat()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'single_text',
'input' => 'datetime',
));
$form->submit('2010-06-02');
$this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $form->getData());
$this->assertEquals('2010-06-02', $form->getViewData());
}
public function testSubmitFromSingleTextDateTimeWithCustomFormat()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'single_text',
'input' => 'datetime',
'format' => 'yyyy',
));
$form->submit('2010');
$this->assertDateTimeEquals(new \DateTime('2010-01-01 UTC'), $form->getData());
$this->assertEquals('2010', $form->getViewData());
}
public function testSubmitFromSingleTextDateTime()
{
// we test against "de_DE", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_DE');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => \IntlDateFormatter::MEDIUM,
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'single_text',
'input' => 'datetime',
));
$form->submit('2.6.2010');
$this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $form->getData());
$this->assertEquals('02.06.2010', $form->getViewData());
}
public function testSubmitFromSingleTextString()
{
// we test against "de_DE", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_DE');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => \IntlDateFormatter::MEDIUM,
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'single_text',
'input' => 'string',
));
$form->submit('2.6.2010');
$this->assertEquals('2010-06-02', $form->getData());
$this->assertEquals('02.06.2010', $form->getViewData());
}
public function testSubmitFromSingleTextTimestamp()
{
// we test against "de_DE", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_DE');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => \IntlDateFormatter::MEDIUM,
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'single_text',
'input' => 'timestamp',
));
$form->submit('2.6.2010');
$dateTime = new \DateTime('2010-06-02 UTC');
$this->assertEquals($dateTime->format('U'), $form->getData());
$this->assertEquals('02.06.2010', $form->getViewData());
}
public function testSubmitFromSingleTextRaw()
{
// we test against "de_DE", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_DE');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => \IntlDateFormatter::MEDIUM,
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'single_text',
'input' => 'array',
));
$form->submit('2.6.2010');
$output = array(
'day' => '2',
'month' => '6',
'year' => '2010',
);
$this->assertEquals($output, $form->getData());
$this->assertEquals('02.06.2010', $form->getViewData());
}
public function testSubmitFromText()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'text',
));
$text = array(
'day' => '2',
'month' => '6',
'year' => '2010',
);
$form->submit($text);
$dateTime = new \DateTime('2010-06-02 UTC');
$this->assertDateTimeEquals($dateTime, $form->getData());
$this->assertEquals($text, $form->getViewData());
}
public function testSubmitFromChoice()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'choice',
'years' => array(2010),
));
$text = array(
'day' => '2',
'month' => '6',
'year' => '2010',
);
$form->submit($text);
$dateTime = new \DateTime('2010-06-02 UTC');
$this->assertDateTimeEquals($dateTime, $form->getData());
$this->assertEquals($text, $form->getViewData());
}
public function testSubmitFromChoiceEmpty()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'choice',
'required' => false,
));
$text = array(
'day' => '',
'month' => '',
'year' => '',
);
$form->submit($text);
$this->assertNull($form->getData());
$this->assertEquals($text, $form->getViewData());
}
public function testSubmitFromInputDateTimeDifferentPattern()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'format' => 'MM*yyyy*dd',
'widget' => 'single_text',
'input' => 'datetime',
));
$form->submit('06*2010*02');
$this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $form->getData());
$this->assertEquals('06*2010*02', $form->getViewData());
}
public function testSubmitFromInputStringDifferentPattern()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'format' => 'MM*yyyy*dd',
'widget' => 'single_text',
'input' => 'string',
));
$form->submit('06*2010*02');
$this->assertEquals('2010-06-02', $form->getData());
$this->assertEquals('06*2010*02', $form->getViewData());
}
public function testSubmitFromInputTimestampDifferentPattern()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'format' => 'MM*yyyy*dd',
'widget' => 'single_text',
'input' => 'timestamp',
));
$form->submit('06*2010*02');
$dateTime = new \DateTime('2010-06-02 UTC');
$this->assertEquals($dateTime->format('U'), $form->getData());
$this->assertEquals('06*2010*02', $form->getViewData());
}
public function testSubmitFromInputRawDifferentPattern()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'format' => 'MM*yyyy*dd',
'widget' => 'single_text',
'input' => 'array',
));
$form->submit('06*2010*02');
$output = array(
'day' => '2',
'month' => '6',
'year' => '2010',
);
$this->assertEquals($output, $form->getData());
$this->assertEquals('06*2010*02', $form->getViewData());
}
/**
* @dataProvider provideDateFormats
*/
public function testDatePatternWithFormatOption($format, $pattern)
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => $format,
))
->createView();
$this->assertEquals($pattern, $view->vars['date_pattern']);
}
public function provideDateFormats()
{
return array(
array('dMy', '{{ day }}{{ month }}{{ year }}'),
array('d-M-yyyy', '{{ day }}-{{ month }}-{{ year }}'),
array('M d y', '{{ month }} {{ day }} {{ year }}'),
);
}
/**
* This test is to check that the strings '0', '1', '2', '3' are not accepted
* as valid IntlDateFormatter constants for FULL, LONG, MEDIUM or SHORT respectively.
*
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testThrowExceptionIfFormatIsNoPattern()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'format' => '0',
'widget' => 'single_text',
'input' => 'string',
));
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
* @expectedExceptionMessage The "format" option should contain the letters "y", "M" and "d". Its current value is "yy".
*/
public function testThrowExceptionIfFormatDoesNotContainYearMonthAndDay()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'months' => array(6, 7),
'format' => 'yy',
));
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
* @expectedExceptionMessage The "format" option should contain the letters "y", "M" or "d". Its current value is "wrong".
*/
public function testThrowExceptionIfFormatMissesYearMonthAndDayWithSingleTextWidget()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'single_text',
'format' => 'wrong',
));
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testThrowExceptionIfFormatIsNoConstant()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'format' => 105,
));
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testThrowExceptionIfFormatIsInvalid()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'format' => array(),
));
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testThrowExceptionIfYearsIsInvalid()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'years' => 'bad value',
));
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testThrowExceptionIfMonthsIsInvalid()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'months' => 'bad value',
));
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testThrowExceptionIfDaysIsInvalid()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'days' => 'bad value',
));
}
public function testSetDataWithNegativeTimezoneOffsetStringInput()
{
// we test against "de_DE", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_DE');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => \IntlDateFormatter::MEDIUM,
'model_timezone' => 'UTC',
'view_timezone' => 'America/New_York',
'input' => 'string',
'widget' => 'single_text',
));
$form->setData('2010-06-02');
// 2010-06-02 00:00:00 UTC
// 2010-06-01 20:00:00 UTC-4
$this->assertEquals('01.06.2010', $form->getViewData());
}
public function testSetDataWithNegativeTimezoneOffsetDateTimeInput()
{
// we test against "de_DE", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_DE');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => \IntlDateFormatter::MEDIUM,
'model_timezone' => 'UTC',
'view_timezone' => 'America/New_York',
'input' => 'datetime',
'widget' => 'single_text',
));
$dateTime = new \DateTime('2010-06-02 UTC');
$form->setData($dateTime);
// 2010-06-02 00:00:00 UTC
// 2010-06-01 20:00:00 UTC-4
$this->assertDateTimeEquals($dateTime, $form->getData());
$this->assertEquals('01.06.2010', $form->getViewData());
}
public function testYearsOption()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'years' => array(2010, 2011),
));
$view = $form->createView();
$this->assertEquals(array(
new ChoiceView('2010', '2010', '2010'),
new ChoiceView('2011', '2011', '2011'),
), $view['year']->vars['choices']);
}
public function testMonthsOption()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'months' => array(6, 7),
'format' => \IntlDateFormatter::SHORT,
));
$view = $form->createView();
$this->assertEquals(array(
new ChoiceView(6, '6', '06'),
new ChoiceView(7, '7', '07'),
), $view['month']->vars['choices']);
}
public function testMonthsOptionShortFormat()
{
// we test against "de_AT", so we need the full implementation
IntlTestHelper::requireFullIntl($this, '57.1');
\Locale::setDefault('de_AT');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'months' => array(1, 4),
'format' => 'dd.MMM.yy',
));
$view = $form->createView();
$this->assertEquals(array(
new ChoiceView(1, '1', 'Jän.'),
new ChoiceView(4, '4', 'Apr.'),
), $view['month']->vars['choices']);
}
public function testMonthsOptionLongFormat()
{
// we test against "de_AT", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_AT');
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'months' => array(1, 4),
'format' => 'dd.MMMM.yy',
))
->createView();
$this->assertEquals(array(
new ChoiceView(1, '1', 'Jänner'),
new ChoiceView(4, '4', 'April'),
), $view['month']->vars['choices']);
}
public function testMonthsOptionLongFormatWithDifferentTimezone()
{
// we test against "de_AT", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_AT');
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'months' => array(1, 4),
'format' => 'dd.MMMM.yy',
))
->createView();
$this->assertEquals(array(
new ChoiceView(1, '1', 'Jänner'),
new ChoiceView(4, '4', 'April'),
), $view['month']->vars['choices']);
}
public function testIsDayWithinRangeReturnsTrueIfWithin()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'days' => array(6, 7),
))
->createView();
$this->assertEquals(array(
new ChoiceView(6, '6', '06'),
new ChoiceView(7, '7', '07'),
), $view['day']->vars['choices']);
}
public function testIsSynchronizedReturnsTrueIfChoiceAndCompletelyEmpty()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'choice',
));
$form->submit(array(
'day' => '',
'month' => '',
'year' => '',
));
$this->assertTrue($form->isSynchronized());
}
public function testIsSynchronizedReturnsTrueIfChoiceAndCompletelyFilled()
{
$form = $this->factory->create(static::TESTED_TYPE, new \DateTime(), array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'choice',
));
$form->submit(array(
'day' => '1',
'month' => '6',
'year' => '2010',
));
$this->assertTrue($form->isSynchronized());
}
public function testIsSynchronizedReturnsFalseIfChoiceAndDayEmpty()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'choice',
));
$form->submit(array(
'day' => '',
'month' => '6',
'year' => '2010',
));
$this->assertFalse($form->isSynchronized());
}
public function testPassDatePatternToView()
{
// we test against "de_AT", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_AT');
$view = $this->factory->create(static::TESTED_TYPE)
->createView();
$this->assertSame('{{ day }}{{ month }}{{ year }}', $view->vars['date_pattern']);
}
public function testPassDatePatternToViewDifferentFormat()
{
// we test against "de_AT", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_AT');
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => \IntlDateFormatter::LONG,
))
->createView();
$this->assertSame('{{ day }}{{ month }}{{ year }}', $view->vars['date_pattern']);
}
public function testPassDatePatternToViewDifferentPattern()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => 'MMyyyydd',
))
->createView();
$this->assertSame('{{ month }}{{ year }}{{ day }}', $view->vars['date_pattern']);
}
public function testPassDatePatternToViewDifferentPatternWithSeparators()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => 'MM*yyyy*dd',
))
->createView();
$this->assertSame('{{ month }}*{{ year }}*{{ day }}', $view->vars['date_pattern']);
}
public function testDontPassDatePatternIfText()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'single_text',
))
->createView();
$this->assertFalse(isset($view->vars['date_pattern']));
}
public function testDatePatternFormatWithQuotedStrings()
{
// we test against "es_ES", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('es_ES');
$view = $this->factory->create(static::TESTED_TYPE, null, array(
// EEEE, d 'de' MMMM 'de' y
'format' => \IntlDateFormatter::FULL,
))
->createView();
$this->assertEquals('{{ day }}{{ month }}{{ year }}', $view->vars['date_pattern']);
}
public function testPassWidgetToView()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'single_text',
))
->createView();
$this->assertSame('single_text', $view->vars['widget']);
}
public function testInitializeWithDateTime()
{
// Throws an exception if "data_class" option is not explicitly set
// to null in the type
$this->assertInstanceOf('Symfony\Component\Form\FormInterface', $this->factory->create(static::TESTED_TYPE, new \DateTime()));
}
public function testSingleTextWidgetShouldUseTheRightInputType()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'single_text',
))
->createView();
$this->assertEquals('date', $view->vars['type']);
}
public function testPassDefaultPlaceholderToViewIfNotRequired()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'required' => false,
))
->createView();
$this->assertSame('', $view['year']->vars['placeholder']);
$this->assertSame('', $view['month']->vars['placeholder']);
$this->assertSame('', $view['day']->vars['placeholder']);
}
public function testPassNoPlaceholderToViewIfRequired()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'required' => true,
))
->createView();
$this->assertNull($view['year']->vars['placeholder']);
$this->assertNull($view['month']->vars['placeholder']);
$this->assertNull($view['day']->vars['placeholder']);
}
public function testPassPlaceholderAsString()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'placeholder' => 'Empty',
))
->createView();
$this->assertSame('Empty', $view['year']->vars['placeholder']);
$this->assertSame('Empty', $view['month']->vars['placeholder']);
$this->assertSame('Empty', $view['day']->vars['placeholder']);
}
/**
* @group legacy
*/
public function testPassEmptyValueBC()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'empty_value' => 'Empty',
))
->createView();
$this->assertSame('Empty', $view['year']->vars['placeholder']);
$this->assertSame('Empty', $view['month']->vars['placeholder']);
$this->assertSame('Empty', $view['day']->vars['placeholder']);
$this->assertSame('Empty', $view['year']->vars['empty_value']);
$this->assertSame('Empty', $view['month']->vars['empty_value']);
$this->assertSame('Empty', $view['day']->vars['empty_value']);
}
public function testPassPlaceholderAsArray()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'placeholder' => array(
'year' => 'Empty year',
'month' => 'Empty month',
'day' => 'Empty day',
),
))
->createView();
$this->assertSame('Empty year', $view['year']->vars['placeholder']);
$this->assertSame('Empty month', $view['month']->vars['placeholder']);
$this->assertSame('Empty day', $view['day']->vars['placeholder']);
}
public function testPassPlaceholderAsPartialArrayAddEmptyIfNotRequired()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'required' => false,
'placeholder' => array(
'year' => 'Empty year',
'day' => 'Empty day',
),
))
->createView();
$this->assertSame('Empty year', $view['year']->vars['placeholder']);
$this->assertSame('', $view['month']->vars['placeholder']);
$this->assertSame('Empty day', $view['day']->vars['placeholder']);
}
public function testPassPlaceholderAsPartialArrayAddNullIfRequired()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'required' => true,
'placeholder' => array(
'year' => 'Empty year',
'day' => 'Empty day',
),
))
->createView();
$this->assertSame('Empty year', $view['year']->vars['placeholder']);
$this->assertNull($view['month']->vars['placeholder']);
$this->assertSame('Empty day', $view['day']->vars['placeholder']);
}
public function testPassHtml5TypeIfSingleTextAndHtml5Format()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'single_text',
))
->createView();
$this->assertSame('date', $view->vars['type']);
}
public function testDontPassHtml5TypeIfHtml5NotAllowed()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'single_text',
'html5' => false,
))
->createView();
$this->assertFalse(isset($view->vars['type']));
}
public function testDontPassHtml5TypeIfNotHtml5Format()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'single_text',
'format' => \IntlDateFormatter::MEDIUM,
))
->createView();
$this->assertFalse(isset($view->vars['type']));
}
public function testDontPassHtml5TypeIfNotSingleText()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'text',
))
->createView();
$this->assertFalse(isset($view->vars['type']));
}
public function provideCompoundWidgets()
{
return array(
array('text'),
array('choice'),
);
}
/**
* @dataProvider provideCompoundWidgets
*/
public function testYearErrorsBubbleUp($widget)
{
$error = new FormError('Invalid!');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => $widget,
));
$form['year']->addError($error);
$this->assertSame(array(), iterator_to_array($form['year']->getErrors()));
$this->assertSame(array($error), iterator_to_array($form->getErrors()));
}
/**
* @dataProvider provideCompoundWidgets
*/
public function testMonthErrorsBubbleUp($widget)
{
$error = new FormError('Invalid!');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => $widget,
));
$form['month']->addError($error);
$this->assertSame(array(), iterator_to_array($form['month']->getErrors()));
$this->assertSame(array($error), iterator_to_array($form->getErrors()));
}
/**
* @dataProvider provideCompoundWidgets
*/
public function testDayErrorsBubbleUp($widget)
{
$error = new FormError('Invalid!');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => $widget,
));
$form['day']->addError($error);
$this->assertSame(array(), iterator_to_array($form['day']->getErrors()));
$this->assertSame(array($error), iterator_to_array($form->getErrors()));
}
public function testYearsFor32BitsMachines()
{
if (4 !== PHP_INT_SIZE) {
$this->markTestSkipped('PHP 32 bit is required.');
}
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'years' => range(1900, 2040),
))
->createView();
$listChoices = array();
foreach (range(1902, 2037) as $y) {
$listChoices[] = new ChoiceView($y, $y, $y);
}
$this->assertEquals($listChoices, $view['year']->vars['choices']);
}
public function testSubmitNull($expected = null, $norm = null, $view = null)
{
parent::testSubmitNull($expected, $norm, array('year' => '', 'month' => '', 'day' => ''));
}
public function testSubmitNullWithSingleText()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'single_text',
));
$form->submit(null);
$this->assertNull($form->getData());
$this->assertNull($form->getNormData());
$this->assertSame('', $form->getViewData());
}
}
| kikutou/rentalmotor | vendor/symfony/form/Tests/Extension/Core/Type/DateTypeTest.php | PHP | gpl-2.0 | 29,797 |
module Katello
module UINotifications
module Subscriptions
class SCADisableSuccess < UINotifications::AbstractNotification
private
def blueprint
@blueprint ||= NotificationBlueprint.find_by(name: 'sca_disable_success')
end
end
end
end
end
| snagoor/katello | app/services/katello/ui_notifications/subscriptions/sca_disable_success.rb | Ruby | gpl-2.0 | 298 |
<?php
namespace TYPO3\CMS\Workspaces\Controller;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Mvc\View\ViewInterface;
use TYPO3\CMS\Workspaces\Service\WorkspaceService;
/**
* Review controller.
*/
class ReviewController extends AbstractController
{
/**
* Set up the doc header properly here
*
* @param ViewInterface $view
*/
protected function initializeView(ViewInterface $view)
{
parent::initializeView($view);
$this->registerButtons();
$this->view->getModuleTemplate()->setFlashMessageQueue($this->controllerContext->getFlashMessageQueue());
}
/**
* Registers the DocHeader buttons
*/
protected function registerButtons()
{
$buttonBar = $this->view->getModuleTemplate()->getDocHeaderComponent()->getButtonBar();
$currentRequest = $this->request;
$moduleName = $currentRequest->getPluginName();
$getVars = $this->request->getArguments();
$extensionName = $currentRequest->getControllerExtensionName();
if (count($getVars) === 0) {
$modulePrefix = strtolower('tx_' . $extensionName . '_' . $moduleName);
$getVars = array('id', 'M', $modulePrefix);
}
$shortcutButton = $buttonBar->makeShortcutButton()
->setModuleName($moduleName)
->setGetVariables($getVars);
$buttonBar->addButton($shortcutButton);
}
/**
* Renders the review module user dependent with all workspaces.
* The module will show all records of one workspace.
*
* @return void
*/
public function indexAction()
{
/** @var WorkspaceService $wsService */
$wsService = GeneralUtility::makeInstance(WorkspaceService::class);
$this->view->assign('showGrid', !($GLOBALS['BE_USER']->workspace === 0 && !$GLOBALS['BE_USER']->isAdmin()));
$this->view->assign('showAllWorkspaceTab', true);
$this->view->assign('pageUid', GeneralUtility::_GP('id'));
if (GeneralUtility::_GP('id')) {
$pageRecord = BackendUtility::getRecord('pages', GeneralUtility::_GP('id'));
if ($pageRecord) {
$this->view->getModuleTemplate()->getDocHeaderComponent()->setMetaInformation($pageRecord);
$this->view->assign('pageTitle', BackendUtility::getRecordTitle('pages', $pageRecord));
}
}
$this->view->assign('showLegend', !($GLOBALS['BE_USER']->workspace === 0 && !$GLOBALS['BE_USER']->isAdmin()));
$wsList = $wsService->getAvailableWorkspaces();
$activeWorkspace = $GLOBALS['BE_USER']->workspace;
$performWorkspaceSwitch = false;
// Only admins see multiple tabs, we decided to use it this
// way for usability reasons. Regular users might be confused
// by switching workspaces with the tabs in a module.
if (!$GLOBALS['BE_USER']->isAdmin()) {
$wsCur = array($activeWorkspace => true);
$wsList = array_intersect_key($wsList, $wsCur);
} else {
if ((string)GeneralUtility::_GP('workspace') !== '') {
$switchWs = (int)GeneralUtility::_GP('workspace');
if (in_array($switchWs, array_keys($wsList)) && $activeWorkspace != $switchWs) {
$activeWorkspace = $switchWs;
$GLOBALS['BE_USER']->setWorkspace($activeWorkspace);
$performWorkspaceSwitch = true;
BackendUtility::setUpdateSignal('updatePageTree');
} elseif ($switchWs == WorkspaceService::SELECT_ALL_WORKSPACES) {
$this->redirect('fullIndex');
}
}
}
$this->pageRenderer->addInlineSetting('Workspaces', 'isLiveWorkspace', (int)$GLOBALS['BE_USER']->workspace === 0);
$this->pageRenderer->addInlineSetting('Workspaces', 'workspaceTabs', $this->prepareWorkspaceTabs($wsList, $activeWorkspace));
$this->pageRenderer->addInlineSetting('Workspaces', 'activeWorkspaceId', $activeWorkspace);
$this->pageRenderer->addInlineSetting('FormEngine', 'moduleUrl', BackendUtility::getModuleUrl('record_edit'));
$this->view->assign('performWorkspaceSwitch', $performWorkspaceSwitch);
$this->view->assign('workspaceList', $wsList);
$this->view->assign('activeWorkspaceUid', $activeWorkspace);
$this->view->assign('activeWorkspaceTitle', WorkspaceService::getWorkspaceTitle($activeWorkspace));
if ($wsService->canCreatePreviewLink(GeneralUtility::_GP('id'), $activeWorkspace)) {
$buttonBar = $this->view->getModuleTemplate()->getDocHeaderComponent()->getButtonBar();
$iconFactory = $this->view->getModuleTemplate()->getIconFactory();
$showButton = $buttonBar->makeLinkButton()
->setHref('#')
->setOnClick('TYPO3.Workspaces.Actions.generateWorkspacePreviewLinksForAllLanguages();return false;')
->setTitle($this->getLanguageService()->sL('LLL:EXT:workspaces/Resources/Private/Language/locallang.xlf:tooltip.generatePagePreview'))
->setIcon($iconFactory->getIcon('module-workspaces-action-preview-link', Icon::SIZE_SMALL));
$buttonBar->addButton($showButton);
}
$this->view->assign('showPreviewLink', $wsService->canCreatePreviewLink(GeneralUtility::_GP('id'), $activeWorkspace));
$GLOBALS['BE_USER']->setAndSaveSessionData('tx_workspace_activeWorkspace', $activeWorkspace);
}
/**
* Renders the review module user dependent.
* The module will show all records of all workspaces.
*
* @return void
*/
public function fullIndexAction()
{
$wsService = GeneralUtility::makeInstance(\TYPO3\CMS\Workspaces\Service\WorkspaceService::class);
$wsList = $wsService->getAvailableWorkspaces();
if (!$GLOBALS['BE_USER']->isAdmin()) {
$activeWorkspace = $GLOBALS['BE_USER']->workspace;
$wsCur = array($activeWorkspace => true);
$wsList = array_intersect_key($wsList, $wsCur);
}
$this->pageRenderer->addInlineSetting('Workspaces', 'workspaceTabs', $this->prepareWorkspaceTabs($wsList, WorkspaceService::SELECT_ALL_WORKSPACES));
$this->pageRenderer->addInlineSetting('Workspaces', 'activeWorkspaceId', WorkspaceService::SELECT_ALL_WORKSPACES);
$this->view->assign('pageUid', GeneralUtility::_GP('id'));
$this->view->assign('showGrid', true);
$this->view->assign('showLegend', true);
$this->view->assign('showAllWorkspaceTab', true);
$this->view->assign('workspaceList', $wsList);
$this->view->assign('activeWorkspaceUid', WorkspaceService::SELECT_ALL_WORKSPACES);
$this->view->assign('showPreviewLink', false);
$GLOBALS['BE_USER']->setAndSaveSessionData('tx_workspace_activeWorkspace', WorkspaceService::SELECT_ALL_WORKSPACES);
// set flag for javascript
$this->pageRenderer->addInlineSetting('Workspaces', 'allView', '1');
}
/**
* Renders the review module for a single page. This is used within the
* workspace-preview frame.
*
* @return void
*/
public function singleIndexAction()
{
$wsService = GeneralUtility::makeInstance(\TYPO3\CMS\Workspaces\Service\WorkspaceService::class);
$wsList = $wsService->getAvailableWorkspaces();
$activeWorkspace = $GLOBALS['BE_USER']->workspace;
$wsCur = array($activeWorkspace => true);
$wsList = array_intersect_key($wsList, $wsCur);
$backendDomain = GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY');
$this->view->assign('pageUid', GeneralUtility::_GP('id'));
$this->view->assign('showGrid', true);
$this->view->assign('showAllWorkspaceTab', false);
$this->view->assign('workspaceList', $wsList);
$this->view->assign('backendDomain', $backendDomain);
// Setting the document.domain early before JavScript
// libraries are loaded, try to access top frame reference
// and possibly run into some CORS issue
$this->pageRenderer->setMetaCharsetTag(
$this->pageRenderer->getMetaCharsetTag() . LF
. GeneralUtility::wrapJS('document.domain = ' . GeneralUtility::quoteJSvalue($backendDomain) . ';')
);
$this->pageRenderer->addInlineSetting('Workspaces', 'singleView', '1');
}
/**
* Initializes the controller before invoking an action method.
*
* @return void
*/
protected function initializeAction()
{
parent::initializeAction();
$backendRelPath = ExtensionManagementUtility::extRelPath('backend');
$this->pageRenderer->addJsFile($backendRelPath . 'Resources/Public/JavaScript/ExtDirect.StateProvider.js');
if (WorkspaceService::isOldStyleWorkspaceUsed()) {
$flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class, $GLOBALS['LANG']->sL('LLL:EXT:workspaces/Resources/Private/Language/locallang.xlf:warning.oldStyleWorkspaceInUser'), '', \TYPO3\CMS\Core\Messaging\FlashMessage::WARNING);
/** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
$flashMessageService = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessageService::class);
/** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
$defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
$defaultFlashMessageQueue->enqueue($flashMessage);
}
$this->pageRenderer->loadExtJS();
$states = $GLOBALS['BE_USER']->uc['moduleData']['Workspaces']['States'];
$this->pageRenderer->addInlineSetting('Workspaces', 'States', $states);
// Load JavaScript:
$this->pageRenderer->addExtDirectCode(array(
'TYPO3.Workspaces'
));
$this->pageRenderer->addJsFile($backendRelPath . 'Resources/Public/JavaScript/extjs/ux/Ext.grid.RowExpander.js');
$this->pageRenderer->addJsFile($backendRelPath . 'Resources/Public/JavaScript/extjs/ux/Ext.app.SearchField.js');
$this->pageRenderer->addJsFile($backendRelPath . 'Resources/Public/JavaScript/extjs/ux/Ext.ux.FitToParent.js');
$resourcePath = ExtensionManagementUtility::extRelPath('workspaces') . 'Resources/Public/JavaScript/';
// @todo Integrate additional stylesheet resources
$this->pageRenderer->addCssFile($resourcePath . 'gridfilters/css/GridFilters.css');
$this->pageRenderer->addCssFile($resourcePath . 'gridfilters/css/RangeMenu.css');
$filters = array(
$resourcePath . 'gridfilters/menu/RangeMenu.js',
$resourcePath . 'gridfilters/menu/ListMenu.js',
$resourcePath . 'gridfilters/GridFilters.js',
$resourcePath . 'gridfilters/filter/Filter.js',
$resourcePath . 'gridfilters/filter/StringFilter.js',
$resourcePath . 'gridfilters/filter/DateFilter.js',
$resourcePath . 'gridfilters/filter/ListFilter.js',
$resourcePath . 'gridfilters/filter/NumericFilter.js',
$resourcePath . 'gridfilters/filter/BooleanFilter.js',
$resourcePath . 'gridfilters/filter/BooleanFilter.js',
);
$custom = $this->getAdditionalResourceService()->getJavaScriptResources();
$resources = array(
$resourcePath . 'Component/RowDetailTemplate.js',
$resourcePath . 'Component/RowExpander.js',
$resourcePath . 'Component/TabPanel.js',
$resourcePath . 'Store/mainstore.js',
$resourcePath . 'configuration.js',
$resourcePath . 'helpers.js',
$resourcePath . 'actions.js',
$resourcePath . 'component.js',
$resourcePath . 'toolbar.js',
$resourcePath . 'grid.js',
$resourcePath . 'workspaces.js'
);
$javaScriptFiles = array_merge($filters, $custom, $resources);
foreach ($javaScriptFiles as $javaScriptFile) {
$this->pageRenderer->addJsFile($javaScriptFile);
}
foreach ($this->getAdditionalResourceService()->getLocalizationResources() as $localizationResource) {
$this->pageRenderer->addInlineLanguageLabelFile($localizationResource);
}
$this->pageRenderer->addInlineSetting('FormEngine', 'moduleUrl', BackendUtility::getModuleUrl('record_edit'));
$this->pageRenderer->addInlineSetting('RecordHistory', 'moduleUrl', BackendUtility::getModuleUrl('record_history'));
}
/**
* Prepares available workspace tabs.
*
* @param array $workspaceList
* @param int $activeWorkspace
* @return array
*/
protected function prepareWorkspaceTabs(array $workspaceList, $activeWorkspace)
{
$tabs = array();
if ($activeWorkspace !== WorkspaceService::SELECT_ALL_WORKSPACES) {
$tabs[] = array(
'title' => $workspaceList[$activeWorkspace],
'itemId' => 'workspace-' . $activeWorkspace,
'workspaceId' => $activeWorkspace,
'triggerUrl' => $this->getModuleUri($activeWorkspace),
);
}
$tabs[] = array(
'title' => 'All workspaces',
'itemId' => 'workspace-' . WorkspaceService::SELECT_ALL_WORKSPACES,
'workspaceId' => WorkspaceService::SELECT_ALL_WORKSPACES,
'triggerUrl' => $this->getModuleUri(WorkspaceService::SELECT_ALL_WORKSPACES),
);
foreach ($workspaceList as $workspaceId => $workspaceTitle) {
if ($workspaceId === $activeWorkspace) {
continue;
}
$tabs[] = array(
'title' => $workspaceTitle,
'itemId' => 'workspace-' . $workspaceId,
'workspaceId' => $workspaceId,
'triggerUrl' => $this->getModuleUri($workspaceId),
);
}
return $tabs;
}
/**
* Gets the module URI.
*
* @param int $workspaceId
* @return string
*/
protected function getModuleUri($workspaceId)
{
$parameters = array(
'id' => (int)$this->pageId,
'workspace' => (int)$workspaceId,
);
// The "all workspaces" tab is handled in fullIndexAction
// which is required as additional GET parameter in the URI then
if ($workspaceId === WorkspaceService::SELECT_ALL_WORKSPACES) {
$this->uriBuilder->reset()->uriFor('fullIndex');
$parameters = array_merge($parameters, $this->uriBuilder->getArguments());
}
return BackendUtility::getModuleUrl('web_WorkspacesWorkspaces', $parameters);
}
/**
* @return \TYPO3\CMS\Lang\LanguageService
*/
protected function getLanguageService()
{
return $GLOBALS['LANG'];
}
}
| liayn/TYPO3.CMS | typo3/sysext/workspaces/Classes/Controller/ReviewController.php | PHP | gpl-2.0 | 15,544 |
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.ComponentModel;
namespace Lcc.Entrada.Articulos
{
public partial class DetalleComprobante : ControlSeleccionElemento
{
protected bool m_MostrarExistencias, m_DiscriminarIva = false, m_AplicarIva = true;
protected Precios m_Precio = Precios.Pvp;
protected ControlesSock m_ControlStock = ControlesSock.Ambos;
protected Lbl.Articulos.ColeccionDatosSeguimiento m_DatosSeguimiento = new Lbl.Articulos.ColeccionDatosSeguimiento();
protected Lbl.Impuestos.Alicuota m_Alicuota = null;
protected decimal m_ImporteUnitarioIva = 0m;
new public event System.Windows.Forms.KeyEventHandler KeyDown;
public event System.EventHandler ImportesChanged;
public event System.EventHandler ObtenerDatosSeguimiento;
public DetalleComprobante()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (Lfx.Workspace.Master != null) {
switch (m_Precio) {
case Precios.Costo:
EntradaUnitario.DecimalPlaces = Lfx.Workspace.Master.CurrentConfig.Moneda.DecimalesCosto;
EntradaImporte.DecimalPlaces = Lfx.Workspace.Master.CurrentConfig.Moneda.DecimalesCosto;
break;
case Precios.Pvp:
EntradaUnitario.DecimalPlaces = Lfx.Workspace.Master.CurrentConfig.Moneda.Decimales;
EntradaImporte.DecimalPlaces = Lfx.Workspace.Master.CurrentConfig.Moneda.Decimales;
break;
}
}
}
public ControlesSock ControlStock
{
get
{
return m_ControlStock;
}
set
{
m_ControlStock = value;
PonerFiltros();
}
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
override public bool ShowChanged
{
set
{
base.ShowChanged = value;
EntradaArticulo.ShowChanged = value;
EntradaDescuento.ShowChanged = value;
EntradaCantidad.ShowChanged = value;
EntradaUnitario.ShowChanged = value;
}
}
[EditorBrowsable(EditorBrowsableState.Never),
System.ComponentModel.Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool AutoUpdate
{
get
{
return EntradaArticulo.AutoUpdate;
}
set
{
EntradaArticulo.AutoUpdate = value;
}
}
public bool PermiteCrear
{
get
{
return EntradaArticulo.CanCreate;
}
set
{
EntradaArticulo.CanCreate = value;
}
}
[EditorBrowsable(EditorBrowsableState.Never),
System.ComponentModel.Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override bool IsEmpty
{
get
{
return EntradaArticulo.IsEmpty;
}
}
[EditorBrowsable(EditorBrowsableState.Never),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
new public int ValueInt
{
get
{
return EntradaArticulo.ValueInt;
}
set
{
if (EntradaArticulo.ValueInt != value)
EntradaArticulo.ValueInt = value;
}
}
[EditorBrowsable(EditorBrowsableState.Never),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Lbl.Articulos.ColeccionDatosSeguimiento DatosSeguimiento
{
get
{
return m_DatosSeguimiento;
}
set
{
if (m_DatosSeguimiento != value) {
this.Changed = true;
}
m_DatosSeguimiento = value;
if (m_DatosSeguimiento == null || m_DatosSeguimiento.Count == 0) {
LabelSerials.Visible = false;
} else {
LabelSerials.Text = "Seguimiento: " + m_DatosSeguimiento.ToString();
LabelSerials.Visible = true;
if (this.Cantidad != m_DatosSeguimiento.CantidadTotal)
this.Cantidad = m_DatosSeguimiento.CantidadTotal;
}
}
}
public bool MuestraPrecio
{
get
{
return EntradaUnitario.Visible;
}
set
{
EntradaUnitario.Visible = value;
EntradaIva.Visible = value;
EntradaCantidad.Visible = value;
EntradaDescuento.Visible = value;
EntradaImporte.Visible = value;
if (value)
EntradaArticulo.Width = EntradaUnitario.Left - 1;
else
EntradaArticulo.Width = this.Width;
}
}
// Oculta al changed de abajo
[EditorBrowsable(EditorBrowsableState.Never),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
new public bool Changed
{
get
{
return EntradaArticulo.Changed || EntradaCantidad.Changed || EntradaUnitario.Changed || EntradaDescuento.Changed;
}
set
{
EntradaArticulo.Changed = value;
EntradaDescuento.Changed = value;
EntradaCantidad.Changed = value;
EntradaUnitario.Changed = value;
}
}
public Precios UsarPrecio
{
get
{
return m_Precio;
}
set
{
m_Precio = value;
this.CambiarArticulo(this.Articulo);
this.Changed = false;
}
}
public bool BloquearAtriculo
{
get
{
return EntradaArticulo.TemporaryReadOnly;
}
set
{
EntradaArticulo.TemporaryReadOnly = value;
}
}
public bool BloquearCantidad
{
get
{
return EntradaCantidad.TemporaryReadOnly;
}
set
{
EntradaCantidad.TemporaryReadOnly = value;
}
}
public bool BloquearPrecio
{
get
{
return EntradaUnitario.TemporaryReadOnly;
}
set
{
EntradaUnitario.ReadOnly = value;
EntradaDescuento.ReadOnly = value || this.BloquearDescuento;
}
}
public bool BloquearDescuento
{
get
{
return EntradaDescuento.TemporaryReadOnly;
}
set
{
EntradaDescuento.ReadOnly = value || this.BloquearPrecio;
}
}
public bool MostrarExistencias
{
get
{
return m_MostrarExistencias;
}
set
{
m_MostrarExistencias = value;
VerificarStock();
}
}
/// <summary>
/// Indica si los precios se muestran con IVA discriminado.
/// </summary>
public bool DiscriminarIva
{
get
{
return m_DiscriminarIva;
}
set
{
bool AntesDiscriminaba = m_DiscriminarIva;
m_DiscriminarIva = value;
EntradaIva.Enabled = this.DiscriminarIva && this.AplicarIva;
if (m_DiscriminarIva != AntesDiscriminaba && m_AplicarIva && m_Alicuota != null) {
if (value) {
// Antes no discriminaba y ahora sí
this.EstablecerImporteUnitarioOriginal(this.ImporteUnitario / (1 + m_Alicuota.Porcentaje / 100m));
} else {
// Antes discriminaba y ahora no
this.EstablecerImporteUnitarioOriginal(this.ImporteUnitario);
}
this.RecalcularImporteFinal();
if (null != ImportesChanged) {
ImportesChanged(this, null);
}
}
this.RecalcularImporteFinal();
}
}
/// <summary>
/// Indica si debe aplicar IVA al cliente.
/// </summary>
public bool AplicarIva
{
get
{
return m_AplicarIva;
}
set
{
bool AntesAplicaba = m_AplicarIva;
m_AplicarIva = value;
EntradaIva.Enabled = this.DiscriminarIva && this.AplicarIva;
if (m_AplicarIva != AntesAplicaba && m_Alicuota != null) {
decimal NuevoImporteUnitarioIva = this.ImporteUnitario * (m_Alicuota.Porcentaje / 100m);
if (value) {
// Antes no aplicaba y ahora sí
this.EstablecerImporteUnitarioOriginal(this.ImporteUnitario);
} else {
// Antes aplicaba y ahora no
this.EstablecerImporteUnitarioOriginal((this.ImporteUnitario + this.ImporteIvaDiscriminadoUnitario) / (1m + m_Alicuota.Porcentaje / 100m));
}
this.RecalcularImporteFinal();
if (null != ImportesChanged) {
ImportesChanged(this, null);
}
}
}
}
public bool Required
{
get
{
return EntradaArticulo.Required;
}
set
{
EntradaArticulo.Required = value;
}
}
[System.ComponentModel.Category("Datos")]
public string FreeTextCode
{
get
{
return EntradaArticulo.FreeTextCode;
}
set
{
EntradaArticulo.FreeTextCode = value;
}
}
public int UnitarioLeft
{
get
{
return EntradaUnitario.Left;
}
}
public int DescuentoLeft
{
get
{
return EntradaDescuento.Left;
}
}
public int CantidadLeft
{
get
{
return EntradaCantidad.Left;
}
}
public int IvaLeft
{
get
{
return EntradaIva.Left;
}
}
public int ImporteLeft
{
get
{
return EntradaImporte.Left;
}
}
public override string Text
{
get
{
if (EntradaArticulo.Text == EntradaArticulo.FreeTextCode && EntradaArticulo.FreeTextCode.Length > 0)
return EntradaArticulo.Text;
else
return EntradaArticulo.ValueInt.ToString();
}
set
{
if (EntradaArticulo.Text != value) {
EntradaArticulo.Text = value;
}
this.Changed = false;
}
}
public string TextDetail
{
get
{
return EntradaArticulo.TextDetail;
}
set
{
EntradaArticulo.TextDetail = value;
this.Changed = false;
}
}
/// <summary>
/// El importe final, con IVA, por cantidad y con descuento.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public decimal ImporteFinal
{
get
{
return EntradaImporte.ValueDecimal;
}
set
{
EntradaImporte.ValueDecimal = value;
this.Changed = false;
}
}
/// <summary>
/// El importe de IVA unitario (sin descuento).
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public decimal ImporteIvaUnitario
{
get
{
return this.m_ImporteUnitarioIva;
}
set
{
this.m_ImporteUnitarioIva = value;
if(this.DiscriminarIva) {
this.EntradaUnitarioIvaDescuentoCantidad_TextChanged(this, null);
}
this.Changed = false;
}
}
/// <summary>
/// El importe de IVA discriminado unitario (sin descuento), o 0 si el IVA no está discriminado.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public decimal ImporteIvaDiscriminadoUnitario
{
get
{
return EntradaIva.ValueDecimal;
}
set
{
EntradaIva.ValueDecimal = value;
this.Changed = false;
}
}
/// <summary>
/// El importe de IVA final, por cantidad y con descuento.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public decimal ImporteIvaUnitarioFinal
{
get
{
return this.ImporteIvaUnitario * this.Cantidad * (1m - this.Descuento / 100m);
}
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public decimal ImporteUnitario
{
get
{
return EntradaUnitario.ValueDecimal;
}
set
{
EntradaUnitario.ValueDecimal = value;
this.Changed = false;
}
}
/// <summary>
/// El importe unitario final, por cantidad y con descuento.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public decimal ImporteUnitarioFinal
{
get
{
return this.ImporteUnitario * this.Cantidad * (1m - this.Descuento / 100m);
}
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public decimal Descuento
{
get
{
return EntradaDescuento.ValueDecimal;
}
set
{
EntradaDescuento.ValueDecimal = value;
this.Changed = false;
}
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Lbl.Articulos.Articulo Articulo
{
get
{
return EntradaArticulo.Elemento as Lbl.Articulos.Articulo;
}
set
{
EntradaArticulo.Elemento = value;
this.Elemento = value;
if(value == null) {
this.m_Alicuota = null;
} else {
this.m_Alicuota = value.ObtenerAlicuota();
}
EntradaArticulo_TextChanged(this, null);
}
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Lbl.Impuestos.Alicuota Alicuota
{
get
{
return m_Alicuota;
}
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public decimal Cantidad
{
get
{
if (this.EstoyUsandoUnidadPrimaria())
return EntradaCantidad.ValueDecimal;
else
return EntradaCantidad.ValueDecimal / Articulo.Rendimiento;
}
set
{
if (this.EstoyUsandoUnidadPrimaria())
EntradaCantidad.ValueDecimal = value;
else
EntradaCantidad.ValueDecimal = value * this.Articulo.Rendimiento;
this.Changed = false;
}
}
private bool EstoyUsandoUnidadPrimaria()
{
return (this.Articulo == null || Articulo.Unidad == null || EntradaCantidad.Sufijo == Articulo.Unidad || (EntradaCantidad.Sufijo.Length == 0 && Articulo.Unidad == "u") || Articulo.Rendimiento == 0);
}
private void EntradaArticulo_TextChanged(object sender, System.EventArgs e)
{
if (this.Connection == null)
return;
EntradaUnitario.TabStop = EntradaArticulo.IsFreeText;
if (this.Elemento != EntradaArticulo.Elemento || EntradaArticulo.IsFreeText) {
this.Elemento = EntradaArticulo.Elemento;
if (this.Articulo != null) {
this.m_Alicuota = this.Articulo.ObtenerAlicuota();
}
this.CambiarArticulo(this.Articulo);
}
this.DatosSeguimiento = null;
this.Changed = true;
this.OnTextChanged(EventArgs.Empty);
}
private void EntradaUnitarioIvaDescuentoCantidad_TextChanged(object sender, System.EventArgs e)
{
if (this.Connection != null) {
decimal ValorAnterior = EntradaImporte.ValueDecimal;
this.RecalcularImporteFinal();
this.VerificarStock();
if (EntradaImporte.ValueDecimal != ValorAnterior) {
this.Changed = true;
if (null != ImportesChanged) {
ImportesChanged(this, null);
}
}
}
}
private void VerificarStock()
{
if (m_MostrarExistencias && Articulo != null) {
if (this.TemporaryReadOnly == false && this.Articulo.TipoDeArticulo != Lbl.Articulos.TiposDeArticulo.Servicio && this.Articulo.Existencias < this.Cantidad) {
if (this.Articulo.Existencias + this.Articulo.Pedido >= this.Cantidad) {
//EntradaArticulo.Font = null;
EntradaArticulo.ForeColor = Color.OrangeRed;
} else {
//EntradaArticulo.Font = new Font(this.Font, FontStyle.Strikeout);
EntradaArticulo.ForeColor = Color.Red;
}
} else {
//EntradaArticulo.Font = null;
EntradaArticulo.ForeColor = this.DisplayStyle.TextColor;
}
} else {
//EntradaArticulo.Font = null;
EntradaArticulo.ForeColor = this.DisplayStyle.TextColor;
}
}
public override bool TemporaryReadOnly
{
get
{
return base.TemporaryReadOnly;
}
set
{
base.TemporaryReadOnly = value;
if (value) {
EntradaArticulo.TemporaryReadOnly = true;
EntradaUnitario.TemporaryReadOnly = true;
EntradaDescuento.TemporaryReadOnly = true;
EntradaCantidad.TemporaryReadOnly = true;
}
this.VerificarStock();
}
}
private void EntradaArticulo_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.Alt == false && e.Control == false && e.Shift == false) {
switch (e.KeyCode) {
case Keys.Right:
case Keys.Return:
e.Handled = true;
if (EntradaUnitario.Visible && this.ReadOnly == false && this.TemporaryReadOnly == false) {
if (this.BloquearPrecio)
EntradaCantidad.Focus();
else
EntradaUnitario.Focus();
} else {
System.Windows.Forms.SendKeys.Send("{tab}");
}
break;
default:
if (KeyDown != null)
KeyDown(sender, e);
this.AutoUpdate = true;
break;
}
}
if (e.Alt == false && e.Control == true && e.Shift == false) {
switch (e.KeyCode) {
case Keys.S:
this.ObtenerDatosSeguimientoSiEsNecesario();
break;
}
}
}
protected void ObtenerDatosSeguimientoSiEsNecesario()
{
if (this.Articulo != null && this.Articulo.ObtenerSeguimiento() != Lbl.Articulos.Seguimientos.Ninguno && this.ObtenerDatosSeguimiento != null)
this.ObtenerDatosSeguimiento(this, new EventArgs());
}
protected override void OnLeave(EventArgs e)
{
Lbl.Articulos.Articulo Art = this.Elemento as Lbl.Articulos.Articulo;
if (this.Cantidad != 0 && Art != null && Art.ObtenerSeguimiento() != Lbl.Articulos.Seguimientos.Ninguno && (this.DatosSeguimiento == null || this.DatosSeguimiento.Count != this.Cantidad)) {
this.ObtenerDatosSeguimientoSiEsNecesario();
}
base.OnLeave(e);
}
private void EntradaUnitario_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
switch (e.KeyCode) {
case Keys.E:
if (e.Control) {
EntradaUnitario.SelectionLength = 0;
EntradaUnitario.SelectionStart = EntradaUnitario.Text.Length;
e.Handled = true;
}
break;
case Keys.Left:
if (EntradaUnitario.SelectionStart == 0) {
e.Handled = true;
EntradaArticulo.Focus();
}
break;
case Keys.Right:
case Keys.Return:
if (EntradaUnitario.SelectionStart >= EntradaUnitario.TextRaw.Length || EntradaUnitario.SelectionLength > 0) {
e.Handled = true;
EntradaCantidad.Focus();
}
break;
case Keys.Up:
System.Windows.Forms.SendKeys.Send("+{tab}");
break;
case Keys.Down:
System.Windows.Forms.SendKeys.Send("{tab}");
break;
default:
if (null != KeyDown)
KeyDown(sender, e);
break;
}
}
private void EntradaDescuento_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode) {
case Keys.Left:
if (EntradaDescuento.SelectionStart == 0) {
e.Handled = true;
EntradaCantidad.Focus();
}
break;
case Keys.Up:
System.Windows.Forms.SendKeys.Send("+{tab}");
break;
case Keys.Down:
System.Windows.Forms.SendKeys.Send("{tab}");
break;
default:
if (null != KeyDown)
KeyDown(sender, e);
break;
}
}
private void EntradaCantidad_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
switch (e.KeyCode) {
case Keys.Left:
e.Handled = true;
if (this.BloquearPrecio)
EntradaArticulo.Focus();
else
EntradaUnitario.Focus();
break;
case Keys.Right:
case Keys.Return:
if (EntradaCantidad.SelectionStart >= EntradaCantidad.TextRaw.Length || EntradaCantidad.SelectionLength > 0) {
if (this.BloquearPrecio == false) {
e.Handled = true;
EntradaDescuento.Focus();
}
}
break;
case Keys.Up:
System.Windows.Forms.SendKeys.Send("+{tab}");
break;
case Keys.Down:
System.Windows.Forms.SendKeys.Send("{tab}");
break;
case Keys.D0:
case Keys.D1:
case Keys.D2:
case Keys.D3:
case Keys.D4:
case Keys.D5:
case Keys.D6:
case Keys.D7:
case Keys.D8:
case Keys.D9:
case Keys.Space:
e.Handled = true;
this.ObtenerDatosSeguimientoSiEsNecesario();
break;
default:
if (KeyDown != null)
KeyDown(sender, e);
break;
}
}
protected override void OnEnter(EventArgs e)
{
base.OnEnter(e);
if (EntradaArticulo.Focused == false)
EntradaArticulo.Focus();
}
private void PonerFiltros()
{
string Filtros = "";
switch (m_ControlStock) {
case ControlesSock.ConControlStock:
Filtros += "control_stock=1";
break;
case ControlesSock.SinControlStock:
Filtros += "control_stock=0";
break;
}
EntradaArticulo.Filter = Filtros;
}
private void RecalcularAltura(object sender, System.EventArgs e)
{
LabelSerialsCruz.Visible = LabelSerials.Visible;
if (LabelSerials.Visible)
this.Height = this.LabelSerials.Bottom + this.EntradaArticulo.Top;
else
this.Height = this.EntradaArticulo.Bottom + this.EntradaArticulo.Top;
}
private void EntradaCantidad_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == ' ') {
if (Articulo != null) {
if (this.EstoyUsandoUnidadPrimaria()) {
//Cambio a unidad secundaria
EntradaCantidad.Sufijo = Articulo.UnidadRendimiento;
EntradaCantidad.Text = Lfx.Types.Formatting.FormatStock(Lfx.Types.Parsing.ParseStock(EntradaCantidad.Text) * this.Articulo.Rendimiento);
} else {
//Cambio a unidad primaria
EntradaCantidad.Sufijo = Articulo.Unidad == "u" ? "" : Articulo.Unidad;
EntradaCantidad.Text = Lfx.Types.Formatting.FormatStock(Lfx.Types.Parsing.ParseStock(EntradaCantidad.Text) / this.Articulo.Rendimiento, 4);
}
e.Handled = true;
}
}
}
private void EntradaCantidad_Click(object sender, EventArgs e)
{
this.ObtenerDatosSeguimientoSiEsNecesario();
}
protected void CambiarArticulo(Lbl.Articulos.Articulo articulo)
{
if (this.Articulo != null) {
EntradaUnitario.Enabled = true;
EntradaUnitario.Enabled = true;
EntradaDescuento.Enabled = true;
EntradaCantidad.Enabled = true;
EntradaImporte.Enabled = true;
EntradaCantidad.TemporaryReadOnly = this.Articulo.ObtenerSeguimiento() != Lbl.Articulos.Seguimientos.Ninguno || this.TemporaryReadOnly;
EntradaUnitario.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio;
EntradaDescuento.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio;
if (this.AutoUpdate) {
if (this.Articulo == null) {
return;
}
if (this.Articulo.Unidad != "u") {
EntradaCantidad.Sufijo = Articulo.Unidad;
} else {
EntradaCantidad.Sufijo = "";
}
decimal UnitarioMostrar;
if (m_Precio == Precios.Costo) {
UnitarioMostrar = Articulo.Costo;
} else {
UnitarioMostrar = Articulo.Pvp;
}
if (this.Cantidad == 0) {
this.Cantidad = 1;
}
this.EstablecerImporteUnitarioOriginal(UnitarioMostrar);
this.RecalcularImporteFinal();
}
} else if (EntradaArticulo.IsFreeText) {
EntradaUnitario.Enabled = true;
EntradaDescuento.Enabled = true;
EntradaCantidad.Enabled = true;
EntradaCantidad.TemporaryReadOnly = this.TemporaryReadOnly;
EntradaUnitario.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio;
EntradaDescuento.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio;
EntradaImporte.Enabled = true;
if (this.AutoUpdate) {
if (this.Cantidad == 0) {
this.Cantidad = 1;
}
}
} else if (EntradaArticulo.Text.Length == 0 || (EntradaArticulo.Text.IsNumericInt() && EntradaArticulo.ValueInt == 0)) {
EntradaUnitario.Enabled = false;
EntradaDescuento.Enabled = false;
EntradaCantidad.Enabled = false;
EntradaCantidad.TemporaryReadOnly = this.TemporaryReadOnly;
EntradaUnitario.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio;
EntradaDescuento.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio;
EntradaImporte.Enabled = false;
if (this.AutoUpdate) {
EntradaCantidad.ValueDecimal = 0m;
EntradaImporte.ValueDecimal = 0m;
this.EstablecerImporteUnitarioOriginal(0m);
EntradaDescuento.ValueDecimal = 0m;
}
}
}
/// <summary>
/// Cambia el importe unitario original (sin IVA), y además recalcula el IVA y lo muestra discriminado si corresponde.
/// </summary>
/// <param name="unitario">El precio unitario a mostrar y usar como base para el cálculo de IVA e importe final.</param>
protected void EstablecerImporteUnitarioOriginal(decimal unitario)
{
if (this.AplicarIva && m_Alicuota != null) {
this.ImporteIvaUnitario = unitario * (m_Alicuota.Porcentaje / 100m);
if (this.DiscriminarIva) {
EntradaUnitario.ValueDecimal = unitario;
EntradaIva.ValueDecimal = this.ImporteIvaUnitario;
} else {
EntradaUnitario.ValueDecimal = unitario + this.ImporteIvaUnitario;
EntradaIva.ValueDecimal = 0m;
}
} else {
this.ImporteIvaUnitario = 0m;
EntradaUnitario.ValueDecimal = unitario;
EntradaIva.ValueDecimal = 0;
}
}
/// <summary>
/// Recalcula el importe final, según importe, IVA, cantidad y descuento.
/// </summary>
protected void RecalcularImporteFinal()
{
if(m_DiscriminarIva) {
if(m_AplicarIva && this.m_Alicuota != null) {
decimal Iva = this.ImporteUnitario * (this.m_Alicuota.Porcentaje / 100m);
if(Math.Abs(this.ImporteIvaUnitario - Iva) > 0.01m) {
this.ImporteIvaUnitario = Iva;
}
} else {
if(this.ImporteIvaUnitario != 0m) {
this.ImporteIvaUnitario = 0m;
}
}
EntradaIva.ValueDecimal = this.ImporteIvaUnitario;
} else {
EntradaIva.ValueDecimal = 0m;
}
try {
decimal ImporteFinal = (this.ImporteUnitario + this.ImporteIvaDiscriminadoUnitario) * this.Cantidad * (1m - this.Descuento / 100m);
EntradaImporte.ValueDecimal = ImporteFinal;
} catch {
EntradaImporte.ValueDecimal = 0m;
}
if (m_MostrarExistencias) {
VerificarStock();
}
}
}
} | lazarogestion/lazaro | Lcc/Entrada/Articulos/DetalleComprobante.cs | C# | gpl-2.0 | 47,695 |
<?php
/**
* Чистый Шаблон для разработки
* Шаблон вывода поста
* http://dontforget.pro
* @package WordPress
* @subpackage clean
*/
get_header(); // Подключаем хедер?>
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); // Начало цикла ?>
<h1><?php the_title(); // Заголовок ?></h1>
<?php the_content(); // Содержимое страницы ?>
<?php echo 'Рубрики: '; the_category( ' | ' ); // Выводим категории поста ?>
<?php the_tags( 'Тэги: ', ' | ', '' ); // Выводим тэги(метки) поста ?>
<?php endwhile; // Конец цикла ?>
<?php previous_post_link( '%link', '<span class="meta-nav">' . _x( '←', 'Previous post link', 'twentyten' ) . '</span> %title' ); // Ссылка на предидущий пост?>
<?php next_post_link( '%link', '%title <span class="meta-nav">' . _x( '→', 'Next post link', 'twentyten' ) . '</span>' ); // Ссылка на следующий пост?>
<?php comments_template( '', true ); // Комментарии ?>
<?php get_sidebar(); // Подключаем сайдбар ?>
<?php get_footer(); // Подключаем футер ?> | lexus65/yummy.loc | wp-content/themes/yummy-theme/single.php | PHP | gpl-2.0 | 1,240 |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# 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.
#
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#-------------------------------------------------------------------------
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from .. import HasGrampsId
#-------------------------------------------------------------------------
#
# HasIdOf
#
#-------------------------------------------------------------------------
class HasIdOf(HasGrampsId):
"""Rule that checks for a person with a specific GRAMPS ID"""
name = _('Person with <Id>')
description = _("Matches person with a specified Gramps ID")
| pmghalvorsen/gramps_branch | gramps/gen/filters/rules/person/_hasidof.py | Python | gpl-2.0 | 1,631 |
/*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.expr;
import java.io.IOException;
import java.util.ArrayList;
import com.caucho.quercus.Location;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.MethodIntern;
import com.caucho.quercus.env.NullValue;
import com.caucho.quercus.env.StringValue;
import com.caucho.quercus.env.QuercusClass;
import com.caucho.quercus.env.Value;
import com.caucho.quercus.env.Var;
import com.caucho.quercus.parser.QuercusParser;
import com.caucho.util.L10N;
/**
* Represents a PHP static field reference.
*/
public class ClassVirtualFieldExpr extends AbstractVarExpr {
private static final L10N L = new L10N(ClassVirtualFieldExpr.class);
protected final StringValue _varName;
public ClassVirtualFieldExpr(String varName)
{
_varName = MethodIntern.intern(varName);
}
//
// function call creation
//
/**
* Creates a function call expression
*/
@Override
public Expr createCall(QuercusParser parser,
Location location,
ArrayList<Expr> args)
throws IOException
{
ExprFactory factory = parser.getExprFactory();
Expr var = parser.createVar(_varName.toString());
return factory.createClassVirtualMethodCall(location, var, args);
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
@Override
public Value eval(Env env)
{
Value qThis = env.getThis();
QuercusClass qClass = qThis != null ? qThis.getQuercusClass() : null;
if (qClass == null) {
env.error(L.l("No calling class found for '{0}'", this));
return NullValue.NULL;
}
return qClass.getStaticFieldValue(env, _varName);
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
@Override
public Var evalVar(Env env)
{
Value qThis = env.getThis();
QuercusClass qClass = qThis != null ? qThis.getQuercusClass() : null;
if (qClass == null) {
env.error(L.l("No calling class found for '{0}'", this));
return NullValue.NULL.toVar();
}
return qClass.getStaticFieldVar(env, _varName);
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
@Override
public Value evalAssignRef(Env env, Value value)
{
Value qThis = env.getThis();
QuercusClass qClass = qThis != null ? qThis.getQuercusClass() : null;
if (qClass == null) {
env.error(L.l("No calling class found for '{0}'", this));
return NullValue.NULL.toVar();
}
return qClass.setStaticFieldRef(env, _varName, value);
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
public void evalUnset(Env env)
{
env.error(getLocation(),
L.l("{0}::${1}: Cannot unset static variables.",
env.getCallingClass().getName(), _varName));
}
public String toString()
{
return "static::$" + _varName;
}
}
| dwango/quercus | src/main/java/com/caucho/quercus/expr/ClassVirtualFieldExpr.java | Java | gpl-2.0 | 4,206 |
#include "punchestableview.h"
#include <qf/core/log.h>
#include <QDrag>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QPainter>
#include <QPixmap>
PunchesTableView::PunchesTableView(QWidget *parent)
: Super(parent)
{
setDropIndicatorShown(false);
}
bool PunchesTableView::edit(const QModelIndex &index, QAbstractItemView::EditTrigger trigger, QEvent *event)
{
Q_UNUSED(event)
if(trigger == QAbstractItemView::EditTrigger::DoubleClicked
|| trigger == QAbstractItemView::EditTrigger::EditKeyPressed) {
qf::core::utils::TableRow row = tableRow(index.row());
int class_id = row.value("classes.id").toInt();
int code = row.value("punches.code").toInt();
qfDebug() << "codeClassActivated:" << class_id << code;
emit codeClassActivated(class_id, code);
}
return false;
}
/*
void PunchesTableView::mousePressEvent(QMouseEvent *event)
{
qfInfo() << Q_FUNC_INFO;
QModelIndex ix = indexAt(event->pos());
if (!ix.isValid())
return;
qf::core::utils::TableRow row = tableRow(ix.row());
QString class_name = row.value(QStringLiteral("classes.name")).toString();
int code = row.value(QStringLiteral("punches.code")).toInt();
QByteArray item_data;
QDataStream data_stream(&item_data, QIODevice::WriteOnly);
data_stream << ix.row() << ix.column();
QMimeData *mime_data = new QMimeData;
mime_data->setData("application/x-quickevent", item_data);
QDrag *drag = new QDrag(this);
drag->setMimeData(mime_data);
//drag->setPixmap(pixmap);
//drag->setHotSpot(event->pos() - child->pos());
QPixmap px{QSize{10, 10}};
QPainter painter;
QFont f = font();
QFontMetrics fm(f, &px);
QString s = QString("%1 - %2").arg(class_name).arg(code);
QRect bounding_rect = fm.boundingRect(s);
static constexpr int inset = 5;
bounding_rect.adjust(-inset, -inset, inset, inset);
px = QPixmap{bounding_rect.size()};
painter.begin(&px);
painter.setFont(f);
//painter.setPen(Qt::black);
//painter.setBrush(Qt::black);
painter.fillRect(px.rect(), QColor("khaki"));
painter.drawRect(QRect(QPoint(), bounding_rect.size() - QSize(1, 1)));
painter.drawText(QPoint{inset, inset + fm.ascent()}, s);
painter.end();
drag->setPixmap(px);
if (drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction) == Qt::MoveAction) {
//child->close();
} else {
//child->show();
//child->setPixmap(pixmap);
}
}
void PunchesTableView::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat("application/x-quickevent")) {
if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void PunchesTableView::dragMoveEvent(QDragMoveEvent *event)
{
if (event->mimeData()->hasFormat("application/x-quickevent")) {
if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
*/
| arnost00/quickbox | quickevent/app/quickevent/plugins/Speaker/src/punchestableview.cpp | C++ | gpl-2.0 | 2,945 |
// prng.cpp or pseudo-random number generator (prng)
// Generates some pseudo-random numbers.
#include <iostream>
#include <iomanip>
using std::cout; // iostream
using std::endl;
using std::setw; // iomanip
// function generates random number
unsigned pseudoRNG() {
static unsigned seed = 5493; // some (any) initial starting seed; initialized only once!
// Take the current seed and generate new value from it
// Due to larg numbers used to generate numbers is difficult to
// predict next value from previous one.
// Static keyword has program scope and is terminated at the end of
// program. Seed value is stored every time in memory using previous
// value.
seed = (3852591 * seed + 5180347);
// return value between 0 and 65535
return (seed % 65535);
}
int main()
{
// generate 100 random numbers - print in separate fields
for (int i = 1; i <= 100; i++) {
cout << setw(8) << pseudoRNG();
// new line every fifth number
if (i % 5 == 0)
cout << endl;
}
return 0;
}
| Grayninja/General | Programming/C++/5.Control_Flow/5.9-random-number-generation/prng.cpp | C++ | gpl-2.0 | 1,000 |
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class System
{
function System()
{
if (!isset($this->CI))
{
$this->CI =& get_instance();
}
$this->settings_table = 'settings';
$this->template_table = 'templates';
$this->languages_table = 'languages';
$this->CI->config->set_item('language', $this->get_default_language());
$this->get_site_info();
}
function get_default_template()
{
$this->CI->db->select('path');
$this->CI->db->where('is_default', '1');
$query = $this->CI->db->get($this->template_table, 1);
if ($query->num_rows() == 1)
{
$row = $query->row_array();
}
return $row['path'];
}
function get_default_language()
{
$this->CI->db->select('language');
$this->CI->db->where('is_default', '1');
$query = $this->CI->db->get($this->languages_table, 1);
if ($query->num_rows() == 1)
{
$row = $query->row_array();
}
return $row['language'];
}
function get_site_info()
{
$this->CI->db->select('blog_title, blog_description, meta_keywords, allow_registrations, enable_rss, enable_atom, links_per_box, months_per_archive');
$this->CI->db->where('id', '1');
$query = $this->CI->db->get($this->settings_table, 1);
if ($query->num_rows() == 1)
{
$result = $query->row_array();
foreach ($result as $key => $value)
{
$this->settings[$key] = $value;
}
}
}
function check_site_status()
{
$this->CI->db->select('enabled, offline_reason');
$this->CI->db->where('id', '1');
$query = $this->CI->db->get($this->settings_table, 1);
if ($query->num_rows() == 1)
{
$result = $query->row_array();
if ($result['enabled'] == 0)
{
echo lang('site_disabled') . "<br />";
echo lang('reason') . " <strong>" . $result['offline_reason'] . "</strong>";
die();
}
}
}
function load($page, $data = null, $admin = false)
{
$data['page'] = $page;
if ($admin == true)
{
$this->CI->load->view('admin/layout/container', $data);
}
else
{
$template = $this->get_default_template();
$this->CI->load->view('templates/' . $template . '/layout/container', $data);
}
}
function load_normal($page, $data = null)
{
$template = $this->get_default_template();
$this->CI->load->view('templates/' . $template . '/layout/pages/' . $page, $data);
}
}
/* End of file System.php */
/* Location: ./application/libraries/System.php */ | JasonBaier/Open-Blog | application/libraries/System.php | PHP | gpl-3.0 | 2,540 |
import string
import socket
import base64
import sys
class message:
def __init__(self, name="generate" ):
if name == "generate":
self.name=socket.gethostname()
else:
self.name=name
self.type="gc"
self.decoded=""
def set ( self, content=" " ):
base64content = base64.b64encode ( content )
self.decoded="piratebox;"+ self.type + ";01;" + self.name + ";" + base64content
def get ( self ):
# TODO Split decoded part
message_parts = string.split ( self.decoded , ";" )
if message_parts[0] != "piratebox":
return None
b64_content_part = message_parts[4]
content = base64.b64decode ( b64_content_part )
return content
def get_sendername (self):
return self.name
def get_message ( self ):
return self.decoded
def set_message ( self , decoded):
self.decoded = decoded
class shoutbox_message(message):
def __init__(self, name="generate" ):
message.__init__( self , name)
self.type="sb"
| LibraryBox-Dev/LibraryBox-core | piratebox_origin/piratebox/piratebox/python_lib/messages.py | Python | gpl-3.0 | 1,109 |
using System;
using Server;
using Server.Items;
namespace Server.Mobiles
{
public class Kurlem : BaseCreature
{
[Constructable]
public Kurlem()
: base( AIType.AI_Melee, FightMode.Aggressor, 22, 1, 0.2, 1.0 )
{
Name = "Kurlem";
Title = "the Caretaker";
Race = Race.Gargoyle;
Blessed = true;
Hue = 0x86DF;
HairItemID = 0x4258;
HairHue = 0x31C;
AddItem( new GargishLeatherArms() );
AddItem( new GargishFancyRobe( 0x3B3 ) );
}
public override bool CanTeach { get { return false; } }
public Kurlem( Serial serial )
: base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
/*int version = */
reader.ReadInt();
}
}
} | greeduomacro/xrunuo | Scripts/Distro/Mobiles/Townfolk/Holy City/Kurlem.cs | C# | gpl-3.0 | 917 |
package instance
import (
"encoding/json"
)
// ID is the identifier for an instance.
type ID string
// Description contains details about an instance.
type Description struct {
ID ID
LogicalID *LogicalID
Tags map[string]string
}
// LogicalID is the logical identifier to associate with an instance.
type LogicalID string
// Attachment is an identifier for a resource to attach to an instance.
type Attachment struct {
// ID is the unique identifier for the attachment.
ID string
// Type is the kind of attachment. This allows multiple attachments of different types, with the supported
// types defined by the plugin.
Type string
}
// Spec is a specification of an instance to be provisioned
type Spec struct {
// Properties is the opaque instance plugin configuration.
Properties *json.RawMessage
// Tags are metadata that describes an instance.
Tags map[string]string
// Init is the boot script to execute when the instance is created.
Init string
// LogicalID is the logical identifier assigned to this instance, which may be absent.
LogicalID *LogicalID
// Attachments are instructions for external entities that should be attached to the instance.
Attachments []Attachment
}
| anarcher/infrakit.gcp | vendor/github.com/docker/infrakit/pkg/spi/instance/types.go | GO | gpl-3.0 | 1,223 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2014 René Samselnig
#
# This file is part of Database Navigator.
#
# Database Navigator 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.
#
# Database Navigator 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 Database Navigator. If not, see <http://www.gnu.org/licenses/>.
#
import sys
import re
import codecs
from collections import Counter
filename = sys.argv[1]
with codecs.open(filename, encoding='utf-8') as f:
text = f.read()
m = re.findall(r'^#{2,3} .*$', text, re.MULTILINE)
def title(s):
return re.sub(r'#+ ', '', s)
def fragment(s):
return '#' + re.sub(r'[^a-z-]', '', re.sub(r'#+ ', '', s).replace(' ', '-').lower())
def depth(s):
return len(re.match(r'(#*)', s).group(0))
c = Counter()
toc = []
for header in m:
t = title(header)
f = fragment(header)
d = depth(header)
if c[f] > 0:
toc.append('{}- [{}]({}-{})'.format('\t'*(d-2), t, f, c[f]))
else:
toc.append('{}- [{}]({})'.format('\t'*(d-2), t, f))
c[f] += 1
with codecs.open(filename, 'w', encoding='utf-8') as f:
f.write(text.replace('[TOC]', '\n'.join(toc)))
| resamsel/dbmanagr | scripts/toc.py | Python | gpl-3.0 | 1,614 |
# -*- coding: utf-8 -*-
"""
pygments.plugin
~~~~~~~~~~~~~~~
Pygments setuptools plugin interface. The methods defined
here also work if setuptools isn't installed but they just
return nothing.
lexer plugins::
[pygments.lexers]
yourlexer = yourmodule:YourLexer
formatter plugins::
[pygments.formatters]
yourformatter = yourformatter:YourFormatter
/.ext = yourformatter:YourFormatter
As you can see, you can define extensions for the formatter
with a leading slash.
syntax plugins::
[pygments.styles]
yourstyle = yourstyle:YourStyle
filter plugin::
[pygments.filter]
yourfilter = yourfilter:YourFilter
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import unicode_literals
try:
import pkg_resources
except ImportError:
pkg_resources = None
LEXER_ENTRY_POINT = 'pygments.lexers'
FORMATTER_ENTRY_POINT = 'pygments.formatters'
STYLE_ENTRY_POINT = 'pygments.styles'
FILTER_ENTRY_POINT = 'pygments.filters'
def find_plugin_lexers():
if pkg_resources is None:
return
for entrypoint in pkg_resources.iter_entry_points(LEXER_ENTRY_POINT):
yield entrypoint.load()
def find_plugin_formatters():
if pkg_resources is None:
return
for entrypoint in pkg_resources.iter_entry_points(FORMATTER_ENTRY_POINT):
yield entrypoint.name, entrypoint.load()
def find_plugin_styles():
if pkg_resources is None:
return
for entrypoint in pkg_resources.iter_entry_points(STYLE_ENTRY_POINT):
yield entrypoint.name, entrypoint.load()
def find_plugin_filters():
if pkg_resources is None:
return
for entrypoint in pkg_resources.iter_entry_points(FILTER_ENTRY_POINT):
yield entrypoint.name, entrypoint.load()
| davy39/eric | ThirdParty/Pygments/pygments/plugin.py | Python | gpl-3.0 | 1,903 |
package com.amaze.filemanager.filesystem;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.provider.DocumentFile;
import com.amaze.filemanager.exceptions.RootNotPermittedException;
import com.amaze.filemanager.utils.DataUtils;
import com.amaze.filemanager.utils.cloud.CloudUtil;
import com.amaze.filemanager.utils.Logger;
import com.amaze.filemanager.utils.MainActivityHelper;
import com.amaze.filemanager.utils.OTGUtil;
import com.amaze.filemanager.utils.OpenMode;
import com.amaze.filemanager.utils.RootUtils;
import com.cloudrail.si.interfaces.CloudStorage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
/**
* Created by arpitkh996 on 13-01-2016, modified by Emmanuel Messulam<emmanuelbendavid@gmail.com>
*/
public class Operations {
// reserved characters by OS, shall not be allowed in file names
private static final String FOREWARD_SLASH = "/";
private static final String BACKWARD_SLASH = "\\";
private static final String COLON = ":";
private static final String ASTERISK = "*";
private static final String QUESTION_MARK = "?";
private static final String QUOTE = "\"";
private static final String GREATER_THAN = ">";
private static final String LESS_THAN = "<";
private static final String FAT = "FAT";
private DataUtils dataUtils = DataUtils.getInstance();
public interface ErrorCallBack {
/**
* Callback fired when file being created in process already exists
*
* @param file
*/
void exists(HFile file);
/**
* Callback fired when creating new file/directory and required storage access framework permission
* to access SD Card is not available
*
* @param file
*/
void launchSAF(HFile file);
/**
* Callback fired when renaming file and required storage access framework permission to access
* SD Card is not available
*
* @param file
* @param file1
*/
void launchSAF(HFile file, HFile file1);
/**
* Callback fired when we're done processing the operation
*
* @param hFile
* @param b defines whether operation was successful
*/
void done(HFile hFile, boolean b);
/**
* Callback fired when an invalid file name is found.
*
* @param file
*/
void invalidName(HFile file);
}
public static void mkdir(@NonNull final HFile file, final Context context, final boolean rootMode,
@NonNull final ErrorCallBack errorCallBack) {
new AsyncTask<Void, Void, Void>() {
private DataUtils dataUtils = DataUtils.getInstance();
@Override
protected Void doInBackground(Void... params) {
// checking whether filename is valid or a recursive call possible
if (MainActivityHelper.isNewDirectoryRecursive(file) ||
!Operations.isFileNameValid(file.getName(context))) {
errorCallBack.invalidName(file);
return null;
}
if (file.exists()) {
errorCallBack.exists(file);
return null;
}
if (file.isSmb()) {
try {
file.getSmbFile(2000).mkdirs();
} catch (SmbException e) {
Logger.log(e, file.getPath(), context);
errorCallBack.done(file, false);
return null;
}
errorCallBack.done(file, file.exists());
return null;
} else if (file.isOtgFile()) {
// first check whether new directory already exists
DocumentFile directoryToCreate = OTGUtil.getDocumentFile(file.getPath(), context, false);
if (directoryToCreate != null) errorCallBack.exists(file);
DocumentFile parentDirectory = OTGUtil.getDocumentFile(file.getParent(), context, false);
if (parentDirectory.isDirectory()) {
parentDirectory.createDirectory(file.getName(context));
errorCallBack.done(file, true);
} else errorCallBack.done(file, false);
return null;
} else if (file.isDropBoxFile()) {
CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);
try {
cloudStorageDropbox.createFolder(CloudUtil.stripPath(OpenMode.DROPBOX, file.getPath()));
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isBoxFile()) {
CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);
try {
cloudStorageBox.createFolder(CloudUtil.stripPath(OpenMode.BOX, file.getPath()));
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isOneDriveFile()) {
CloudStorage cloudStorageOneDrive = dataUtils.getAccount(OpenMode.ONEDRIVE);
try {
cloudStorageOneDrive.createFolder(CloudUtil.stripPath(OpenMode.ONEDRIVE, file.getPath()));
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isGoogleDriveFile()) {
CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);
try {
cloudStorageGdrive.createFolder(CloudUtil.stripPath(OpenMode.GDRIVE, file.getPath()));
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else {
if (file.isLocal() || file.isRoot()) {
int mode = checkFolder(new File(file.getParent()), context);
if (mode == 2) {
errorCallBack.launchSAF(file);
return null;
}
if (mode == 1 || mode == 0)
FileUtil.mkdir(file.getFile(), context);
if (!file.exists() && rootMode) {
file.setMode(OpenMode.ROOT);
if (file.exists()) errorCallBack.exists(file);
try {
RootUtils.mkDir(file.getParent(context), file.getName(context));
} catch (RootNotPermittedException e) {
Logger.log(e, file.getPath(), context);
}
errorCallBack.done(file, file.exists());
return null;
}
errorCallBack.done(file, file.exists());
return null;
}
errorCallBack.done(file, file.exists());
}
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public static void mkfile(@NonNull final HFile file, final Context context, final boolean rootMode,
@NonNull final ErrorCallBack errorCallBack) {
new AsyncTask<Void, Void, Void>() {
private DataUtils dataUtils = DataUtils.getInstance();
@Override
protected Void doInBackground(Void... params) {
// check whether filename is valid or not
if (!Operations.isFileNameValid(file.getName(context))) {
errorCallBack.invalidName(file);
return null;
}
if (file.exists()) {
errorCallBack.exists(file);
return null;
}
if (file.isSmb()) {
try {
file.getSmbFile(2000).createNewFile();
} catch (SmbException e) {
Logger.log(e, file.getPath(), context);
errorCallBack.done(file, false);
return null;
}
errorCallBack.done(file, file.exists());
return null;
} else if (file.isDropBoxFile()) {
CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);
try {
byte[] tempBytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
cloudStorageDropbox.upload(CloudUtil.stripPath(OpenMode.DROPBOX, file.getPath()),
byteArrayInputStream, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isBoxFile()) {
CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);
try {
byte[] tempBytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
cloudStorageBox.upload(CloudUtil.stripPath(OpenMode.BOX, file.getPath()),
byteArrayInputStream, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isOneDriveFile()) {
CloudStorage cloudStorageOneDrive = dataUtils.getAccount(OpenMode.ONEDRIVE);
try {
byte[] tempBytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
cloudStorageOneDrive.upload(CloudUtil.stripPath(OpenMode.ONEDRIVE, file.getPath()),
byteArrayInputStream, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isGoogleDriveFile()) {
CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);
try {
byte[] tempBytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
cloudStorageGdrive.upload(CloudUtil.stripPath(OpenMode.GDRIVE, file.getPath()),
byteArrayInputStream, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isOtgFile()) {
// first check whether new file already exists
DocumentFile fileToCreate = OTGUtil.getDocumentFile(file.getPath(), context, false);
if (fileToCreate != null) errorCallBack.exists(file);
DocumentFile parentDirectory = OTGUtil.getDocumentFile(file.getParent(), context, false);
if (parentDirectory.isDirectory()) {
parentDirectory.createFile(file.getName(context).substring(file.getName().lastIndexOf(".")),
file.getName(context));
errorCallBack.done(file, true);
} else errorCallBack.done(file, false);
return null;
} else {
if (file.isLocal() || file.isRoot()) {
int mode = checkFolder(new File(file.getParent()), context);
if (mode == 2) {
errorCallBack.launchSAF(file);
return null;
}
if (mode == 1 || mode == 0)
try {
FileUtil.mkfile(file.getFile(), context);
} catch (IOException e) {
}
if (!file.exists() && rootMode) {
file.setMode(OpenMode.ROOT);
if (file.exists()) errorCallBack.exists(file);
try {
RootUtils.mkFile(file.getPath());
} catch (RootNotPermittedException e) {
Logger.log(e, file.getPath(), context);
}
errorCallBack.done(file, file.exists());
return null;
}
errorCallBack.done(file, file.exists());
return null;
}
errorCallBack.done(file, file.exists());
}
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public static void rename(final HFile oldFile, final HFile newFile, final boolean rootMode,
final Context context, final ErrorCallBack errorCallBack) {
new AsyncTask<Void, Void, Void>() {
private DataUtils dataUtils = DataUtils.getInstance();
@Override
protected Void doInBackground(Void... params) {
// check whether file names for new file are valid or recursion occurs
if (MainActivityHelper.isNewDirectoryRecursive(newFile) ||
!Operations.isFileNameValid(newFile.getName(context))) {
errorCallBack.invalidName(newFile);
return null;
}
if (newFile.exists()) {
errorCallBack.exists(newFile);
return null;
}
if (oldFile.isSmb()) {
try {
SmbFile smbFile = new SmbFile(oldFile.getPath());
SmbFile smbFile1 = new SmbFile(newFile.getPath());
if (smbFile1.exists()) {
errorCallBack.exists(newFile);
return null;
}
smbFile.renameTo(smbFile1);
if (!smbFile.exists() && smbFile1.exists())
errorCallBack.done(newFile, true);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SmbException e) {
e.printStackTrace();
}
return null;
} else if (oldFile.isDropBoxFile()) {
CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);
try {
cloudStorageDropbox.move(CloudUtil.stripPath(OpenMode.DROPBOX, oldFile.getPath()),
CloudUtil.stripPath(OpenMode.DROPBOX, newFile.getPath()));
errorCallBack.done(newFile, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(newFile, false);
}
} else if (oldFile.isBoxFile()) {
CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);
try {
cloudStorageBox.move(CloudUtil.stripPath(OpenMode.BOX, oldFile.getPath()),
CloudUtil.stripPath(OpenMode.BOX, newFile.getPath()));
errorCallBack.done(newFile, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(newFile, false);
}
} else if (oldFile.isOneDriveFile()) {
CloudStorage cloudStorageOneDrive = dataUtils.getAccount(OpenMode.ONEDRIVE);
try {
cloudStorageOneDrive.move(CloudUtil.stripPath(OpenMode.ONEDRIVE, oldFile.getPath()),
CloudUtil.stripPath(OpenMode.ONEDRIVE, newFile.getPath()));
errorCallBack.done(newFile, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(newFile, false);
}
} else if (oldFile.isGoogleDriveFile()) {
CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);
try {
cloudStorageGdrive.move(CloudUtil.stripPath(OpenMode.GDRIVE, oldFile.getPath()),
CloudUtil.stripPath(OpenMode.GDRIVE, newFile.getPath()));
errorCallBack.done(newFile, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(newFile, false);
}
} else if (oldFile.isOtgFile()) {
DocumentFile oldDocumentFile = OTGUtil.getDocumentFile(oldFile.getPath(), context, false);
DocumentFile newDocumentFile = OTGUtil.getDocumentFile(newFile.getPath(), context, false);
if (newDocumentFile != null) {
errorCallBack.exists(newFile);
return null;
}
errorCallBack.done(newFile, oldDocumentFile.renameTo(newFile.getName(context)));
return null;
} else {
File file = new File(oldFile.getPath());
File file1 = new File(newFile.getPath());
switch (oldFile.getMode()) {
case FILE:
int mode = checkFolder(file.getParentFile(), context);
if (mode == 2) {
errorCallBack.launchSAF(oldFile, newFile);
} else if (mode == 1 || mode == 0) {
try {
FileUtil.renameFolder(file, file1, context);
} catch (RootNotPermittedException e) {
e.printStackTrace();
}
boolean a = !file.exists() && file1.exists();
if (!a && rootMode) {
try {
RootUtils.rename(file.getPath(), file1.getPath());
} catch (Exception e) {
Logger.log(e, oldFile.getPath() + "\n" + newFile.getPath(), context);
}
oldFile.setMode(OpenMode.ROOT);
newFile.setMode(OpenMode.ROOT);
a = !file.exists() && file1.exists();
}
errorCallBack.done(newFile, a);
return null;
}
break;
case ROOT:
try {
RootUtils.rename(file.getPath(), file1.getPath());
} catch (Exception e) {
Logger.log(e, oldFile.getPath() + "\n" + newFile.getPath(), context);
}
newFile.setMode(OpenMode.ROOT);
errorCallBack.done(newFile, true);
break;
}
}
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private static int checkFolder(final File folder, Context context) {
boolean lol = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
if (lol) {
boolean ext = FileUtil.isOnExtSdCard(folder, context);
if (ext) {
if (!folder.exists() || !folder.isDirectory()) {
return 0;
}
// On Android 5, trigger storage access framework.
if (!FileUtil.isWritableNormalOrSaf(folder, context)) {
return 2;
}
return 1;
}
} else if (Build.VERSION.SDK_INT == 19) {
// Assume that Kitkat workaround works
if (FileUtil.isOnExtSdCard(folder, context)) return 1;
}
// file not on external sd card
if (FileUtil.isWritable(new File(folder, "DummyFile"))) {
return 1;
} else {
return 0;
}
}
/**
* Well, we wouldn't want to copy when the target is inside the source
* otherwise it'll end into a loop
*
* @param sourceFile
* @param targetFile
* @return true when copy loop is possible
*/
public static boolean isCopyLoopPossible(BaseFile sourceFile, HFile targetFile) {
return targetFile.getPath().contains(sourceFile.getPath());
}
/**
* Validates file name
* special reserved characters shall not be allowed in the file names on FAT filesystems
*
* @param fileName the filename, not the full path!
* @return boolean if the file name is valid or invalid
*/
public static boolean isFileNameValid(String fileName) {
//String fileName = builder.substring(builder.lastIndexOf("/")+1, builder.length());
// TODO: check file name validation only for FAT filesystems
return !(fileName.contains(ASTERISK) || fileName.contains(BACKWARD_SLASH) ||
fileName.contains(COLON) || fileName.contains(FOREWARD_SLASH) ||
fileName.contains(GREATER_THAN) || fileName.contains(LESS_THAN) ||
fileName.contains(QUESTION_MARK) || fileName.contains(QUOTE));
}
private static boolean isFileSystemFAT(String mountPoint) {
String[] args = new String[]{"/bin/bash", "-c", "df -DO_NOT_REPLACE | awk '{print $1,$2,$NF}' | grep \"^"
+ mountPoint + "\""};
try {
Process proc = new ProcessBuilder(args).start();
OutputStream outputStream = proc.getOutputStream();
String buffer = null;
outputStream.write(buffer.getBytes());
return buffer != null && buffer.contains(FAT);
} catch (IOException e) {
e.printStackTrace();
// process interrupted, returning true, as a word of cation
return true;
}
}
}
| martincz/AmazeFileManager | src/main/java/com/amaze/filemanager/filesystem/Operations.java | Java | gpl-3.0 | 24,347 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "qmljstoolsplugin.h"
#include "qmljsmodelmanager.h"
#include "qmljsfunctionfilter.h"
#include "qmljslocatordata.h"
#include "qmljscodestylesettingspage.h"
#include "qmljstoolsconstants.h"
#include "qmljstoolssettings.h"
#include "qmljsbundleprovider.h"
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <QMenu>
using namespace Core;
namespace QmlJSTools {
namespace Internal {
enum { debug = 0 };
class QmlJSToolsPluginPrivate : public QObject
{
public:
QmlJSToolsPluginPrivate();
QmlJSToolsSettings settings;
ModelManager modelManager;
QAction resetCodeModelAction{QmlJSToolsPlugin::tr("Reset Code Model"), nullptr};
LocatorData locatorData;
FunctionFilter functionFilter{&locatorData};
QmlJSCodeStyleSettingsPage codeStyleSettingsPage;
BasicBundleProvider basicBundleProvider;
};
QmlJSToolsPlugin::~QmlJSToolsPlugin()
{
delete d;
}
bool QmlJSToolsPlugin::initialize(const QStringList &arguments, QString *error)
{
Q_UNUSED(arguments)
Q_UNUSED(error)
d = new QmlJSToolsPluginPrivate;
return true;
}
QmlJSToolsPluginPrivate::QmlJSToolsPluginPrivate()
{
// Core::VcsManager *vcsManager = Core::VcsManager::instance();
// Core::DocumentManager *documentManager = Core::DocumentManager::instance();
// connect(vcsManager, &Core::VcsManager::repositoryChanged,
// &d->modelManager, &ModelManager::updateModifiedSourceFiles);
// connect(documentManager, &DocumentManager::filesChangedInternally,
// &d->modelManager, &ModelManager::updateSourceFiles);
// Menus
ActionContainer *mtools = ActionManager::actionContainer(Core::Constants::M_TOOLS);
ActionContainer *mqmljstools = ActionManager::createMenu(Constants::M_TOOLS_QMLJS);
QMenu *menu = mqmljstools->menu();
menu->setTitle(QmlJSToolsPlugin::tr("&QML/JS"));
menu->setEnabled(true);
mtools->addMenu(mqmljstools);
// Update context in global context
Command *cmd = ActionManager::registerAction(
&resetCodeModelAction, Constants::RESET_CODEMODEL);
connect(&resetCodeModelAction, &QAction::triggered,
&modelManager, &ModelManager::resetCodeModel);
mqmljstools->addAction(cmd);
// Watch task progress
connect(ProgressManager::instance(), &ProgressManager::taskStarted, this,
[this](Core::Id type) {
if (type == QmlJS::Constants::TASK_INDEX)
resetCodeModelAction.setEnabled(false);
});
connect(ProgressManager::instance(), &ProgressManager::allTasksFinished,
[this](Core::Id type) {
if (type == QmlJS::Constants::TASK_INDEX)
resetCodeModelAction.setEnabled(true);
});
}
void QmlJSToolsPlugin::extensionsInitialized()
{
d->modelManager.delayedInitialization();
}
} // Internal
} // QmlJSTools
| sailfish-sdk/sailfish-qtcreator | src/plugins/qmljstools/qmljstoolsplugin.cpp | C++ | gpl-3.0 | 4,284 |
<?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/>.
/**
* Strings for component 'theme_overlay', language 'es', branch 'MOODLE_22_STABLE'
*
* @package theme_overlay
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['configtitle'] = 'Ajustes Overlay';
$string['customcss'] = 'CSS personalizado';
$string['customcssdesc'] = 'Cualquier CSS que introduzca aquí será agregado a todas las páginas, permitiéndole personalizar con facilidad este tema.';
$string['footertext'] = 'Texto del pie de página';
$string['footertextdesc'] = 'Ajustar una nota o texto a pie de página.';
$string['headercolor'] = 'Color de la cabecera';
$string['headercolordesc'] = 'Color de fondo de la cabecera.';
$string['linkcolor'] = 'Color de los enlaces';
$string['linkcolordesc'] = 'Esta opción ajusta el color de los enlaces en el tema';
$string['pluginname'] = 'Overlay';
$string['region-side-post'] = 'Derecha';
$string['region-side-pre'] = 'Izquierda';
| danielbonetto/twig_MVC | lang/es/theme_overlay.php | PHP | gpl-3.0 | 1,725 |
/*
Copyright (C) 2014-2019 de4dot@gmail.com
This file is part of dnSpy
dnSpy 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.
dnSpy 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 dnSpy. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using dnSpy.Contracts.Images;
using dnSpy.Contracts.Menus;
using dnSpy.Contracts.ToolWindows;
using dnSpy.Contracts.ToolWindows.App;
namespace dnSpy.MainApp {
sealed class ToolWindowGroupContext {
public readonly IDsToolWindowService DsToolWindowService;
public readonly IToolWindowGroupService ToolWindowGroupService;
public readonly IToolWindowGroup ToolWindowGroup;
public ToolWindowGroupContext(IDsToolWindowService toolWindowService, IToolWindowGroup toolWindowGroup) {
DsToolWindowService = toolWindowService;
ToolWindowGroupService = toolWindowGroup.ToolWindowGroupService;
ToolWindowGroup = toolWindowGroup;
}
}
abstract class CtxMenuToolWindowGroupCommand : MenuItemBase<ToolWindowGroupContext> {
protected sealed override object CachedContextKey => ContextKey;
static readonly object ContextKey = new object();
protected sealed override ToolWindowGroupContext? CreateContext(IMenuItemContext context) => CreateContextInternal(context);
readonly IDsToolWindowService toolWindowService;
protected CtxMenuToolWindowGroupCommand(IDsToolWindowService toolWindowService) => this.toolWindowService = toolWindowService;
protected ToolWindowGroupContext? CreateContextInternal(IMenuItemContext context) {
if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_TOOLWINDOW_TABCONTROL_GUID))
return null;
var twg = context.Find<IToolWindowGroup>();
if (twg is null || !toolWindowService.Owns(twg))
return null;
return new ToolWindowGroupContext(toolWindowService, twg);
}
}
[ExportMenuItem(Header = "res:HideToolWindowCommand", InputGestureText = "res:ShortCutKeyShiftEsc", Icon = DsImagesAttribute.TableViewNameOnly, Group = MenuConstants.GROUP_CTX_TOOLWINS_CLOSE, Order = 10)]
sealed class HideTWCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
HideTWCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroup.CloseActiveTabCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroup.CloseActiveTab();
}
[ExportMenuItem(Header = "res:HideAllToolWindowsCommand", Icon = DsImagesAttribute.CloseDocumentGroup, Group = MenuConstants.GROUP_CTX_TOOLWINS_CLOSE, Order = 20)]
sealed class CloseAllTabsTWCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
CloseAllTabsTWCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseAllTabsCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseAllTabs();
}
static class CmdConstants {
public const string MOVE_CONTENT_GUID = "D54D52CB-A6FC-408C-9A52-EA0D53AEEC3A";
public const string GROUP_MOVE_CONTENT = "0,92C51A9F-DE4B-4D7F-B1DC-AAA482936B5C";
public const string MOVE_GROUP_GUID = "047ECD64-82EF-4774-9C0A-330A61989432";
public const string GROUP_MOVE_GROUP = "0,174B60EE-279F-4DA4-9F07-44FFD03E4421";
}
[ExportMenuItem(Header = "res:MoveToolWindowCommand", Guid = CmdConstants.MOVE_CONTENT_GUID, Group = MenuConstants.GROUP_CTX_TOOLWINS_CLOSE, Order = 30)]
sealed class MoveTWCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTWCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override void Execute(ToolWindowGroupContext context) => Debug.Fail("Shouldn't be here");
}
[ExportMenuItem(Header = "res:MoveToolWindowGroupCommand", Guid = CmdConstants.MOVE_GROUP_GUID, Group = MenuConstants.GROUP_CTX_TOOLWINS_CLOSE, Order = 40)]
sealed class MoveGroupTWCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveGroupTWCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroup.TabContents.Count() > 1;
public override void Execute(ToolWindowGroupContext context) => Debug.Fail("Shouldn't be here");
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_CONTENT_GUID, Header = "res:MoveTopCommand", Icon = DsImagesAttribute.ToolstripPanelTop, Group = CmdConstants.GROUP_MOVE_CONTENT, Order = 0)]
sealed class MoveTWTopCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTWTopCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Top);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Top);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_CONTENT_GUID, Header = "res:MoveLeftCommand", Icon = DsImagesAttribute.ToolstripPanelLeft, Group = CmdConstants.GROUP_MOVE_CONTENT, Order = 10)]
sealed class MoveTWLeftCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTWLeftCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Left);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Left);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_CONTENT_GUID, Header = "res:MoveRightCommand", Icon = DsImagesAttribute.ToolstripPanelRight, Group = CmdConstants.GROUP_MOVE_CONTENT, Order = 20)]
sealed class MoveTWRightCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTWRightCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Right);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Right);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_CONTENT_GUID, Header = "res:MoveBottomCommand", Icon = DsImagesAttribute.ToolstripPanelBottom, Group = CmdConstants.GROUP_MOVE_CONTENT, Order = 30)]
sealed class MoveTWBottomCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTWBottomCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Bottom);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Bottom);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_GROUP_GUID, Header = "res:MoveTopCommand", Icon = DsImagesAttribute.ToolstripPanelTop, Group = CmdConstants.GROUP_MOVE_GROUP, Order = 0)]
sealed class MoveGroupTWTopCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveGroupTWTopCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup, AppToolWindowLocation.Top);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup, AppToolWindowLocation.Top);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_GROUP_GUID, Header = "res:MoveLeftCommand", Icon = DsImagesAttribute.ToolstripPanelLeft, Group = CmdConstants.GROUP_MOVE_GROUP, Order = 10)]
sealed class MoveGroupTWLeftCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveGroupTWLeftCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup, AppToolWindowLocation.Left);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup, AppToolWindowLocation.Left);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_GROUP_GUID, Header = "res:MoveRightCommand", Icon = DsImagesAttribute.ToolstripPanelRight, Group = CmdConstants.GROUP_MOVE_GROUP, Order = 20)]
sealed class MoveGroupTWRightCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveGroupTWRightCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup, AppToolWindowLocation.Right);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup, AppToolWindowLocation.Right);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_GROUP_GUID, Header = "res:MoveBottomCommand", Icon = DsImagesAttribute.ToolstripPanelBottom, Group = CmdConstants.GROUP_MOVE_GROUP, Order = 30)]
sealed class MoveGroupTWBottomCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveGroupTWBottomCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup, AppToolWindowLocation.Bottom);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup, AppToolWindowLocation.Bottom);
}
[ExportMenuItem(Header = "res:NewHorizontalTabGroupCommand", Icon = DsImagesAttribute.SplitScreenHorizontally, Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 0)]
sealed class NewHorizontalTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
NewHorizontalTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.NewHorizontalTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.NewHorizontalTabGroup();
}
[ExportMenuItem(Header = "res:NewVerticalTabGroupCommand", Icon = DsImagesAttribute.SplitScreenVertically, Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 10)]
sealed class NewVerticalTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
NewVerticalTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.NewVerticalTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.NewVerticalTabGroup();
}
[ExportMenuItem(Header = "res:MoveToNextTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 20)]
sealed class MoveToNextTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveToNextTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveToNextTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveToNextTabGroup();
}
[ExportMenuItem(Header = "res:MoveAllTabsToNextTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 30)]
sealed class MoveAllToNextTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveAllToNextTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveAllToNextTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveAllToNextTabGroup();
}
[ExportMenuItem(Header = "res:MoveToPreviousTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 40)]
sealed class MoveToPreviousTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveToPreviousTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveToPreviousTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveToPreviousTabGroup();
}
[ExportMenuItem(Header = "res:MoveAllToPreviousTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 50)]
sealed class MoveAllToPreviousTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveAllToPreviousTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveAllToPreviousTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveAllToPreviousTabGroup();
}
[ExportMenuItem(Header = "res:CloseTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSCLOSE, Order = 0)]
sealed class CloseTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
CloseTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseTabGroup();
}
[ExportMenuItem(Header = "res:CloseAllTabGroupsButThisCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSCLOSE, Order = 10)]
sealed class CloseAllTabGroupsButThisCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
CloseAllTabGroupsButThisCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseAllTabGroupsButThisCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseAllTabGroupsButThis();
}
[ExportMenuItem(Header = "res:MoveTabGroupAfterNextTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSCLOSE, Order = 20)]
sealed class MoveTabGroupAfterNextTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTabGroupAfterNextTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveTabGroupAfterNextTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveTabGroupAfterNextTabGroup();
}
[ExportMenuItem(Header = "res:MoveTabGroupBeforePreviousTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSCLOSE, Order = 30)]
sealed class MoveTabGroupBeforePreviousTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTabGroupBeforePreviousTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveTabGroupBeforePreviousTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveTabGroupBeforePreviousTabGroup();
}
[ExportMenuItem(Header = "res:MergeAllTabGroupsCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSCLOSE, Order = 40)]
sealed class MergeAllTabGroupsCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MergeAllTabGroupsCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MergeAllTabGroupsCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MergeAllTabGroups();
}
[ExportMenuItem(Header = "res:UseVerticalTabGroupsCommand", Icon = DsImagesAttribute.SplitScreenVertically, Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSVERT, Order = 0)]
sealed class UseVerticalTabGroupsCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
UseVerticalTabGroupsCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.UseVerticalTabGroupsCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.UseVerticalTabGroups();
}
[ExportMenuItem(Header = "res:UseHorizontalTabGroupsCommand", Icon = DsImagesAttribute.SplitScreenHorizontally, Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSVERT, Order = 10)]
sealed class UseHorizontalTabGroupsCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
UseHorizontalTabGroupsCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.UseHorizontalTabGroupsCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.UseHorizontalTabGroups();
}
}
| manojdjoshi/dnSpy | dnSpy/dnSpy/MainApp/DsToolWindowServiceCommands.cs | C# | gpl-3.0 | 19,003 |
'use strict';
/**
* Types of events
* @readonly
* @enum {number}
*/
var EventTypes = {
// Channel Events
/**
* A channel got connected
* @type {EventType}
*/
CONNECT: "connect",
/**
* A channel got disconnected
*/
DISCONNECT: "disconnect",
/**
* A channel got reconnected
*/
RECONNECT: "reconnect",
/**
* A channel is attempting to reconnect
*/
RECONNECTATTEMPT: "reconnect_attempt",
/**
* chatMode
*/
CHATMODE: "chatMode",
/**
* A list of current users in a channel
*/
CHANNELUSERS: "channelUsers",
/**
* A server message
*/
SERVERMESSAGE: "srvMsg",
/**
* A user message
*/
USERMESSAGE: "userMsg",
/**
* A /me message
*/
MEMESSAGE: "meMsg",
/**
* A /me message
*/
WHISPER: "whisper",
/**
* A global message
*/
GLOBALMESSAGE: "globalMsg",
/**
* An instruction/request to clear chat history
*/
CLEARCHAT: "clearChat",
/**
* A request for built-in command help
*/
COMMANDHELP: "commandHelp",
/**
* Whether or not mod tools should be visible
*/
MODTOOLSVISIBLE: "modToolsVisible",
/**
* A list of current mods in a channel
*/
MODLIST: "modList",
/**
* The color of the bot's name in chat
*/
COLOR: "color",
/**
* The online state of a stream
*/
ONLINESTATE: "onlineState",
/**
* A list of users included in a raffle
*/
RAFFLEUSERS: "raffleUsers",
/**
* The winner of a raffle
*/
WONRAFFLE: "wonRaffle",
/**
* runPoll
*/
RUNPOLL: "runPoll",
/**
* showPoll
*/
SHOWPOLL: "showPoll",
/**
* pollVotes
*/
POLLVOTES: "pollVotes",
/**
* voteResponse
*/
VOTERESPONSE: "voteResponse",
/**
* finishPoll
*/
FINISHPOLL: "finishPoll",
/**
* gameMode
*/
GAMEMODE: "gameMode",
/**
* adultMode
*/
ADULTMODE: "adultMode",
/**
* commissionsAvailable
*/
COMMISSIONSAVAILABLE: "commissionsAvailable",
/**
* clearUser
*/
CLEARUSER: "clearUser",
/**
* removeMsg
*/
REMOVEMESSAGE: "removeMsg",
/**
* A PTVAdmin? warning that a channel has adult content but is not in adult mode.
*/
WARNADULT: "warnAdult",
/**
* A PTVAdmin? warning that a channel has gaming content but is not in gaming mode.
*/
WARNGAMING: "warnGaming",
/**
* A PTVAdmin? warning that a channel has movie content.
*/
WARNMOVIES: "warnMovies",
/**
* The multistream status of a channel
*/
MULTISTATUS: "multiStatus",
/**
* Emitted after replaying chat history
*/
ENDHISTORY: "endHistory",
/**
* A list of people being ignored
*/
IGNORES: "ignores",
// Bot Events
/**
* The bot threw an exception
*/
EXCEPTION: "exception",
/**
* A bot command
*/
CHATCOMMAND: "chatCommand",
/**
* A console command
*/
CONSOLECOMMAND: "consoleCommand",
/**
* A command needs completing
*/
COMMANDCOMPLETION: "commandCompletion",
/**
* A plugin was loaded
*/
PLUGINLOADED: "pluginLoaded",
/**
* A plugin was started
*/
PLUGINSTARTED: "pluginStarted",
/**
* A plugin was loaded
*/
PLUGINUNLOADED: "pluginUnloaded",
/**
* A plugin was started
*/
PLUGINSTOPPED: "pluginStopped",
/**
* Used to query plugins if they want to add a cli option/flag
*/
CLIOPTIONS: "CLIOptions"
};
module.exports = EventTypes; | Tschrock/FezBot | modules/eventtypes.js | JavaScript | gpl-3.0 | 3,753 |
namespace Allors.Repository
{
using System;
using Attributes;
#region Allors
[Id("d0f9fc0d-a3c5-46cc-ab00-4c724995fc14")]
#endregion
public partial class FaceToFaceCommunication : CommunicationEvent, Versioned
{
#region inherited properties
public CommunicationEventState PreviousCommunicationEventState { get; set; }
public CommunicationEventState LastCommunicationEventState { get; set; }
public CommunicationEventState CommunicationEventState { get; set; }
public ObjectState[] PreviousObjectStates { get; set; }
public ObjectState[] LastObjectStates { get; set; }
public ObjectState[] ObjectStates { get; set; }
public SecurityToken OwnerSecurityToken { get; set; }
public AccessControl OwnerAccessControl { get; set; }
public DateTime ScheduledStart { get; set; }
public Party[] ToParties { get; set; }
public ContactMechanism[] ContactMechanisms { get; set; }
public Party[] InvolvedParties { get; set; }
public DateTime InitialScheduledStart { get; set; }
public CommunicationEventPurpose[] EventPurposes { get; set; }
public DateTime ScheduledEnd { get; set; }
public DateTime ActualEnd { get; set; }
public WorkEffort[] WorkEfforts { get; set; }
public string Description { get; set; }
public DateTime InitialScheduledEnd { get; set; }
public Party[] FromParties { get; set; }
public string Subject { get; set; }
public Media[] Documents { get; set; }
public Case Case { get; set; }
public Priority Priority { get; set; }
public Person Owner { get; set; }
public string Note { get; set; }
public DateTime ActualStart { get; set; }
public bool SendNotification { get; set; }
public bool SendReminder { get; set; }
public DateTime RemindAt { get; set; }
public Permission[] DeniedPermissions { get; set; }
public SecurityToken[] SecurityTokens { get; set; }
public string Comment { get; set; }
public LocalisedText[] LocalisedComments { get; set; }
public Guid UniqueId { get; set; }
public User CreatedBy { get; set; }
public User LastModifiedBy { get; set; }
public DateTime CreationDate { get; set; }
public DateTime LastModifiedDate { get; set; }
#endregion
#region Allors
[Id("52b8614b-799e-4aea-a012-ea8dbc23f8dd")]
[AssociationId("ac424847-d426-4614-99a2-37c70841c454")]
[RoleId("bcf4a8df-8b57-4b3c-a6e5-f9b56c71a13b")]
#endregion
[Multiplicity(Multiplicity.ManyToMany)]
[Indexed]
[Workspace]
public Party[] Participants { get; set; }
#region Allors
[Id("95ae979f-d549-4ea1-87f0-46aa55e4b14a")]
[AssociationId("d34e4203-0bd2-4fe4-a2ef-9f9f52b49cf9")]
[RoleId("9f67b296-953d-4e04-b94d-6ffece87ceef")]
#endregion
[Size(256)]
[Workspace]
public string Location { get; set; }
#region Versioning
#region Allors
[Id("4339C173-EEAA-4B11-8E54-D96C98B2AF01")]
[AssociationId("41DDA0ED-160D-41B7-A347-CD167A957555")]
[RoleId("DE4BD7DC-B219-4CE6-9F03-4E7F4681BFEC")]
[Indexed]
#endregion
[Multiplicity(Multiplicity.OneToOne)]
[Workspace]
public FaceToFaceCommunicationVersion CurrentVersion { get; set; }
#region Allors
[Id("B97DEBD2-482A-47A7-A7A2-FBC3FD20E7B4")]
[AssociationId("428849DB-9000-4107-A68E-27FA4828344E")]
[RoleId("4F9C3CE5-3418-484C-A770-48D2EDEB6E6A")]
[Indexed]
#endregion
[Multiplicity(Multiplicity.OneToMany)]
[Workspace]
public FaceToFaceCommunicationVersion[] AllVersions { get; set; }
#endregion
#region inherited methods
public void OnBuild(){}
public void OnPostBuild(){}
public void OnPreDerive(){}
public void OnDerive(){}
public void OnPostDerive(){}
public void Cancel(){}
public void Close(){}
public void Reopen(){}
public void Delete(){}
#endregion
}
} | Allors/allors | Domains/Apps/Repository/Domain/Export/Apps/FaceToFaceCommunication.cs | C# | gpl-3.0 | 4,297 |
package com.xxl.job.admin.core.route.strategy;
import com.xxl.job.admin.core.route.ExecutorRouter;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.biz.model.TriggerParam;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* 单个JOB对应的每个执行器,使用频率最低的优先被选举
* a(*)、LFU(Least Frequently Used):最不经常使用,频率/次数
* b、LRU(Least Recently Used):最近最久未使用,时间
*
* Created by xuxueli on 17/3/10.
*/
public class ExecutorRouteLFU extends ExecutorRouter {
private static ConcurrentMap<Integer, HashMap<String, Integer>> jobLfuMap = new ConcurrentHashMap<Integer, HashMap<String, Integer>>();
private static long CACHE_VALID_TIME = 0;
public String route(int jobId, List<String> addressList) {
// cache clear
if (System.currentTimeMillis() > CACHE_VALID_TIME) {
jobLfuMap.clear();
CACHE_VALID_TIME = System.currentTimeMillis() + 1000*60*60*24;
}
// lfu item init
HashMap<String, Integer> lfuItemMap = jobLfuMap.get(jobId); // Key排序可以用TreeMap+构造入参Compare;Value排序暂时只能通过ArrayList;
if (lfuItemMap == null) {
lfuItemMap = new HashMap<String, Integer>();
jobLfuMap.putIfAbsent(jobId, lfuItemMap); // 避免重复覆盖
}
// put new
for (String address: addressList) {
if (!lfuItemMap.containsKey(address) || lfuItemMap.get(address) >1000000 ) {
lfuItemMap.put(address, new Random().nextInt(addressList.size())); // 初始化时主动Random一次,缓解首次压力
}
}
// remove old
List<String> delKeys = new ArrayList<>();
for (String existKey: lfuItemMap.keySet()) {
if (!addressList.contains(existKey)) {
delKeys.add(existKey);
}
}
if (delKeys.size() > 0) {
for (String delKey: delKeys) {
lfuItemMap.remove(delKey);
}
}
// load least userd count address
List<Map.Entry<String, Integer>> lfuItemList = new ArrayList<Map.Entry<String, Integer>>(lfuItemMap.entrySet());
Collections.sort(lfuItemList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Map.Entry<String, Integer> addressItem = lfuItemList.get(0);
String minAddress = addressItem.getKey();
addressItem.setValue(addressItem.getValue() + 1);
return addressItem.getKey();
}
@Override
public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList) {
String address = route(triggerParam.getJobId(), addressList);
return new ReturnT<String>(address);
}
}
| xuxueli/xxl-job | xxl-job-admin/src/main/java/com/xxl/job/admin/core/route/strategy/ExecutorRouteLFU.java | Java | gpl-3.0 | 3,053 |
package com.bioxx.tfc2.gui;
import java.awt.Rectangle;
import java.util.Collection;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import net.minecraft.client.gui.inventory.GuiInventory;
import net.minecraft.client.renderer.InventoryEffectRenderer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.stats.AchievementList;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import com.bioxx.tfc2.Core;
import com.bioxx.tfc2.Reference;
import com.bioxx.tfc2.core.PlayerInventory;
public class GuiInventoryTFC extends InventoryEffectRenderer
{
private float xSizeLow;
private float ySizeLow;
private boolean hasEffect;
protected static final ResourceLocation UPPER_TEXTURE = new ResourceLocation(Reference.ModID+":textures/gui/inventory.png");
protected static final ResourceLocation UPPER_TEXTURE_2X2 = new ResourceLocation(Reference.ModID+":textures/gui/gui_inventory2x2.png");
protected static final ResourceLocation EFFECTS_TEXTURE = new ResourceLocation(Reference.ModID+":textures/gui/inv_effects.png");
protected EntityPlayer player;
protected Slot activeSlot;
public GuiInventoryTFC(EntityPlayer player)
{
super(player.inventoryContainer);
this.allowUserInput = true;
player.addStat(AchievementList.OPEN_INVENTORY, 1);
xSize = 176;
ySize = 102 + PlayerInventory.invYSize;
this.player = player;
}
@Override
protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3)
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
if(player.getEntityData().hasKey("craftingTable"))
Core.bindTexture(UPPER_TEXTURE);
else
Core.bindTexture(UPPER_TEXTURE_2X2);
int k = this.guiLeft;
int l = this.guiTop;
this.drawTexturedModalRect(k, l, 0, 0, this.xSize, 102);
//Draw the player avatar
GuiInventory.drawEntityOnScreen(k + 51, l + 75, 30, k + 51 - this.xSizeLow, l + 75 - 50 - this.ySizeLow, this.mc.player);
PlayerInventory.drawInventory(this, width, height, ySize - PlayerInventory.invYSize);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
@Override
protected void drawGuiContainerForegroundLayer(int par1, int par2)
{
//this.fontRenderer.drawString(I18n.format("container.crafting", new Object[0]), 86, 7, 4210752);
}
@Override
/**
* Called from the main game loop to update the screen.
*/
public void updateScreen()
{
if (this.mc.playerController.isInCreativeMode())
this.mc.displayGuiScreen(new GuiContainerCreative(player));
}
@Override
public void initGui()
{
super.buttonList.clear();
if (this.mc.playerController.isInCreativeMode())
{
this.mc.displayGuiScreen(new GuiContainerCreative(this.mc.player));
}
else
super.initGui();
if (!this.mc.player.getActivePotionEffects().isEmpty())
{
//this.guiLeft = 160 + (this.width - this.xSize - 200) / 2;
this.guiLeft = (this.width - this.xSize) / 2;
this.hasEffect = true;
}
buttonList.clear();
buttonList.add(new GuiInventoryButton(0, new Rectangle(guiLeft+176, guiTop + 3, 25, 20),
new Rectangle(0, 103, 25, 20), Core.translate("gui.Inventory.Inventory"), new Rectangle(1,223,32,32)));
buttonList.add(new GuiInventoryButton(1, new Rectangle(guiLeft+176, guiTop + 22, 25, 20),
new Rectangle(0, 103, 25, 20), Core.translate("gui.Inventory.Skills"), new Rectangle(100,223,32,32)));
buttonList.add(new GuiInventoryButton(2, new Rectangle(guiLeft+176, guiTop + 41, 25, 20),
new Rectangle(0, 103, 25, 20), Core.translate("gui.Calendar.Calendar"), new Rectangle(34,223,32,32)));
buttonList.add(new GuiInventoryButton(3, new Rectangle(guiLeft+176, guiTop + 60, 25, 20),
new Rectangle(0, 103, 25, 20), Core.translate("gui.Inventory.Health"), new Rectangle(67,223,32,32)));
}
@Override
protected void actionPerformed(GuiButton guibutton)
{
//Removed during port
if (guibutton.id == 1)
Minecraft.getMinecraft().displayGuiScreen(new GuiSkills(player));
/*else if (guibutton.id == 2)
Minecraft.getMinecraft().displayGuiScreen(new GuiCalendar(player));*/
else if (guibutton.id == 3)
Minecraft.getMinecraft().displayGuiScreen(new GuiHealth(player));
}
@Override
public void drawScreen(int par1, int par2, float par3)
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
super.drawScreen(par1, par2, par3);
this.xSizeLow = par1;
this.ySizeLow = par2;
if(hasEffect)
displayDebuffEffects();
//removed during port
/*for (int j1 = 0; j1 < this.inventorySlots.inventorySlots.size(); ++j1)
{
Slot slot = (Slot)this.inventorySlots.inventorySlots.get(j1);
if (this.isMouseOverSlot(slot, par1, par2) && slot.func_111238_b())
this.activeSlot = slot;
}*/
}
protected boolean isMouseOverSlot(Slot par1Slot, int par2, int par3)
{
return this.isPointInRegion(par1Slot.xPos, par1Slot.yPos, 16, 16, par2, par3);
}
/**
* Displays debuff/potion effects that are currently being applied to the player
*/
private void displayDebuffEffects()
{
int var1 = this.guiLeft - 124;
int var2 = this.guiTop;
Collection var4 = this.mc.player.getActivePotionEffects();
//Remvoed during port
/*if (!var4.isEmpty())
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_LIGHTING);
int var6 = 33;
if (var4.size() > 5)
var6 = 132 / (var4.size() - 1);
for (Iterator var7 = this.mc.player.getActivePotionEffects().iterator(); var7.hasNext(); var2 += var6)
{
PotionEffect var8 = (PotionEffect)var7.next();
Potion var9 = Potion.potionTypes[var8.getPotionID()] instanceof TFCPotion ?
((TFCPotion) Potion.potionTypes[var8.getPotionID()]) :
Potion.potionTypes[var8.getPotionID()];
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
TFC_Core.bindTexture(EFFECTS_TEXTURE);
this.drawTexturedModalRect(var1, var2, 0, 166, 140, 32);
if (var9.hasStatusIcon())
{
int var10 = var9.getStatusIconIndex();
this.drawTexturedModalRect(var1 + 6, var2 + 7, 0 + var10 % 8 * 18, 198 + var10 / 8 * 18, 18, 18);
}
String var12 = Core.translate(var9.getName());
if (var8.getAmplifier() == 1)
var12 = var12 + " II";
else if (var8.getAmplifier() == 2)
var12 = var12 + " III";
else if (var8.getAmplifier() == 3)
var12 = var12 + " IV";
this.fontRenderer.drawStringWithShadow(var12, var1 + 10 + 18, var2 + 6, 16777215);
String var11 = Potion.getDurationString(var8);
this.fontRenderer.drawStringWithShadow(var11, var1 + 10 + 18, var2 + 6 + 10, 8355711);
}
}*/
}
private long spamTimer;
@Override
protected boolean checkHotbarKeys(int keycode)
{
/*if(this.activeSlot != null && this.activeSlot.slotNumber == 0 && this.activeSlot.getHasStack() &&
this.activeSlot.getStack().getItem() instanceof IFood)
return false;*/
return super.checkHotbarKeys(keycode);
}
private int getEmptyCraftSlot()
{
if(this.inventorySlots.getSlot(4).getStack() == null)
return 4;
if(this.inventorySlots.getSlot(1).getStack() == null)
return 1;
if(this.inventorySlots.getSlot(2).getStack() == null)
return 2;
if(this.inventorySlots.getSlot(3).getStack() == null)
return 3;
if(player.getEntityData().hasKey("craftingTable"))
{
if(this.inventorySlots.getSlot(45).getStack() == null)
return 45;
if(this.inventorySlots.getSlot(46).getStack() == null)
return 46;
if(this.inventorySlots.getSlot(47).getStack() == null)
return 47;
if(this.inventorySlots.getSlot(48).getStack() == null)
return 48;
if(this.inventorySlots.getSlot(49).getStack() == null)
return 49;
}
return -1;
}
}
| CHeuberger/TFC2 | src/Common/com/bioxx/tfc2/gui/GuiInventoryTFC.java | Java | gpl-3.0 | 7,667 |
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=manga_ranobe_storage_app',
'username' => 'travis',
'password' => '',
'charset' => 'utf8',
]; | gunmetal313/MangaRanobeStorageApp | helper_scripts/travis/db_mysql.php | PHP | gpl-3.0 | 198 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* FUEL CMS
* http://www.getfuelcms.com
*
* An open source Content Management System based on the
* Codeigniter framework (http://codeigniter.com)
*
* @package FUEL CMS
* @author David McReynolds @ Daylight Studio
* @copyright Copyright (c) 2015, Run for Daylight LLC.
* @license http://docs.getfuelcms.com/general/license
* @link http://www.getfuelcms.com
*/
// ------------------------------------------------------------------------
/**
* An alternative to the CI Validation class
*
* This class is used in MY_Model and the Form class. Does not require
* post data and is a little more generic then the CI Validation class.
* The <a href="[user_guide_url]helpers/validator_helper">validator_helper</a>
* that contains many helpful rule functions is automatically loaded.
*
* @package FUEL CMS
* @subpackage Libraries
* @category Libraries
* @author David McReynolds @ Daylight Studio
* @link http://docs.getfuelcms.com/libraries/validator
*/
class Validator {
public $field_error_delimiter = "\n"; // delimiter for rendering multiple errors for a field
public $stack_field_errors = FALSE; // stack multiple field errors if any or just replace with the newest
public $register_to_global_errors = TRUE; // will add to the globals error array
public $load_helpers = TRUE; // will automatically load the validator helpers
protected $_fields = array(); // fields to validate
protected $_errors = array(); // errors after running validation
// --------------------------------------------------------------------
/**
* Constructor
*
* Accepts an associative array as input, containing preferences (optional)
*
* @access public
* @param array config preferences
* @return void
*/
public function __construct ($params = array()) {
if (!defined('GLOBAL_ERRORS'))
{
define('GLOBAL_ERRORS', '__ERRORS__');
}
if (!isset($GLOBALS[GLOBAL_ERRORS])) $GLOBALS[GLOBAL_ERRORS] = array();
if (function_exists('get_instance') && $this->load_helpers)
{
$CI =& get_instance();
$CI->load->helper('validator');
}
if (count($params) > 0)
{
$this->initialize($params);
}
}
// --------------------------------------------------------------------
/**
* Initialize preferences
*
* @access public
* @param array
* @return void
*/
public function initialize($params = array())
{
$this->reset();
$this->set_params($params);
}
// --------------------------------------------------------------------
/**
* Set object parameters
*
* @access public
* @param array
* @return void
*/
function set_params($params)
{
if (is_array($params) AND count($params) > 0)
{
foreach ($params as $key => $val)
{
if (isset($this->$key))
{
$this->$key = $val;
}
}
}
}
// --------------------------------------------------------------------
/**
* Add processing rule (function) to an input variable.
* The <a href="[user_guide_url]helpers/validator_helper">validator_helper</a> contains many helpful rule functions you can use
*
* @access public
* @param string key in processing array to assign to rule. Often times its the same name as the field input
* @param string error message
* @param string function for processing
* @param mixed function arguments with the first usually being the posted value. If multiple arguments need to be passed, then you can use an array.
* @return void
*/
public function add_rule($field, $func, $msg, $params = array())
{
if (empty($fields[$field])) $fields[$field] = array();
settype($params, 'array');
// if params are emtpy then we will look in the $_POST
if (empty($params))
{
if (!empty($_POST[$field])) $params = $_POST[$field];
if (empty($params[$field]) AND !empty($_FILES[$field])) $params = $_FILES[$field];
}
$rule = new Validator_Rule($func, $msg, $params);
$this->_fields[$field][] = $rule;
}
// --------------------------------------------------------------------
/**
* Removes rule from validation
*
* @access public
* @param string field to remove
* @param string key for rule (can have more then one rule for a field) (optional)
* @return void
*/
public function remove_rule($field, $func = NULL)
{
if (!empty($func))
{
if (!isset($this->_fields[$field]))
{
return;
}
foreach($this->_fields[$field] as $key => $rule)
{
if ($rule->func == $func)
{
unset($this->_fields[$field][$key]);
}
}
}
else
{
// remove all rules
unset($this->_fields[$field]);
}
}
// --------------------------------------------------------------------
/**
* Runs through validation
*
* @access public
* @param array assoc array of values to validate (optional)
* @param boolean exit on first error? (optional)
* @param boolean reset validation errors (optional)
* @return boolean
*/
public function validate($values = array(), $stop_on_first = FALSE, $reset = TRUE)
{
// reset errors to start with a fresh validation
if ($reset) $this->_errors = array();
//if (empty($values)) $values = $_POST;
if (empty($values))
{
$values = array_keys($this->_fields);
}
else if (!array_key_exists(0, $values)) // detect if it is an associative array and if so just use keys
{
$values = array_keys($values);
}
foreach($values as $key)
{
if (!empty($this->_fields[$key]))
{
$rules = $this->_fields[$key];
foreach($rules as $key2 => $val2)
{
$ok = $val2->run();
if (!$ok)
{
$this->catch_error($val2->get_message(), $key);
if (!empty($stop_on_first)) return FALSE;
}
}
}
}
return $this->is_valid();
}
// --------------------------------------------------------------------
/**
* Checks to see if it validates
*
* @access public
* @return boolean
*/
public function is_valid()
{
return (count($this->_errors) <= 0);
}
// --------------------------------------------------------------------
/**
* Catches error into the global array
*
* @access public
* @param string msg error message
* @param mixed key to identify error message
* @return string key of variable input
*/
public function catch_error($msg, $key = NULL)
{
if (empty($key)) $key = count($this->_errors);
if ($this->stack_field_errors)
{
$this->_errors[$key] = (!empty($this->_errors[$key])) ? $this->_errors[$key] = $this->_errors[$key].$this->field_error_delimiter.$msg : $msg;
}
else
{
$this->_errors[$key] = $msg;
}
if ($this->register_to_global_errors)
{
$GLOBALS[GLOBAL_ERRORS][$key] = $this->_errors[$key];
}
return $key;
}
// --------------------------------------------------------------------
/**
* Catches multiple errors
*
* @access public
* @param array of error messages
* @param key of error message if a single message
* @return string key of variable input
*/
public function catch_errors($errors, $key = NULL)
{
if (is_array($errors))
{
foreach($errors as $key => $val)
{
if (is_int($key))
{
$this->catch_error($val);
}
else
{
$this->catch_error($val, $key);
}
}
}
else
{
return $this->catch_error($errors, $key);
}
}
// --------------------------------------------------------------------
/**
* Retrieve errors
*
* @access public
* @return assoc array of errors and messages
*/
public function get_errors()
{
return $this->_errors;
}
// --------------------------------------------------------------------
/**
* Retrieves a single error
*
* @access public
* @param mixed key to error message
* @return string error message
*/
public function get_error($key)
{
if (!empty($this->_errors[$key]))
{
return $this->_errors[$key];
}
else
{
return NULL;
}
}
// --------------------------------------------------------------------
/**
* Retrieves the last error message
*
* @access public
* @return string error message
*/
public function get_last_error()
{
if (!empty($this->_errors))
{
return end($this->_errors);
}
else
{
return NULL;
}
}
// --------------------------------------------------------------------
/**
* Returns the fields with rules
* @access public
* @return array
*/
public function fields()
{
return $this->_fields;
}
// --------------------------------------------------------------------
/**
* Same as reset
*
* @access public
* @return void
*/
public function clear()
{
$this->reset();
}
// --------------------------------------------------------------------
/**
* Resets rules and errors
* @access public
* @return void
*/
public function reset($remove_fields = TRUE)
{
$this->_errors = array();
if ($remove_fields)
{
$this->_fields = array();
}
}
}
// ------------------------------------------------------------------------
/**
* Validation rule object
*
* @package FUEL CMS
* @subpackage Libraries
* @category Libraries
* @author David McReynolds @ Daylight Studio
* @autodoc FALSE
*/
class Validator_Rule {
public $func; // function to execute that will return TRUE/FALSE
public $msg; // message to be display on error
public $args; // arguments to pass to the function
/**
* Validator rule constructor
*
* @param string function to execute that will return TRUE/FALSE
* @param string message to be display on error
* @param mixed arguments to pass to the function
*/
public function __construct($func, $msg, $args)
{
$this->func = $func;
$this->msg = $msg;
if (!is_array($args))
{
$this->args[] = $args;
}
else if (empty($args))
{ // create first argument
$this->args[] = '';
}
else
{
$this->args = $args;
}
}
/**
* Runs the rules function
*
* @access public
* @return boolean (should return TRUE/FALSE but it depends on the function of course)
*/
public function run()
{
return call_user_func_array($this->func, $this->args);
}
/**
* Retrieve errors
*
* @access public
* @return string error message
*/
public function get_message()
{
return $this->msg;
}
}
/* End of file Validator.php */
/* Location: ./modules/fuel/libraries/Validator.php */ | scotton34/sample | fuel/modules/fuel/libraries/Validator.php | PHP | gpl-3.0 | 10,348 |
/*
* GPXParser.java
*
* Copyright (c) 2012, AlternativeVision. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.alternativevision.gpx;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.alternativevision.gpx.beans.GPX;
import org.alternativevision.gpx.beans.Route;
import org.alternativevision.gpx.beans.Track;
import org.alternativevision.gpx.beans.Waypoint;
import org.alternativevision.gpx.extensions.IExtensionParser;
import org.alternativevision.gpx.types.FixType;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* <p>This class defines methods for parsing and writing gpx files.</p>
* <br>
* Usage for parsing a gpx file into a {@link GPX} object:<br>
* <code>
* GPXParser p = new GPXParser();<br>
* FileInputStream in = new FileInputStream("inFile.gpx");<br>
* GPX gpx = p.parseGPX(in);<br>
* </code>
* <br>
* Usage for writing a {@link GPX} object to a file:<br>
* <code>
* GPXParser p = new GPXParser();<br>
* FileOutputStream out = new FileOutputStream("outFile.gpx");<br>
* p.writeGPX(gpx, out);<br>
* out.close();<br>
* </code>
*/
public class GPXParser {
private ArrayList<IExtensionParser> extensionParsers = new ArrayList<IExtensionParser>();
private Logger logger = Logger.getLogger(this.getClass().getName());
private DocumentBuilderFactory docFactory= DocumentBuilderFactory.newInstance();
private TransformerFactory tFactory = TransformerFactory.newInstance();
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss");
private SimpleDateFormat sdfZ = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss'Z'");
/**
* Adds a new extension parser to be used when parsing a gpx steam
*
* @param parser an instance of a {@link IExtensionParser} implementation
*/
public void addExtensionParser(IExtensionParser parser) {
extensionParsers.add(parser);
}
/**
* Removes an extension parser previously added
*
* @param parser an instance of a {@link IExtensionParser} implementation
*/
public void removeExtensionParser(IExtensionParser parser) {
extensionParsers.remove(parser);
}
public GPX parseGPX(File gpxFile) throws IOException, ParserConfigurationException, SAXException, IOException {
InputStream in = FileUtils.openInputStream(gpxFile);
GPX gpx = parseGPX(in);
in.close();
return gpx;
}
/**
* Parses a stream containing GPX data
*
* @param in the input stream
* @return {@link GPX} object containing parsed data, or null if no gpx data was found in the seream
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
public GPX parseGPX(InputStream in) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilder builder = docFactory.newDocumentBuilder();
Document doc = builder.parse(in);
Node firstChild = doc.getFirstChild();
if( firstChild != null && GPXConstants.GPX_NODE.equals(firstChild.getNodeName())) {
GPX gpx = new GPX();
NamedNodeMap attrs = firstChild.getAttributes();
for(int idx = 0; idx < attrs.getLength(); idx++) {
Node attr = attrs.item(idx);
if(GPXConstants.VERSION_ATTR.equals(attr.getNodeName())) {
gpx.setVersion(attr.getNodeValue());
} else if(GPXConstants.CREATOR_ATTR.equals(attr.getNodeName())) {
gpx.setCreator(attr.getNodeValue());
}
}
NodeList nodes = firstChild.getChildNodes();
if(logger.isDebugEnabled())logger.debug("Found " +nodes.getLength()+ " child nodes. Start parsing ...");
for(int idx = 0; idx < nodes.getLength(); idx++) {
Node currentNode = nodes.item(idx);
if(GPXConstants.WPT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("Found waypoint node. Start parsing...");
Waypoint w = parseWaypoint(currentNode);
if(w!= null) {
logger.info("Add waypoint to gpx data. [waypointName="+ w.getName() + "]");
gpx.addWaypoint(w);
}
} else if(GPXConstants.TRK_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("Found track node. Start parsing...");
Track trk = parseTrack(currentNode);
if(trk!= null) {
logger.info("Add track to gpx data. [trackName="+ trk.getName() + "]");
gpx.addTrack(trk);
}
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("Found extensions node. Start parsing...");
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseGPXExtension(currentNode);
gpx.addExtensionData(parser.getId(), data);
}
} else if(GPXConstants.RTE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("Found route node. Start parsing...");
Route rte = parseRoute(currentNode);
if(rte!= null) {
logger.info("Add route to gpx data. [routeName="+ rte.getName() + "]");
gpx.addRoute(rte);
}
}
}
//TODO: parse route node
return gpx;
} else {
logger.error("FATAL!! - Root node is not gpx.");
}
return null;
}
/**
* Parses a wpt node into a Waypoint object
*
* @param node
* @return Waypoint object with info from the received node
*/
private Waypoint parseWaypoint(Node node) {
if(node == null) {
logger.error("null node received");
return null;
}
Waypoint w = new Waypoint();
NamedNodeMap attrs = node.getAttributes();
//check for lat attribute
Node latNode = attrs.getNamedItem(GPXConstants.LAT_ATTR);
if(latNode != null) {
Double latVal = null;
try {
latVal = Double.parseDouble(latNode.getNodeValue());
} catch(NumberFormatException ex) {
logger.error("bad lat value in waypoint data: " + latNode.getNodeValue());
}
w.setLatitude(latVal);
} else {
logger.warn("no lat value in waypoint data.");
}
//check for lon attribute
Node lonNode = attrs.getNamedItem(GPXConstants.LON_ATTR);
if(lonNode != null) {
Double lonVal = null;
try {
lonVal = Double.parseDouble(lonNode.getNodeValue());
} catch(NumberFormatException ex) {
logger.error("bad lon value in waypoint data: " + lonNode.getNodeValue());
}
w.setLongitude(lonVal);
} else {
logger.warn("no lon value in waypoint data.");
}
NodeList childNodes = node.getChildNodes();
if(childNodes != null) {
for(int idx = 0; idx < childNodes.getLength(); idx++) {
Node currentNode = childNodes.item(idx);
if(GPXConstants.ELE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found ele node in waypoint data");
w.setElevation(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.TIME_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found time node in waypoint data");
w.setTime(getNodeValueAsDate(currentNode));
} else if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found name node in waypoint data");
w.setName(getNodeValueAsString(currentNode));
} else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found cmt node in waypoint data");
w.setComment(getNodeValueAsString(currentNode));
} else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found desc node in waypoint data");
w.setDescription(getNodeValueAsString(currentNode));
} else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found src node in waypoint data");
w.setSrc(getNodeValueAsString(currentNode));
} else if(GPXConstants.MAGVAR_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found magvar node in waypoint data");
w.setMagneticDeclination(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.GEOIDHEIGHT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found geoidheight node in waypoint data");
w.setGeoidHeight(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found link node in waypoint data");
//TODO: parse link
//w.setGeoidHeight(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.SYM_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found sym node in waypoint data");
w.setSym(getNodeValueAsString(currentNode));
} else if(GPXConstants.FIX_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found fix node in waypoint data");
w.setFix(getNodeValueAsFixType(currentNode));
} else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found type node in waypoint data");
w.setType(getNodeValueAsString(currentNode));
} else if(GPXConstants.SAT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found sat node in waypoint data");
w.setSat(getNodeValueAsInteger(currentNode));
} else if(GPXConstants.HDOP_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found hdop node in waypoint data");
w.setHdop(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.VDOP_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found vdop node in waypoint data");
w.setVdop(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.PDOP_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found pdop node in waypoint data");
w.setPdop(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.AGEOFGPSDATA_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found ageofgpsdata node in waypoint data");
w.setAgeOfGPSData(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.DGPSID_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found dgpsid node in waypoint data");
w.setDgpsid(getNodeValueAsInteger(currentNode));
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found extensions node in waypoint data");
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseWaypointExtension(currentNode);
w.addExtensionData(parser.getId(), data);
}
}
}
} else {
if(logger.isDebugEnabled())logger.debug("no child nodes found in waypoint");
}
return w;
}
private Track parseTrack(Node node) {
if(node == null) {
logger.error("null node received");
return null;
}
Track trk = new Track();
NodeList nodes = node.getChildNodes();
if(nodes != null) {
for(int idx = 0; idx < nodes.getLength(); idx++) {
Node currentNode = nodes.item(idx);
if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node name found");
trk.setName(getNodeValueAsString(currentNode));
} else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node cmt found");
trk.setComment(getNodeValueAsString(currentNode));
} else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node desc found");
trk.setDescription(getNodeValueAsString(currentNode));
} else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node src found");
trk.setSrc(getNodeValueAsString(currentNode));
} else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node link found");
//TODO: parse link
//trk.setLink(getNodeValueAsLink(currentNode));
} else if(GPXConstants.NUMBER_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node number found");
trk.setNumber(getNodeValueAsInteger(currentNode));
} else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node type found");
trk.setType(getNodeValueAsString(currentNode));
} else if(GPXConstants.TRKSEG_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node trkseg found");
trk.setTrackPoints(parseTrackSeg(currentNode));
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
if(logger.isDebugEnabled())logger.debug("node extensions found");
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseTrackExtension(currentNode);
trk.addExtensionData(parser.getId(), data);
}
}
}
}
}
return trk;
}
private Route parseRoute(Node node) {
if(node == null) {
logger.error("null node received");
return null;
}
Route rte = new Route();
NodeList nodes = node.getChildNodes();
if(nodes != null) {
for(int idx = 0; idx < nodes.getLength(); idx++) {
Node currentNode = nodes.item(idx);
if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node name found");
rte.setName(getNodeValueAsString(currentNode));
} else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node cmt found");
rte.setComment(getNodeValueAsString(currentNode));
} else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node desc found");
rte.setDescription(getNodeValueAsString(currentNode));
} else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node src found");
rte.setSrc(getNodeValueAsString(currentNode));
} else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node link found");
//TODO: parse link
//rte.setLink(getNodeValueAsLink(currentNode));
} else if(GPXConstants.NUMBER_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node number found");
rte.setNumber(getNodeValueAsInteger(currentNode));
} else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node type found");
rte.setType(getNodeValueAsString(currentNode));
} else if(GPXConstants.RTEPT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node rtept found");
Waypoint wp = parseWaypoint(currentNode);
if(wp!=null) {
rte.addRoutePoint(wp);
}
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
if(logger.isDebugEnabled())logger.debug("node extensions found");
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseRouteExtension(currentNode);
rte.addExtensionData(parser.getId(), data);
}
}
}
}
}
return rte;
}
private ArrayList<Waypoint> parseTrackSeg(Node node) {
if(node == null) {
logger.error("null node received");
return null;
}
ArrayList<Waypoint> trkpts = new ArrayList<Waypoint>();
NodeList nodes = node.getChildNodes();
if(nodes != null) {
for(int idx = 0; idx < nodes.getLength(); idx++) {
Node currentNode = nodes.item(idx);
if(GPXConstants.TRKPT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node name found");
Waypoint wp = parseWaypoint(currentNode);
if(wp!=null) {
trkpts.add(wp);
}
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node extensions found");
/*
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseWaypointExtension(currentNode);
//.addExtensionData(parser.getId(), data);
}
*/
}
}
}
return trkpts;
}
private Double getNodeValueAsDouble(Node node) {
Double val = null;
try {
val = Double.parseDouble(node.getFirstChild().getNodeValue());
} catch (Exception ex) {
logger.error("error parsing Double value form node. val=" + node.getNodeValue(), ex);
}
return val;
}
private Date getNodeValueAsDate(Node node) {
//2012-02-25T09:28:45Z
Date val = null;
try {
val = sdf.parse(node.getFirstChild().getNodeValue());
} catch (Exception ex) {
logger.error("error parsing Date value form node. val=" + node.getNodeName(), ex);
}
return val;
}
private String getNodeValueAsString(Node node) {
String val = null;
try {
val = node.getFirstChild().getNodeValue();
} catch (Exception ex) {
logger.error("error getting String value form node. val=" + node.getNodeName(), ex);
}
return val;
}
private FixType getNodeValueAsFixType(Node node) {
FixType val = null;
try {
val = FixType.returnType(node.getFirstChild().getNodeValue());
} catch (Exception ex) {
logger.error("error getting FixType value form node. val=" + node.getNodeName(), ex);
}
return val;
}
private Integer getNodeValueAsInteger(Node node) {
Integer val = null;
try {
val = Integer.parseInt(node.getFirstChild().getNodeValue());
} catch (Exception ex) {
logger.error("error parsing Integer value form node. val=" + node.getNodeValue(), ex);
}
return val;
}
public void writeGPX(GPX gpx, File gpxFile) throws IOException, ParserConfigurationException, TransformerException {
OutputStream out = FileUtils.openOutputStream(gpxFile);
writeGPX(gpx,out);
out.flush();
out.close();
}
public void writeGPX(GPX gpx, OutputStream out) throws ParserConfigurationException, TransformerException {
DocumentBuilder builder = docFactory.newDocumentBuilder();
Document doc = builder.newDocument();
Node gpxNode = doc.createElement(GPXConstants.GPX_NODE);
addBasicGPXInfoToNode(gpx, gpxNode, doc);
if(gpx.getWaypoints() != null) {
Iterator<Waypoint> itW = gpx.getWaypoints().iterator();
while(itW.hasNext()) {
addWaypointToGPXNode(itW.next(), gpxNode, doc);
}
Iterator<Track> itT = gpx.getTracks().iterator();
while(itT.hasNext()) {
addTrackToGPXNode(itT.next(), gpxNode, doc);
}
Iterator<Route> itR = gpx.getRoutes().iterator();
while(itR.hasNext()) {
addRouteToGPXNode(itR.next(), gpxNode, doc);
}
}
doc.appendChild(gpxNode);
// Use a Transformer for output
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(out);
transformer.transform(source, result);
}
private void addWaypointToGPXNode(Waypoint wpt, Node gpxNode, Document doc) {
addGenericWaypointToGPXNode(GPXConstants.WPT_NODE, wpt, gpxNode, doc);
}
private void addGenericWaypointToGPXNode(String tagName,Waypoint wpt, Node gpxNode, Document doc) {
Node wptNode = doc.createElement(tagName);
NamedNodeMap attrs = wptNode.getAttributes();
if(wpt.getLatitude() != null) {
Node latNode = doc.createAttribute(GPXConstants.LAT_ATTR);
latNode.setNodeValue(wpt.getLatitude().toString());
attrs.setNamedItem(latNode);
}
if(wpt.getLongitude() != null) {
Node longNode = doc.createAttribute(GPXConstants.LON_ATTR);
longNode.setNodeValue(wpt.getLongitude().toString());
attrs.setNamedItem(longNode);
}
if(wpt.getElevation() != null) {
Node node = doc.createElement(GPXConstants.ELE_NODE);
node.appendChild(doc.createTextNode(wpt.getElevation().toString()));
wptNode.appendChild(node);
}
if(wpt.getTime() != null) {
Node node = doc.createElement(GPXConstants.TIME_NODE);
node.appendChild(doc.createTextNode(sdfZ.format(wpt.getTime())));
wptNode.appendChild(node);
}
if(wpt.getMagneticDeclination() != null) {
Node node = doc.createElement(GPXConstants.MAGVAR_NODE);
node.appendChild(doc.createTextNode(wpt.getMagneticDeclination().toString()));
wptNode.appendChild(node);
}
if(wpt.getGeoidHeight() != null) {
Node node = doc.createElement(GPXConstants.GEOIDHEIGHT_NODE);
node.appendChild(doc.createTextNode(wpt.getGeoidHeight().toString()));
wptNode.appendChild(node);
}
if(wpt.getName() != null) {
Node node = doc.createElement(GPXConstants.NAME_NODE);
node.appendChild(doc.createTextNode(wpt.getName()));
wptNode.appendChild(node);
}
if(wpt.getComment() != null) {
Node node = doc.createElement(GPXConstants.CMT_NODE);
node.appendChild(doc.createTextNode(wpt.getComment()));
wptNode.appendChild(node);
}
if(wpt.getDescription() != null) {
Node node = doc.createElement(GPXConstants.DESC_NODE);
node.appendChild(doc.createTextNode(wpt.getDescription()));
wptNode.appendChild(node);
}
if(wpt.getSrc() != null) {
Node node = doc.createElement(GPXConstants.SRC_NODE);
node.appendChild(doc.createTextNode(wpt.getSrc()));
wptNode.appendChild(node);
}
//TODO: write link node
if(wpt.getSym() != null) {
Node node = doc.createElement(GPXConstants.SYM_NODE);
node.appendChild(doc.createTextNode(wpt.getSym()));
wptNode.appendChild(node);
}
if(wpt.getType() != null) {
Node node = doc.createElement(GPXConstants.TYPE_NODE);
node.appendChild(doc.createTextNode(wpt.getType()));
wptNode.appendChild(node);
}
if(wpt.getFix() != null) {
Node node = doc.createElement(GPXConstants.FIX_NODE);
node.appendChild(doc.createTextNode(wpt.getFix().toString()));
wptNode.appendChild(node);
}
if(wpt.getSat() != null) {
Node node = doc.createElement(GPXConstants.SAT_NODE);
node.appendChild(doc.createTextNode(wpt.getSat().toString()));
wptNode.appendChild(node);
}
if(wpt.getHdop() != null) {
Node node = doc.createElement(GPXConstants.HDOP_NODE);
node.appendChild(doc.createTextNode(wpt.getHdop().toString()));
wptNode.appendChild(node);
}
if(wpt.getVdop() != null) {
Node node = doc.createElement(GPXConstants.VDOP_NODE);
node.appendChild(doc.createTextNode(wpt.getVdop().toString()));
wptNode.appendChild(node);
}
if(wpt.getPdop() != null) {
Node node = doc.createElement(GPXConstants.PDOP_NODE);
node.appendChild(doc.createTextNode(wpt.getPdop().toString()));
wptNode.appendChild(node);
}
if(wpt.getAgeOfGPSData() != null) {
Node node = doc.createElement(GPXConstants.AGEOFGPSDATA_NODE);
node.appendChild(doc.createTextNode(wpt.getAgeOfGPSData().toString()));
wptNode.appendChild(node);
}
if(wpt.getDgpsid() != null) {
Node node = doc.createElement(GPXConstants.DGPSID_NODE);
node.appendChild(doc.createTextNode(wpt.getDgpsid().toString()));
wptNode.appendChild(node);
}
if(wpt.getExtensionsParsed() > 0) {
Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
it.next().writeWaypointExtensionData(node, wpt, doc);
}
wptNode.appendChild(node);
}
gpxNode.appendChild(wptNode);
}
private void addTrackToGPXNode(Track trk, Node gpxNode, Document doc) {
Node trkNode = doc.createElement(GPXConstants.TRK_NODE);
if(trk.getName() != null) {
Node node = doc.createElement(GPXConstants.NAME_NODE);
node.appendChild(doc.createTextNode(trk.getName()));
trkNode.appendChild(node);
}
if(trk.getComment() != null) {
Node node = doc.createElement(GPXConstants.CMT_NODE);
node.appendChild(doc.createTextNode(trk.getComment()));
trkNode.appendChild(node);
}
if(trk.getDescription() != null) {
Node node = doc.createElement(GPXConstants.DESC_NODE);
node.appendChild(doc.createTextNode(trk.getDescription()));
trkNode.appendChild(node);
}
if(trk.getSrc() != null) {
Node node = doc.createElement(GPXConstants.SRC_NODE);
node.appendChild(doc.createTextNode(trk.getSrc()));
trkNode.appendChild(node);
}
//TODO: write link
if(trk.getNumber() != null) {
Node node = doc.createElement(GPXConstants.NUMBER_NODE);
node.appendChild(doc.createTextNode(trk.getNumber().toString()));
trkNode.appendChild(node);
}
if(trk.getType() != null) {
Node node = doc.createElement(GPXConstants.TYPE_NODE);
node.appendChild(doc.createTextNode(trk.getType()));
trkNode.appendChild(node);
}
if(trk.getExtensionsParsed() > 0) {
Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
it.next().writeTrackExtensionData(node, trk, doc);
}
trkNode.appendChild(node);
}
if(trk.getTrackPoints() != null) {
Node trksegNode = doc.createElement(GPXConstants.TRKSEG_NODE);
Iterator<Waypoint> it = trk.getTrackPoints().iterator();
while(it.hasNext()) {
addGenericWaypointToGPXNode(GPXConstants.TRKPT_NODE, it.next(), trksegNode, doc);
}
trkNode.appendChild(trksegNode);
}
gpxNode.appendChild(trkNode);
}
private void addRouteToGPXNode(Route rte, Node gpxNode, Document doc) {
Node trkNode = doc.createElement(GPXConstants.TRK_NODE);
if(rte.getName() != null) {
Node node = doc.createElement(GPXConstants.NAME_NODE);
node.appendChild(doc.createTextNode(rte.getName()));
trkNode.appendChild(node);
}
if(rte.getComment() != null) {
Node node = doc.createElement(GPXConstants.CMT_NODE);
node.appendChild(doc.createTextNode(rte.getComment()));
trkNode.appendChild(node);
}
if(rte.getDescription() != null) {
Node node = doc.createElement(GPXConstants.DESC_NODE);
node.appendChild(doc.createTextNode(rte.getDescription()));
trkNode.appendChild(node);
}
if(rte.getSrc() != null) {
Node node = doc.createElement(GPXConstants.SRC_NODE);
node.appendChild(doc.createTextNode(rte.getSrc()));
trkNode.appendChild(node);
}
//TODO: write link
if(rte.getNumber() != null) {
Node node = doc.createElement(GPXConstants.NUMBER_NODE);
node.appendChild(doc.createTextNode(rte.getNumber().toString()));
trkNode.appendChild(node);
}
if(rte.getType() != null) {
Node node = doc.createElement(GPXConstants.TYPE_NODE);
node.appendChild(doc.createTextNode(rte.getType()));
trkNode.appendChild(node);
}
if(rte.getExtensionsParsed() > 0) {
Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
it.next().writeRouteExtensionData(node, rte, doc);
}
trkNode.appendChild(node);
}
if(rte.getRoutePoints() != null) {
Iterator<Waypoint> it = rte.getRoutePoints().iterator();
while(it.hasNext()) {
addGenericWaypointToGPXNode(GPXConstants.RTEPT_NODE, it.next(), trkNode, doc);
}
}
gpxNode.appendChild(trkNode);
}
private void addBasicGPXInfoToNode(GPX gpx, Node gpxNode, Document doc) {
NamedNodeMap attrs = gpxNode.getAttributes();
if(gpx.getVersion() != null) {
Node verNode = doc.createAttribute(GPXConstants.VERSION_ATTR);
verNode.setNodeValue(gpx.getVersion());
attrs.setNamedItem(verNode);
}
if(gpx.getCreator() != null) {
Node creatorNode = doc.createAttribute(GPXConstants.CREATOR_ATTR);
creatorNode.setNodeValue(gpx.getCreator());
attrs.setNamedItem(creatorNode);
}
if(gpx.getExtensionsParsed() > 0) {
Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
it.next().writeGPXExtensionData(node, gpx, doc);
}
gpxNode.appendChild(node);
}
}
} | RBerliner/freeboard-server | src/main/java/org/alternativevision/gpx/GPXParser.java | Java | gpl-3.0 | 30,515 |
<?php
/**
* This file is part of OXID eShop Community Edition.
*
* OXID eShop Community Edition 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.
*
* OXID eShop Community Edition 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 OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>.
*
* @link http://www.oxid-esales.com
* @package core
* @copyright (C) OXID eSales AG 2003-2012
* @version OXID eShop CE
* @version SVN: $Id: oxvoucherserie.php 47273 2012-07-12 12:47:43Z linas.kukulskis $
*/
/**
* Voucher serie manager.
* Manages list of available Vouchers (fetches, deletes, etc.).
*
* @package model
*/
class oxVoucherSerie extends oxBase
{
/**
* User groups array (default null).
* @var object
*/
protected $_oGroups = null;
/**
* @var string name of current class
*/
protected $_sClassName = 'oxvoucherserie';
/**
* Class constructor, initiates parent constructor (parent::oxBase()).
*/
public function __construct()
{
parent::__construct();
$this->init('oxvoucherseries');
}
/**
* Override delete function so we can delete user group and article or category relations first.
*
* @param string $sOxId object ID (default null)
*
* @return null
*/
public function delete( $sOxId = null )
{
if ( !$sOxId ) {
$sOxId = $this->getId();
}
$this->unsetDiscountRelations();
$this->unsetUserGroups();
$this->deleteVoucherList();
return parent::delete( $sOxId );
}
/**
* Collects and returns user group list.
*
* @return object
*/
public function setUserGroups()
{
if ( $this->_oGroups === null ) {
$this->_oGroups = oxNew( 'oxlist' );
$this->_oGroups->init( 'oxgroups' );
$sViewName = getViewName( "oxgroups" );
$sSelect = "select gr.* from {$sViewName} as gr, oxobject2group as o2g where
o2g.oxobjectid = ". oxDb::getDb()->quote( $this->getId() ) ." and gr.oxid = o2g.oxgroupsid ";
$this->_oGroups->selectString( $sSelect );
}
return $this->_oGroups;
}
/**
* Removes user groups relations.
*
* @return null
*/
public function unsetUserGroups()
{
$oDb = oxDb::getDb();
$sDelete = 'delete from oxobject2group where oxobjectid = ' . $oDb->quote( $this->getId() );
$oDb->execute( $sDelete );
}
/**
* Removes product or dategory relations.
*
* @return null
*/
public function unsetDiscountRelations()
{
$oDb = oxDb::getDb();
$sDelete = 'delete from oxobject2discount where oxobject2discount.oxdiscountid = ' . $oDb->quote( $this->getId() );
$oDb->execute( $sDelete );
}
/**
* Returns array of a vouchers assigned to this serie.
*
* @return array
*/
public function getVoucherList()
{
$oVoucherList = oxNew( 'oxvoucherlist' );
$sSelect = 'select * from oxvouchers where oxvoucherserieid = ' . oxDb::getDb()->quote( $this->getId() );
$oVoucherList->selectString( $sSelect );
return $oVoucherList;
}
/**
* Deletes assigned voucher list.
*
* @return null
*/
public function deleteVoucherList()
{
$oDb = oxDb::getDb();
$sDelete = 'delete from oxvouchers where oxvoucherserieid = ' . $oDb->quote( $this->getId() );
$oDb->execute( $sDelete );
}
/**
* Returns array of vouchers counts.
*
* @return array
*/
public function countVouchers()
{
$aStatus = array();
$oDb = oxDb::getDb();
$sQuery = 'select count(*) as total from oxvouchers where oxvoucherserieid = ' .$oDb->quote( $this->getId() );
$aStatus['total'] = $oDb->getOne( $sQuery );
$sQuery = 'select count(*) as used from oxvouchers where oxvoucherserieid = ' . $oDb->quote( $this->getId() ) . ' and ((oxorderid is not NULL and oxorderid != "") or (oxdateused is not NULL and oxdateused != 0))';
$aStatus['used'] = $oDb->getOne( $sQuery );
$aStatus['available'] = $aStatus['total'] - $aStatus['used'];
return $aStatus;
}
}
| jadzgauskas/oxidce | application/models/oxvoucherserie.php | PHP | gpl-3.0 | 4,795 |
var translations = {
'es': {
'One moment while we<br>log you in':
'Espera un momento mientras<br>iniciamos tu sesión',
'You are now connected to the network':
'Ahora estás conectado a la red',
'Account signups/purchases are disabled in preview mode':
'La inscripciones de cuenta/compras están desactivadas en el modo de vista previa.',
'Notice':
'Aviso',
'Day':
'Día',
'Days':
'Días',
'Hour':
'Hora',
'Hours':
'Horas',
'Minutes':
'Minutos',
'Continue':
'Continuar',
'Thank You for Trying TWC WiFi':
'Gracias por probar TWC WiFi',
'Please purchase a TWC Access Pass to continue using WiFi':
'Adquiere un Pase de acceso (Access Pass) de TWC para continuar usando la red WiFi',
'Your TWC Access Pass has expired. Please select a new Access Pass Now.':
'Tu Access Pass (Pase de acceso) de TWC ha vencido. Selecciona un nuevo Access Pass (Pase de acceso) ahora.',
'Your account information has been pre-populated into the form. If you wish to change any information, you may edit the form before completing the order.':
'El formulario ha sido llenado con la información de tu cuenta. Si deseas modificar algún dato, puedes editar el formulario antes de completar la solicitud.',
'Your Password':
'Tu contraseña',
'Proceed to Login':
'Proceder con el inicio de sesión',
'Payment portal is not available at this moment':
'',
'Redirecting to Payment portal...':
'',
'Could not log you into the network':
'No se pudo iniciar sesión en la red'
}
}
function translate(text, language) {
if (language == 'en')
return text;
if (!translations[language])
return text;
if (!translations[language][text])
return text;
return translations[language][text] || text;
}
| kbeflo/evilportals | archive/optimumwifi/assets/js/xlate.js | JavaScript | gpl-3.0 | 2,089 |
package it.ninjatech.kvo.async.job;
import it.ninjatech.kvo.model.ImageProvider;
import it.ninjatech.kvo.util.Logger;
import java.awt.Dimension;
import java.awt.Image;
import java.util.EnumSet;
public class CacheRemoteImageAsyncJob extends AbstractImageLoaderAsyncJob {
private static final long serialVersionUID = -8459315395025635686L;
private final String path;
private final String type;
private final Dimension size;
private Image image;
public CacheRemoteImageAsyncJob(String id, ImageProvider provider, String path, Dimension size, String type) {
super(id, EnumSet.of(LoadType.Cache, LoadType.Remote), provider);
this.path = path;
this.size = size;
this.type = type;
}
@Override
protected void execute() {
try {
Logger.log("-> executing cache-remote image %s\n", this.id);
this.image = getImage(null, null, this.id, this.path, this.size, this.type);
}
catch (Exception e) {
this.exception = e;
}
}
public Image getImage() {
return this.image;
}
}
| vincenzomazzeo/kodi-video-organizer | src/main/java/it/ninjatech/kvo/async/job/CacheRemoteImageAsyncJob.java | Java | gpl-3.0 | 1,058 |
/******************************************************************************/
/* */
/* X r d C m s L o g i n . c c */
/* */
/* (c) 2007 by the Board of Trustees of the Leland Stanford, Jr., University */
/* All Rights Reserved */
/* Produced by Andrew Hanushevsky for Stanford University under contract */
/* DE-AC02-76-SFO0515 with the Department of Energy */
/* */
/* This file is part of the XRootD software suite. */
/* */
/* XRootD is free software: you can redistribute it and/or modify it under */
/* the terms of the GNU Lesser General Public License as published by the */
/* Free Software Foundation, either version 3 of the License, or (at your */
/* option) any later version. */
/* */
/* XRootD is distributed in the hope that it will be useful, but WITHOUT */
/* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */
/* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public */
/* License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License */
/* along with XRootD in a file called COPYING.LESSER (LGPL license) and file */
/* COPYING (GPL license). If not, see <http://www.gnu.org/licenses/>. */
/* */
/* The copyright holder's institutional names and contributor's names may not */
/* be used to endorse or promote products derived from this software without */
/* specific prior written permission of the institution or contributor. */
/******************************************************************************/
#include <netinet/in.h>
#include "XProtocol/YProtocol.hh"
#include "Xrd/XrdLink.hh"
#include "XrdCms/XrdCmsLogin.hh"
#include "XrdCms/XrdCmsParser.hh"
#include "XrdCms/XrdCmsTalk.hh"
#include "XrdCms/XrdCmsSecurity.hh"
#include "XrdCms/XrdCmsTrace.hh"
#include "XrdOuc/XrdOucPup.hh"
#include "XrdSys/XrdSysError.hh"
#include "XrdSys/XrdSysPthread.hh"
using namespace XrdCms;
/******************************************************************************/
/* Public: A d m i t */
/******************************************************************************/
int XrdCmsLogin::Admit(XrdLink *Link, CmsLoginData &Data)
{
CmsRRHdr myHdr;
CmsLoginData myData;
const char *eText, *Token;
int myDlen, Toksz;
// Get complete request
//
if ((eText = XrdCmsTalk::Attend(Link, myHdr, myBuff, myBlen, myDlen)))
return Emsg(Link, eText, 0);
// If we need to do authentication, do so now
//
if ((Token = XrdCmsSecurity::getToken(Toksz, Link->Host()))
&& !XrdCmsSecurity::Authenticate(Link, Token, Toksz)) return 0;
// Fiddle with the login data structures
//
Data.SID = Data.Paths = 0;
memset(&myData, 0, sizeof(myData));
myData.Mode = Data.Mode;
myData.HoldTime = Data.HoldTime;
myData.Version = Data.Version = kYR_Version;
// Decode the data pointers ans grab the login data
//
if (!Parser.Parse(&Data, myBuff, myBuff+myDlen))
return Emsg(Link, "invalid login data", 0);
// Do authentication now, if needed
//
if ((Token = XrdCmsSecurity::getToken(Toksz, Link->Host())))
if (!XrdCmsSecurity::Authenticate(Link, Token, Toksz)) return 0;
// Send off login reply
//
return (sendData(Link, myData) ? 0 : 1);
}
/******************************************************************************/
/* Private: E m s g */
/******************************************************************************/
int XrdCmsLogin::Emsg(XrdLink *Link, const char *msg, int ecode)
{
Say.Emsg("Login", Link->Name(), "login failed;", msg);
return ecode;
}
/******************************************************************************/
/* Public: L o g i n */
/******************************************************************************/
int XrdCmsLogin::Login(XrdLink *Link, CmsLoginData &Data, int timeout)
{
CmsRRHdr LIHdr;
char WorkBuff[4096], *hList, *wP = WorkBuff;
int n, dataLen;
// Send the data
//
if (sendData(Link, Data)) return kYR_EINVAL;
// Get the response.
//
if ((n = Link->RecvAll((char *)&LIHdr, sizeof(LIHdr), timeout)) < 0)
return Emsg(Link, (n == -ETIMEDOUT ? "timed out" : "rejected"));
// Receive and decode the response. We apparently have protocol version 2.
//
if ((dataLen = static_cast<int>(ntohs(LIHdr.datalen))))
{if (dataLen > (int)sizeof(WorkBuff))
return Emsg(Link, "login reply too long");
if (Link->RecvAll(WorkBuff, dataLen, timeout) < 0)
return Emsg(Link, "login receive error");
}
// Check if we are being asked to identify ourselves
//
if (LIHdr.rrCode == kYR_xauth)
{if (!XrdCmsSecurity::Identify(Link, LIHdr, WorkBuff, sizeof(WorkBuff)))
return kYR_EINVAL;
dataLen = static_cast<int>(ntohs(LIHdr.datalen));
if (dataLen > (int)sizeof(WorkBuff))
return Emsg(Link, "login reply too long");
}
// The response can also be a login redirect (i.e., a try request).
//
if (!(Data.Mode & CmsLoginData::kYR_director)
&& LIHdr.rrCode == kYR_try)
{if (!XrdOucPup::Unpack(&wP, wP+dataLen, &hList, n))
return Emsg(Link, "malformed try host data");
Data.Paths = (kXR_char *)strdup(n ? hList : "");
return kYR_redirect;
}
// Process error reply
//
if (LIHdr.rrCode == kYR_error)
return (dataLen < (int)sizeof(kXR_unt32)+8
? Emsg(Link, "invalid error reply")
: Emsg(Link, WorkBuff+sizeof(kXR_unt32)));
// Process normal reply
//
if (LIHdr.rrCode != kYR_login
|| !Parser.Parse(&Data, WorkBuff, WorkBuff+dataLen))
return Emsg(Link, "invalid login response");
return 0;
}
/******************************************************************************/
/* Private: s e n d D a t a */
/******************************************************************************/
int XrdCmsLogin::sendData(XrdLink *Link, CmsLoginData &Data)
{
static const int xNum = 16;
int iovcnt;
char Work[xNum*12];
struct iovec Liov[xNum];
CmsRRHdr Resp={0, kYR_login, 0, 0};
// Pack the response (ignore the auth token for now)
//
if (!(iovcnt=Parser.Pack(kYR_login,&Liov[1],&Liov[xNum],(char *)&Data,Work)))
return Emsg(Link, "too much login reply data");
// Complete I/O vector
//
Resp.datalen = Data.Size;
Liov[0].iov_base = (char *)&Resp;
Liov[0].iov_len = sizeof(Resp);
// Send off the data
//
Link->Send(Liov, iovcnt+1);
// Return success
//
return 0;
}
| bbockelm/xrootd_old_git | src/XrdCms/XrdCmsLogin.cc | C++ | gpl-3.0 | 7,499 |
//
// Author : Toru Shiozaki
// Date : May 2009
//
#define NGRID 12
#define MAXT 64
#define NBOX 32
#define NBOXL 0
#define T_INFTY 11
#include <sstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include "mpreal.h"
#include <map>
#include <cmath>
#include <string>
#include <cassert>
#include <fstream>
#include "gmp_macros.h"
#include <boost/lexical_cast.hpp>
#include "../erirootlist.h"
extern "C" {
void dsyev_(const char*, const char*, const int*, double*, const int*, double*, double*, const int*, int*);
}
using namespace boost;
using namespace std;
using namespace mpfr;
using namespace bagel;
void rysroot_gmp(const vector<mpfr::mpreal>& ta, vector<mpfr::mpreal>& dx, vector<mpfr::mpreal>& dw, const int nrank, const int nbatch) ;
vector<mpreal> chebft(int n) {
mpfr::mpreal::set_default_prec(GMPPREC);
vector<mpreal> out(n);
const mpreal half = "0.5";
for (int k = 0; k != n; ++k) {
const mpreal y = mpfr::cos(GMPPI * (k + half) / n);
out[k] = y;
}
return out;
}
vector<vector<double>> get_C(const mpreal tbase, const mpreal stride, int rank, const bool asymp) {
mpfr::mpreal::set_default_prec(GMPPREC);
const int n = NGRID;
const mpreal zero = "0.0";
const mpreal half = "0.5";
const mpreal one = "1.0";
vector<mpreal> cheb = chebft(n);
const mpreal Tmin = tbase;
const mpreal Tmax = Tmin + stride;
const mpreal Tp = half * (Tmin + Tmax);
vector<mpreal> Tpoints(n);
for (int i = 0; i != n; ++i) {
Tpoints[i] = stride*half*cheb[i] + Tp;
}
#ifdef DAWSON
vector<mpreal> tt_infty(1); tt_infty[0] = Tmax;
vector<mpreal> dx_infty(rank);
vector<mpreal> dw_infty(rank);
if (asymp) rysroot_gmp(tt_infty, dx_infty, dw_infty, rank, 1);
#endif
vector<map<mpreal, mpreal>> table_reserve(n);
#pragma omp parallel for
for (int i = 0; i < n; ++i) {
vector<mpreal> ttt(1); ttt[0] = Tpoints[i];
vector<mpreal> dx(rank);
vector<mpreal> dw(rank);
rysroot_gmp(ttt, dx, dw, rank, 1);
// sort dx and dw using dx
#ifdef DAWSON
if (asymp) {
for (int j = 0; j != rank; ++j) {
table_reserve[i].insert(make_pair(-(1.0 - dx[j])*ttt[0]/((1.0 - dx_infty[j])*tt_infty[0]), dw[j]*ttt[0]/(dw_infty[j]*tt_infty[0])));
}
} else {
for (int j = 0; j != rank; ++j)
table_reserve[i].insert(make_pair(dx[j], dw[j]));
}
#else
for (int j = 0; j != rank; ++j)
table_reserve[i].insert(make_pair(dx[j], dw[j]));
#endif
}
vector<vector<double>> c;
for (int ii = 0; ii != rank; ++ii) {
vector<double> tc(n);
vector<double> tc2(n);
vector<mpreal> cdx, cdw;
for (int j = 0; j != n; ++j) {
auto iter = table_reserve[j].begin();
for (int i = 0; i != ii; ++i) ++iter;
cdx.push_back(iter->first);
cdw.push_back(iter->second);
}
const mpreal two = "2.0";
const mpreal half = "0.5";
const mpreal fac = two / n;
const mpreal pi = GMPPI;
for (int j = 0; j != n; ++j) {
mpreal sum = "0.0";
mpreal sum2 = "0.0";
for (int k = 0; k != n; ++k) {
sum += cdx[k] * mpfr::cos(pi * j * (k + half) / n);
sum2 += cdw[k] * mpfr::cos(pi * j * (k + half) / n);
}
tc[j] = (sum * fac).toDouble();
tc2[j] = (sum2 * fac).toDouble();
}
if (tc[n-1] > 1.0e-10 || tc2[n-1] > 1.0e-10) {
cout << " caution: cheb not converged " << ii << " " << setprecision(10) << fixed << Tmin.toDouble() << " " << Tmax.toDouble() << endl;
for (int i = 0; i != n; ++i) {
cout << setw(20) << Tpoints[i].toDouble() << setw(20) << tc[i] << setw(20) << tc2[i] << endl;
}
}
c.push_back(tc);
c.push_back(tc2);
}
return c;
}
bool test(const int nrank, const double tin) {
mpfr::mpreal::set_default_prec(GMPPREC);
const static int nsize = 1;
vector<mpreal> tt(nsize, tin);
vector<mpreal> rr(nsize*nrank);
vector<mpreal> ww(nsize*nrank);
rysroot_gmp(tt, rr, ww, nrank, nsize);
map<mpreal,mpreal> gmp;
for (int i = 0; i != nsize*nrank; ++i)
gmp.insert(make_pair(rr[i], ww[i]));
double dt[nsize] = {tt[0].toDouble()};
double dr[nsize*nrank];
double dw[nsize*nrank];
eriroot__.root(nrank, dt, dr, dw, nsize);
cout << setprecision(10) << scientific << endl;
auto iter = gmp.begin();
for (int i = 0; i != nrank*nsize; ++i, ++iter) {
cout << setw(20) << dr[i] << setw(20) << iter->first << setw(20) << fabs(dr[i] - (iter->first).toDouble()) << endl;
cout << setw(20) << dw[i] << setw(20) << iter->second << setw(20) << fabs(dw[i] - (iter->second).toDouble()) << endl;
}
iter = gmp.begin();
for (int i = 0; i != nrank; ++i, ++iter) {
if (!(fabs(dr[i] - (iter->first).toDouble()))) cout << dt[0] << endl;
//assert(fabs(dr[i] - (iter->first).toDouble()) < 1.0e-13);
//assert(fabs(dw[i] - (iter->second).toDouble()) < 1.0e-13);
}
cout << "test passed: rank" << setw(3) << nrank << endl;
cout << "----------" << endl;
}
#include <boost/lexical_cast.hpp>
int main(int argc, char** argv) {
const mpreal T_ASYM = static_cast<mpreal>(MAXT + (NBOXL)*(NBOXL + 1.0)*(2.0*NBOXL + 1.0)/6.0);
mpfr::mpreal::set_default_prec(GMPPREC);
mpfr::mpreal pi = GMPPI;
if (argc > 1) {
cout << "--- TEST---" << endl;
const string toggle = argv[1];
if (toggle == "t") {
#if 0
if (argc <= 3) assert(false);
const string low = argv[2];
const string high = argv[3];
for (int i = 0; i < 700; ++i) {
for (int n = lexical_cast<int>(low); n <= lexical_cast<int>(high); ++n) test(n, i*0.1+1.0e-10);
}
#else
test(6,1.10033333333333);
test(6,1.11133333333333);
test(6,1.12233333333333);
test(6,1.13233333333333);
test(6,1.14333333333333);
test(6,1.14333333333333e1);
test(6,0.645e2);
test(6,0.675e2);
test(6,0.805e2);
test(6,0.912e2);
test(6,1.14333333333333e2);
test(6,1.285e2);
test(6,128.000000000000);
test(6,1.31e2);
test(6,1.38e2);
test(6,2.43e2);
test(6,256.000000000000);
test(6,1.14333333333333e3);
test(6,8e3);
test(6,8192.000000000000);
test(6,1.14333333333333e4);
test(6,1.14333333333333e5);
test(6,1.14333333333333e6);
#endif
return 0;
}
}
vector<double> nbox_(52);
for (int nroot=1; nroot!=52; ++nroot) {
nbox_[nroot] = NBOX;
}
for (int nroot=1; nroot!=52; ++nroot) { // this is the outer most loop.
if (argc > 2) {
const string toggle = argv[1];
if (toggle == "-r") {
const string target = argv[2];
if (nroot != lexical_cast<int>(target)) continue;
}
}
vector<double> aroot;
vector<double> aweight;
#ifndef DAWSON
#ifndef SPIN2
#ifndef BREIT
// first obtain asymptotics
const int n=nroot*2;
double a[10000] = {0.0};
double b[100];
double c[500];
for (int i=0; i!= n; ++i) {
a[i+i*n] = 0.0;
if (i > 0) {
const double ia = static_cast<double>(i);
a[(i-1)+i*n] = std::sqrt(ia*0.5);
a[i+(i-1)*n] = std::sqrt(ia*0.5);
}
}
int nn = n*5;
int info = 0;
dsyev_("v", "U", &n, a, &n, b, c, &nn, &info);
for (int j = 0; j != nroot; ++j) {
aroot.push_back(b[nroot+j]*b[nroot+j]);
aweight.push_back(a[(nroot+j)*(nroot*2)]*a[(nroot+j)*(nroot*2)]*(sqrt(pi)).toDouble());
}
#else
const mpreal t = 1000;
const mpreal s = 2000;
vector<mpreal> dx(nroot*2);
vector<mpreal> dw(nroot*2);
vector<mpreal> tt(1, t); tt.push_back(s);
rysroot_gmp(tt, dx, dw, nroot, 2);
for (int j = 0; j != nroot; ++j) {
assert(fabs(dx[j]*t - dx[j+nroot]*s) < 1.0e-16);
assert(fabs(dw[j]*t*sqrt(t) - dw[j+nroot]*s*sqrt(s)) < 1.0e-16);
aroot.push_back((dx[j]*t).toDouble());
aweight.push_back((dw[j]*t*sqrt(t)).toDouble());
}
#endif
#else
const mpreal t = 1000;
const mpreal s = 2000;
vector<mpreal> dx(nroot*2);
vector<mpreal> dw(nroot*2);
vector<mpreal> tt(1, t); tt.push_back(s);
rysroot_gmp(tt, dx, dw, nroot, 2);
for (int j = 0; j != nroot; ++j) {
assert(fabs(dx[j]*t - dx[j+nroot]*s) < 1.0e-16);
assert(fabs(dw[j]*t*t*sqrt(t) - dw[j+nroot]*s*s*sqrt(s)) < 1.0e-16);
aroot.push_back((dx[j]*t).toDouble());
aweight.push_back((dw[j]*t*t*sqrt(t)).toDouble());
}
#endif
#else
mpreal infty;
if (T_INFTY < MAXT) {
assert (NBOXL == 0);
const int nbox0 = static_cast<int>(log(MAXT)/log(2.0));
infty = pow(2, nbox0 + T_INFTY);
} else {
infty = static_cast<mpreal>(T_INFTY);
}
vector<mpreal> tt_infty(1); tt_infty[0] = infty;
vector<mpreal> dx_infty(nroot);
vector<mpreal> dw_infty(nroot);
rysroot_gmp(tt_infty, dx_infty, dw_infty, nroot, 1);
for (int j = 0; j != nroot; ++j) {
aroot.push_back(((1.0 - dx_infty[j])*tt_infty[0]).toDouble());
aweight.push_back((dw_infty[j]*tt_infty[0]).toDouble());
}
#endif
const int ndeg = NGRID;
const int nbox = nbox_[nroot];
#ifndef DAWSON
const int jend = nbox;
#else
int jend;
if (MAXT < T_INFTY) {
jend = NBOX + NBOXL + 1;
} else {
jend = NBOX + T_INFTY;
}
#endif
const double stride = static_cast<double>(MAXT)/nbox;
const mpreal mstride = static_cast<mpreal>(MAXT)/nbox;
ofstream ofs;
#ifndef SPIN2
#ifndef BREIT
#ifndef DAWSON
const string func = "eriroot";
#else
const string func = "r2root";
#endif
#else
const string func = "breitroot";
#endif
#else
const string func = "spin2root";
#endif
string filename = "_" + func + "_" + lexical_cast<string>(nroot) + ".cc";
ofs.open(filename.c_str());
ofs << "\
//\n\
// BAGEL - Brilliantly Advanced General Electronic Structure Library\n\
// Filename: " + filename + "\n\
// Copyright (C) 2013 Toru Shiozaki\n\
//\n\
// Author: Toru Shiozaki <shiozaki@northwestern.edu>\n\
// Maintainer: Shiozaki group\n\
//\n\
// This file is part of the BAGEL package.\n\
//\n\
// This program is free software: you can redistribute it and/or modify\n\
// it under the terms of the GNU General Public License as published by\n\
// the Free Software Foundation, either version 3 of the License, or\n\
// (at your option) any later version.\n\
//\n\
// This program is distributed in the hope that it will be useful,\n\
// but WITHOUT ANY WARRANTY; without even the implied warranty of\n\
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\
// GNU General Public License for more details.\n\
//\n\
// You should have received a copy of the GNU General Public License\n\
// along with this program. If not, see <http://www.gnu.org/licenses/>.\n\
//\n\
\n\
#include <algorithm> \n\
#include <cassert>" << endl;
#ifdef BREIT
ofs << "#include <src/integral/rys/breitrootlist.h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
\n\
void BreitRootList::" << func << nroot << "(const double* ta, double* rr, double* ww, const int n) {\n" << endl;
#else
#ifdef DAWSON
ofs << "#include <src/integral/rys/r2rootlist.h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
\n\
void R2RootList::" << func << nroot << "(const double* ta, double* rr, double* ww, const int n) {\n" << endl;
#else
#ifdef SPIN2
ofs << "#include <src/integral/rys/spin2rootlist.h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
\n\
void Spin2RootList::" << func << nroot << "(const double* ta, double* rr, double* ww, const int n) {\n" << endl;
#else
ofs << "#include <src/integral/rys/erirootlist.h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
\n\
void ERIRootList::" << func << nroot << "(const double* ta, double* rr, double* ww, const int n) {\n" << endl;
#endif
#endif
#endif
ofs << "\
constexpr double ax["<<nroot<<"] = {";
for (int j=0; j!= nroot; ++j) {
ofs << scientific << setprecision(15) << setw(20) << aroot[j];
if (j != nroot-1) ofs << ",";
if (j%7 == 4) ofs << endl << " ";
}
ofs << "};" << endl;
ofs << "\
constexpr double aw["<<nroot<<"] = {";
for (int j=0; j!= nroot; ++j) {
ofs << scientific << setprecision(15) << setw(20) << aweight[j];
if (j != nroot-1) ofs << ",";
if (j%7 == 4) ofs << endl << " ";
}
ofs << "};" << endl;
////////////////////////////////////////
// now creates data
////////////////////////////////////////
stringstream listx, listw;
string indent(" ");
int nblock = 0;
int index = 0;
double tiny = 1.0e-100;
int xcnt = 0;
int wcnt = 0;
#ifdef DAWSON
const int ibox0 = static_cast<int>(log(MAXT)/log(2.0));
#endif
for (int j=0; j != jend; ++j) {
#ifndef DAWSON
vector<vector<double>> c_all = get_C(j*mstride, mstride, nroot, false);
#else
vector<vector<double>> c_all;
if (j < NBOX) {
c_all = get_C(j*mstride, mstride, nroot, false);
} else {
if (MAXT < T_INFTY) {
if (j >= NBOX && j < jend-1) { // NBOXL between MAXT and T_ASYM
const int ibox = j - NBOX;
const mpreal mstart = static_cast<mpreal> (MAXT + ibox*(ibox + 1.0)*(2.0*ibox + 1.0)/6.0);
const mpreal mstrideL = static_cast<mpreal> (ibox + 1.0)*(ibox + 1.0);
c_all = get_C(mstart, mstrideL, nroot, false);
} else {
const mpreal mstart = static_cast<mpreal> (T_ASYM);
const mpreal mstrideL = static_cast<mpreal> (infty - T_ASYM);
c_all = get_C(mstart, mstrideL, nroot, true);
}
} else {
assert(NBOXL == 0);
const int ibox = j - NBOX;
const mpreal mstart = static_cast<mpreal>(pow(2.0, ibox0 + ibox));
const mpreal mstrideL = static_cast<mpreal>(pow(2.0, ibox0 + ibox));
c_all = get_C(mstart, mstrideL, nroot, true);
}
}
#endif
for (int i = 0; i != nroot; ++i, ++index) {
const int ii = 2 * i;
const vector<double> x = c_all[ii];
const vector<double> w = c_all[ii + 1];
for (auto iter = x.begin(); iter != x.end(); ++iter) {
listx << indent << scientific << setprecision(15) << ((*iter > 0.0 || fabs(*iter) < tiny) ? " " : "") << setw(20) <<
(fabs(*iter) < tiny ? 0.0 : *iter);
if (iter + 1 != x.end() || j+1 != jend || i+1 != nroot || MAXT >= T_INFTY) listx << ",";
if (xcnt++ % 7 == 4) listx << "\n";
}
for (auto iter = w.begin(); iter != w.end(); ++iter) {
listw << indent << scientific << setprecision(15) << ((*iter > 0.0 || fabs(*iter) < tiny) ? " " : "") << setw(20) <<
(fabs(*iter) < tiny ? 0.0 : *iter);
if (iter + 1 != w.end() || j+1 != jend || i+1 != nroot || MAXT >= T_INFTY) listw << ",";
if (wcnt++ % 7 == 4) listw << "\n";
}
}
}
#ifdef DAWSON
if (MAXT >= T_INFTY) {
for (int ibox = 0; ibox != T_INFTY; ++ibox) {
vector<mpreal> tt_infty(1); tt_infty[0] = static_cast<mpreal>(pow(2.0, ibox + ibox0 + 1));
vector<mpreal> dx_infty(nroot);
vector<mpreal> dw_infty(nroot);
rysroot_gmp(tt_infty, dx_infty, dw_infty, nroot, 1);
for (auto iter = dx_infty.begin(); iter != dx_infty.end(); ++iter) {
listx << indent << scientific << setprecision(15) << ((*iter > 0.0 || fabs(*iter) < tiny) ? " " : "") << setw(20) <<
(fabs(*iter) < tiny ? 0.0 : *iter);
if (iter + 1 != dx_infty.end() || ibox + 1 != T_INFTY) listx << ",";
if (xcnt++ % 7 == 4) listx << "\n";
}
for (auto iter = dw_infty.begin(); iter != dw_infty.end(); ++iter) {
listw << indent << scientific << setprecision(15) << ((*iter > 0.0 || fabs(*iter) < tiny) ? " " : "") << setw(20) <<
(fabs(*iter) < tiny ? 0.0 : *iter);
if (iter + 1 != dw_infty.end() || ibox + 1 != T_INFTY) listw << ",";
if (wcnt++ % 7 == 4) listw << "\n";
}
}
}
#endif
#ifndef SPIN2
#ifndef BREIT
string tafactor = "t";
#else
string tafactor = "t*t*t";
#endif
#else
string tafactor = "t*t*t*t*t";
#endif
int nbox2 = 0;
#ifndef DAWSON
const int nbox1 = nbox;
#else
int nbox1;
if (MAXT < T_INFTY) {
nbox1 = nbox + NBOXL + 1;
} else {
nbox1 = nbox + T_INFTY;
nbox2 = T_INFTY;
}
#endif
ofs << "\
constexpr double x[" << nroot*nbox1*ndeg + nroot*nbox2 <<"] = {";
ofs << listx.str() << "\
};" << endl;
ofs << "\
constexpr double w[" << nroot*nbox1*ndeg + nroot*nbox2 <<"] = {";
ofs << listw.str() << "\
};" << endl;
ofs << "\
int offset = -" << nroot << ";\n";
#ifdef DAWSON
ofs << "\
const int ibox0 = static_cast<int>(log(" << MAXT << ".0) / log(2.0)); \n";
#endif
ofs << "\
for (int i = 1; i <= n; ++i) {\n\
double t = ta[i-1];\n\
offset += " << nroot << ";\n\
if (std::isnan(t)) {\n\
fill_n(rr+offset, " << nroot << ", 0.5);\n\
fill_n(ww+offset, " << nroot << ", 0.0);\n";
#ifndef DAWSON
ofs << "\
} else if (t >= " << MAXT << ".0) {\n\
t = 1.0/sqrt(t);\n\
for (int r = 0; r != " << nroot << "; ++r) {\n\
rr[offset+r] = ax[r]*t*t;\n\
ww[offset+r] = aw[r]*" + tafactor + ";\n\
}\n\
} else {\n\
assert(t >= 0);\n\
int it = static_cast<int>(t*" << setw(20) << setprecision(15) << fixed << 1.0/stride<< ");\n\
t = (t-it*" << stride << "-" << setw(20) << setprecision(15) << fixed << stride/2.0 << ") *" << setw(20) << setprecision(15) << fixed << 2.0/stride << ";\n\
\n";
#else
ofs << "\
} else if (t >= " << infty << ".0) {\n\
for (int r = 0; r != " << nroot << "; ++r) {\n\
ww[offset+r] = aw[" << nroot << "-r-1] / t;\n\
rr[offset+r] = 1.0 - ax[" << nroot << "-r-1] / t;\n\
}\n\
} else {\n\
assert(t >= 0);\n";
if (MAXT < T_INFTY) {
ofs << "\
vector<double> rr_infty(" << nroot << "); \n\
vector<double> ww_infty(" << nroot << "); \n";
for (int j = 0; j != nroot; ++j) {
ofs << "\
ww_infty[" << j << "] = " << setw(20) << setprecision(15) << fixed << dw_infty[j] << "; \n\
rr_infty[" << j << "] = " << setw(20) << setprecision(15) << fixed << dx_infty[j] << "; \n";
}
}
ofs << "\
int it; \n\
double bigT = 0.0; \n";
if (NBOXL != 0) {
ofs << "\
if (" << MAXT << ".0 <= t && t < " << T_ASYM << ".0) { \n\
int ka = static_cast<int>((pow((t - " << MAXT << ".0)*6.0, 1.0/3.0) - pow(0.25, 1.0/3.0))/pow(2.0, 1.0/3.0)); \n\
int kb = static_cast<int>((pow((t - " << MAXT << ".0)*6.0, 1.0/3.0) - pow(6.0, 1.0/3.0))/pow(2.0, 1.0/3.0)); \n\
assert(kb + 1 == ka || kb == ka); \n\
it = " << NBOX << " + ka; \n\
double a = " << MAXT << ".0 + ka * (ka + 1) * (2*ka + 1)/6.0; \n\
double b = " << MAXT << ".0 + (ka + 1) * (ka + 2) * (2*ka + 3)/6.0; \n\
t = (t - (a+b)/2) * 2/(a-b);\n\
} else if (t >= " << T_ASYM << ".0 && t < " << infty << ".0) { \n";
} else {
ofs << "\
if (t >= " << T_ASYM << ".0 && t < " << infty << ".0) { \n";
}
ofs << "\
bigT = t; \n";
if (MAXT < T_INFTY) {
ofs << "\
it = static_cast<int>(" << NBOX + NBOXL << ");\n\
t = (t - (" << T_ASYM << ".0 + " << infty << ".0)/2) * 2/(" << infty << ".0 - " << T_ASYM << ".0);\n";
} else {
ofs << "\
it = static_cast<int>(log(bigT) / log(2.0) + " << NBOX << " - ibox0);\n\
t = (t - 1.5 * pow(2.0, it + ibox0 - " << NBOX << "))* 2/pow(2.0, it + ibox0 - " << NBOX << ");\n\
cout << \" new t = \" << t << endl; \n";
}
ofs << "\
} else { \n\
it = static_cast<int>(t*" << setw(20) << setprecision(15) << fixed << 1.0/stride<< ");\n\
t = (t - it *" << stride << "-" << setw(20) << setprecision(15) << fixed << stride/2.0 << ") *" << setw(20) << setprecision(15) << fixed << 2.0/stride << ";\n\
} \n";
#endif
ofs << "\
const double t2 = t * 2.0;\n\
for (int j=1; j <=" << nroot << "; ++j) {\n\
const int boxof = it*" << ndeg*nroot << "+" << ndeg << "*(j-1);\n";
assert((ndeg/2)*2 == ndeg);
for (int i=ndeg; i!=0; --i) {
if (i==ndeg) {
ofs << "\
double d = x[boxof+" << i-1 << "];\n\
double e = w[boxof+" << i-1 << "];\n";
} else if (i==ndeg-1) {
ofs << "\
double f = t2*d + x[boxof+" << i-1 << "];\n\
double g = t2*e + w[boxof+" << i-1 << "];\n";
} else if (i != 1 && ((i/2)*2 == i)) { // odd
ofs << "\
d = t2*f - d + x[boxof+" << i-1 << "];\n\
e = t2*g - e + w[boxof+" << i-1 << "];\n";
} else if (i != 1) { // even
ofs << "\
f = t2*d - f + x[boxof+" << i-1 << "];\n\
g = t2*e - g + w[boxof+" << i-1 << "];\n";
} else {
ofs << "\
rr[offset+j-1] = t*d - f + x[boxof+" << i-1 << "]*0.5;\n\
ww[offset+j-1] = t*e - g + w[boxof+" << i-1 << "]*0.5;\n";
#ifdef DAWSON
if (MAXT < T_INFTY) {
ofs << "\
if (" << T_ASYM << ".0 <= bigT && bigT < " << infty << ".0) { \n\
ww[offset+j-1] = ww[offset+j-1] * ww_infty[" << nroot << "-j] * " << infty << ".0 / bigT;\n\
rr[offset+j-1] = 1.0 + rr[offset+j-1] * (1.0 - rr_infty[" << nroot << "-j]) * " << infty << ".0 /bigT; \n\
}\n";
} else {
ofs << "\
if (" << MAXT << ".0 <= bigT && bigT < " << infty << ".0) {\n\
const int iref = " << (NBOX + T_INFTY) * nroot * NGRID << " + (it - " << NBOX << ") * " << nroot << " + " << nroot << " - j;\n\
double rr_infty = x[iref];\n\
double ww_infty = w[iref];\n\
double Tref = pow(2.0, it + ibox0 + 1 - " << NBOX << ");\n\
ww[offset+j-1] = ww[offset+j-1] * ww_infty * Tref / bigT;\n\
rr[offset+j-1] = 1.0 + rr[offset+j-1] * (1.0 - rr_infty) * Tref /bigT;\n\
}\n";
}
#endif
}
}
ofs << "\
}\n\
}\n\
}\n\
}";
ofs.close();
}
return 0;
}
| nubakery/bagel | src/integral/rys/interpolate/main.cc | C++ | gpl-3.0 | 22,012 |
<?php
/**
* LICENSE: The MIT License (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* https://github.com/azure/azure-storage-php/LICENSE
*
* 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.
*
* PHP version 5
*
* @category Microsoft
* @package MicrosoftAzure\Storage\Table\Models
* @author Azure Storage PHP SDK <dmsh@microsoft.com>
* @copyright 2016 Microsoft Corporation
* @license https://github.com/azure/azure-storage-php/LICENSE
* @link https://github.com/azure/azure-storage-php
*/
namespace MicrosoftAzure\Storage\Table\Models;
use MicrosoftAzure\Storage\Common\Internal\Validate;
use MicrosoftAzure\Storage\Common\Internal\Resources;
use MicrosoftAzure\Storage\Common\Internal\Utilities;
/**
* Represents one batch operation
*
* @category Microsoft
* @package MicrosoftAzure\Storage\Table\Models
* @author Azure Storage PHP SDK <dmsh@microsoft.com>
* @copyright 2016 Microsoft Corporation
* @license https://github.com/azure/azure-storage-php/LICENSE
* @version Release: 0.10.1
* @link https://github.com/azure/azure-storage-php
*/
class BatchOperation
{
/**
* @var string
*/
private $_type;
/**
* @var array
*/
private $_params;
/**
* Sets operation type.
*
* @param string $type The operation type. Must be valid type.
*
* @return none
*/
public function setType($type)
{
Validate::isTrue(
BatchOperationType::isValid($type),
Resources::INVALID_BO_TYPE_MSG
);
$this->_type = $type;
}
/**
* Gets operation type.
*
* @return string
*/
public function getType()
{
return $this->_type;
}
/**
* Adds or sets parameter for the operation.
*
* @param string $name The param name. Must be valid name.
* @param mix $value The param value.
*
* @return none
*/
public function addParameter($name, $value)
{
Validate::isTrue(
BatchOperationParameterName::isValid($name),
Resources::INVALID_BO_PN_MSG
);
$this->_params[$name] = $value;
}
/**
* Gets parameter value and if the name doesn't exist, return null.
*
* @param string $name The parameter name.
*
* @return mix
*/
public function getParameter($name)
{
return Utilities::tryGetValue($this->_params, $name);
}
}
| segej87/ecomapper | DataEntry/server_side/ecomapper-backend/vendor/microsoft/azure-storage/src/Table/Models/BatchOperation.php | PHP | gpl-3.0 | 2,844 |
/*
*\class PASER_Neighbor_Table
*@brief Class represents an entry in the neighbor table
*
*\authors Eugen.Paul | Mohamad.Sbeiti \@paser.info
*
*\copyright (C) 2012 Communication Networks Institute (CNI - Prof. Dr.-Ing. Christian Wietfeld)
* at Technische Universitaet Dortmund, Germany
* http://www.kn.e-technik.tu-dortmund.de/
*
*
* 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.
* For further information see file COPYING
* in the top level directory
********************************************************************************
* This work is part of the secure wireless mesh networks framework, which is currently under development by CNI
********************************************************************************/
#include "Configuration.h"
#ifdef OPENSSL_IS_LINKED
#include <openssl/x509.h>
#include "PASER_Neighbor_Entry.h"
PASER_Neighbor_Entry::~PASER_Neighbor_Entry() {
if (root) {
free(root);
}
root = NULL;
if (Cert) {
X509_free((X509*) Cert);
}
Cert = NULL;
}
void PASER_Neighbor_Entry::setValidTimer(PASER_Timer_Message *_validTimer) {
validTimer = _validTimer;
}
#endif
| ngocthienle/SG_OMNeTpp | inetmanet-2.0/src/networklayer/manetrouting/PASER/paser_tables/PASER_Neighbor_Entry.cc | C++ | gpl-3.0 | 1,505 |
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\PageCache\Test\Unit\Model;
use Magento\PageCache\Model\Config;
class ConfigTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Magento\PageCache\Model\Config
*/
protected $_model;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $_coreConfigMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Cache\StateInterface
*/
protected $_cacheState;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Module\Dir\Reader
*/
protected $moduleReader;
/**
* setUp all mocks and data function
*/
protected function setUp()
{
$readFactoryMock = $this->getMock('Magento\Framework\Filesystem\Directory\ReadFactory', [], [], '', false);
$this->_coreConfigMock = $this->getMock('Magento\Framework\App\Config\ScopeConfigInterface');
$this->_cacheState = $this->getMockForAbstractClass('Magento\Framework\App\Cache\StateInterface');
$modulesDirectoryMock = $this->getMock(
'Magento\Framework\Filesystem\Directory\Write',
[],
[],
'',
false
);
$readFactoryMock->expects(
$this->any()
)->method(
'create'
)->will(
$this->returnValue($modulesDirectoryMock)
);
$modulesDirectoryMock->expects(
$this->any()
)->method(
'readFile'
)->will(
$this->returnValue(file_get_contents(__DIR__ . '/_files/test.vcl'))
);
$this->_coreConfigMock->expects(
$this->any()
)->method(
'getValue'
)->will(
$this->returnValueMap(
[
[
\Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_BACKEND_HOST,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
null,
'example.com',
],
[
\Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_BACKEND_PORT,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
null,
'8080'
],
[
\Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_ACCESS_LIST,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
null,
'127.0.0.1, 192.168.0.1,127.0.0.2'
],
[
\Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_DESIGN_THEME_REGEX,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
null,
serialize([['regexp' => '(?i)pattern', 'value' => 'value_for_pattern']])
],
]
)
);
$this->moduleReader = $this->getMock('Magento\Framework\Module\Dir\Reader', [], [], '', false);
$this->_model = new \Magento\PageCache\Model\Config(
$readFactoryMock,
$this->_coreConfigMock,
$this->_cacheState,
$this->moduleReader
);
}
/**
* test for getVcl method
*/
public function testGetVcl()
{
$this->moduleReader->expects($this->once())
->method('getModuleDir')
->willReturn('/magento/app/code/Magento/PageCache');
$test = $this->_model->getVclFile(Config::VARNISH_3_CONFIGURATION_PATH);
$this->assertEquals(file_get_contents(__DIR__ . '/_files/result.vcl'), $test);
}
public function testGetTll()
{
$this->_coreConfigMock->expects($this->once())->method('getValue')->with(Config::XML_PAGECACHE_TTL);
$this->_model->getTtl();
}
/**
* Whether a cache type is enabled
*/
public function testIsEnabled()
{
$this->_cacheState->expects($this->at(0))
->method('isEnabled')
->with(\Magento\PageCache\Model\Cache\Type::TYPE_IDENTIFIER)
->will($this->returnValue(true));
$this->_cacheState->expects($this->at(1))
->method('isEnabled')
->with(\Magento\PageCache\Model\Cache\Type::TYPE_IDENTIFIER)
->will($this->returnValue(false));
$this->assertTrue($this->_model->isEnabled());
$this->assertFalse($this->_model->isEnabled());
}
}
| rajmahesh/magento2-master | vendor/magento/module-page-cache/Test/Unit/Model/ConfigTest.php | PHP | gpl-3.0 | 4,719 |
<?php
/**
* Nooku Platform - http://www.nooku.org/platform
*
* @copyright Copyright (C) 2007 - 2014 Johan Janssens and Timble CVBA. (http://www.timble.net)
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link https://github.com/nooku/nooku-platform for the canonical source repository
*/
namespace Nooku\Library;
/**
* Event Mixin
*
* Class can be used as a mixin in classes that want to implement a an event publisher and allow adding and removing
* event listeners and subscribers.
*
* @author Johan Janssens <http://github.com/johanjanssens>
* @package Nooku\Library\Event
*/
class EventMixin extends ObjectMixinAbstract implements EventMixinInterface
{
/**
* Event publisher object
*
* @var EventPublisherInterface
*/
private $__event_publisher;
/**
* List of event subscribers
*
* Associative array of event subscribers, where key holds the subscriber identifier string
* and the value is an identifier object.
*
* @var array
*/
private $__event_subscribers = array();
/**
* Object constructor
*
* @param ObjectConfig $config An optional ObjectConfig object with configuration options
* @throws \InvalidArgumentException
*/
public function __construct(ObjectConfig $config)
{
parent::__construct($config);
if (is_null($config->event_publisher)) {
throw new \InvalidArgumentException('event_publisher [EventPublisherInterface] config option is required');
}
//Set the event dispatcher
$this->__event_publisher = $config->event_publisher;
//Add the event listeners
foreach ($config->event_listeners as $event => $listener) {
$this->addEventListener($event, $listener);
}
//Add the event subscribers
$subscribers = (array) ObjectConfig::unbox($config->event_subscribers);
foreach ($subscribers as $key => $value)
{
if (is_numeric($key)) {
$this->addEventSubscriber($value);
} else {
$this->addEventSubscriber($key, $value);
}
}
}
/**
* Initializes the options for the object
*
* Called from {@link __construct()} as a first step of object instantiation.
*
* @param ObjectConfig $config An optional ObjectConfig object with configuration options
* @return void
*/
protected function _initialize(ObjectConfig $config)
{
$config->append(array(
'event_publisher' => 'event.publisher',
'event_subscribers' => array(),
'event_listeners' => array(),
));
parent::_initialize($config);
}
/**
* Publish an event by calling all listeners that have registered to receive it.
*
* @param string|EventInterface $event The event name or a KEventInterface object
* @param array|\Traversable|EventInterface $attributes An associative array, an object implementing the
* EventInterface or a Traversable object
* @param mixed $target The event target
* @throws \InvalidArgumentException If the event is not a string or does not implement the KEventInterface
* @return null|EventInterface Returns the event object. If the chain is not enabled will return NULL.
*/
public function publishEvent($event, $attributes = array(), $target = null)
{
return $this->getEventPublisher()->publishEvent($event, $attributes, $target);
}
/**
* Get the event publisher
*
* @throws \UnexpectedValueException
* @return EventPublisherInterface
*/
public function getEventPublisher()
{
if(!$this->__event_publisher instanceof EventPublisherInterface)
{
$this->__event_publisher = $this->getObject($this->__event_publisher);
if(!$this->__event_publisher instanceof EventPublisherInterface)
{
throw new \UnexpectedValueException(
'EventPublisher: '.get_class($this->__event_publisher).' does not implement KEventPublisherInterface'
);
}
}
return $this->__event_publisher;
}
/**
* Set the event publisher
*
* @param EventPublisherInterface $publisher An event publisher object
* @return ObjectInterface The mixer
*/
public function setEventPublisher(EventPublisherInterface $publisher)
{
$this->__event_publisher = $publisher;
return $this->getMixer();
}
/**
* Add an event listener
*
* @param string|EventInterface $event The event name or a KEventInterface object
* @param callable $listener The listener
* @param integer $priority The event priority, usually between 1 (high priority) and 5 (lowest),
* default is 3 (normal)
* @throws \InvalidArgumentException If the listener is not a callable
* @throws \InvalidArgumentException If the event is not a string or does not implement the KEventInterface
* @return ObjectInterface The mixer
*/
public function addEventListener($event, $listener, $priority = EventInterface::PRIORITY_NORMAL)
{
$this->getEventPublisher()->addListener($event, $listener, $priority);
return $this->getMixer();
}
/**
* Remove an event listener
*
* @param string|EventInterface $event The event name or a KEventInterface object
* @param callable $listener The listener
* @throws \InvalidArgumentException If the listener is not a callable
* @throws \InvalidArgumentException If the event is not a string or does not implement the KEventInterface
* @return ObjectInterface The mixer
*/
public function removeEventListener($event, $listener)
{
$this->getEventPublisher()->removeListener($event, $listener);
return $this->getMixer();
}
/**
* Add an event subscriber
*
* @param mixed $subscriber An object that implements ObjectInterface, ObjectIdentifier object
* or valid identifier string
* @param array $config An optional associative array of configuration options
* @return ObjectInterface The mixer
*/
public function addEventSubscriber($subscriber, $config = array())
{
if (!($subscriber instanceof EventSubscriberInterface)) {
$subscriber = $this->getEventSubscriber($subscriber, $config);
}
$subscriber->subscribe($this->getEventPublisher());
return $this;
}
/**
* Remove an event subscriber
*
* @param EventSubscriberInterface $subscriber An event subscriber
* @return ObjectInterface The mixer
*/
public function removeEventSubscriber(EventSubscriberInterface $subscriber)
{
$subscriber->unsubscribe($this->getEventPublisher());
return $this->getMixer();
}
/**
* Get a event subscriber by identifier
*
* The subscriber will be created if does not exist yet, otherwise the existing subscriber will be returned.
*
* @param mixed $subscriber An object that implements ObjectInterface, ObjectIdentifier object
* or valid identifier string
* @param array $config An optional associative array of configuration settings
* @throws \UnexpectedValueException If the subscriber is not implementing the EventSubscriberInterface
* @return EventSubscriberInterface
*/
public function getEventSubscriber($subscriber, $config = array())
{
if (!($subscriber instanceof ObjectIdentifier))
{
//Create the complete identifier if a partial identifier was passed
if (is_string($subscriber) && strpos($subscriber, '.') === false)
{
$identifier = $this->getIdentifier()->toArray();
$identifier['path'] = array('event', 'subscriber');
$identifier['name'] = $subscriber;
$identifier = $this->getIdentifier($identifier);
}
else $identifier = $this->getIdentifier($subscriber);
}
else $identifier = $subscriber;
if (!isset($this->__event_subscribers[(string)$identifier]))
{
$subscriber = $this->getObject($identifier, $config);
//Check the event subscriber interface
if (!($subscriber instanceof EventSubscriberInterface))
{
throw new \UnexpectedValueException(
"Event Subscriber $identifier does not implement KEventSubscriberInterface"
);
}
}
else $subscriber = $this->__event_subscribers[(string)$identifier];
return $subscriber;
}
/**
* Gets the event subscribers
*
* @return array An array of event subscribers
*/
public function getEventSubscribers()
{
return array_values($this->__event_subscribers);
}
} | babsgosgens/nooku-ember-example-theme | library/event/mixin.php | PHP | gpl-3.0 | 9,285 |
require 'nokogiri'
require 'digest'
class XMLReader
# uses nokogiri to extract all system information from scenario.xml
# This includes module filters, which are module objects that contain filters for selecting
# from the actual modules that are available
# @return [Array] Array containing Systems objects
def self.parse_doc(file_path, schema, type)
doc = nil
begin
doc = Nokogiri::XML(File.read(file_path))
rescue
Print.err "Failed to read #{type} configuration file (#{file_path})"
exit
end
validate_xml(doc, file_path, schema, type)
# remove xml namespaces for ease of processing
doc.remove_namespaces!
end
def self.validate_xml(doc, file_path, schema, type)
# validate XML against schema
begin
xsd = Nokogiri::XML::Schema(File.open(schema))
xsd.validate(doc).each do |error|
Print.err "Error in scenario configuration file (#{scenario_file}):"
Print.err " #{error.line}: #{error.message}"
exit
end
rescue Exception => e
Print.err "Failed to validate #{type} xml file (#{file_path}): against schema (#{schema})"
Print.err e.message
exit
end
end
def self.read_attributes(node)
attributes = {}
node.xpath('@*').each do |attr|
attributes["#{attr.name}"] = [attr.text] unless attr.text.nil? || attr.text == ''
end
attributes
end
end | cliffe/SecGen | lib/readers/xml_reader.rb | Ruby | gpl-3.0 | 1,407 |
<?php
// Heading
$_['heading_title'] = 'Blog Viewed Report';
// Text
$_['text_success'] = 'Success: You have modified the blog viewed report!';
// Column
$_['column_article_name'] = 'Article Name';
$_['column_author_name'] = 'Author Name';
$_['column_viewed'] = 'Viewed';
$_['column_percent'] = 'Percent';
// Entry
$_['entry_date_start'] = 'Date Start:';
$_['entry_date_end'] = 'Date End:';
?> | dhananjaypingale2112/vc_fitness | upload/aplogin/language/english/simple_blog/report.php | PHP | gpl-3.0 | 415 |
<?php
namespace App\itnovum\openITCOCKPIT\Core\AngularJS;
class PdfAssets {
/**
* @return array
*/
static public function getCssFiles() {
return [
'/node_modules/bootstrap/dist/css/bootstrap.css',
'/smartadmin4/dist/css/vendors.bundle.css',
'/smartadmin4/dist/css/app.bundle.css',
'/node_modules/@fortawesome/fontawesome-free/css/all.css',
'/css/openitcockpit-colors.css',
'/css/openitcockpit-utils.css',
'/css/openitcockpit.css',
'/css/openitcockpit-pdf.css',
];
}
}
| trevrobwhite/openITCOCKPIT | src/itnovum/openITCOCKPIT/Core/AngularJS/PdfAssets.php | PHP | gpl-3.0 | 608 |
using LeagueSharp.Common;
using SharpDX;
using EloBuddy;
using LeagueSharp.Common;
namespace e.Motion_Katarina
{
public class Dagger
{
private static readonly int DELAY = 0;
private static readonly int MAXACTIVETIME = 4000;
private bool Destructable;
private Vector3 Position;
private int Time;
public Dagger(Vector3 position)
{
Time = Utils.TickCount + DELAY;
this.Position = position;
}
//Object Pooling Pseudo-Constructor
public void Recreate(Vector3 position)
{
Destructable = false;
Time = Utils.TickCount + DELAY;
this.Position = position;
}
public Vector3 GetPosition()
{
return Position;
}
public bool IsDead()
{
return Destructable;
}
public void MarkDead()
{
Destructable = true;
}
public bool IsActive()
{
return Utils.TickCount >= Time;
}
public void CheckForUpdate()
{
if(Time + MAXACTIVETIME <= Utils.TickCount)
{
Destructable = true;
return;
}
}
}
}
| saophaisau/port | Core/Champion Ports/Katarina/e.Motion Katarina/Dagger.cs | C# | gpl-3.0 | 1,294 |
package org.obiba.mica.search.aggregations;
import org.obiba.mica.micaConfig.service.helper.AggregationMetaDataProvider;
import org.obiba.mica.micaConfig.service.helper.PopulationIdAggregationMetaDataHelper;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import java.util.Map;
@Component
public class PopulationAggregationMetaDataProvider implements AggregationMetaDataProvider {
private static final String AGGREGATION_NAME = "populationId";
private final PopulationIdAggregationMetaDataHelper helper;
@Inject
public PopulationAggregationMetaDataProvider(PopulationIdAggregationMetaDataHelper helper) {
this.helper = helper;
}
@Override
public MetaData getMetadata(String aggregation, String termKey, String locale) {
Map<String, LocalizedMetaData> dataMap = helper.getPopulations();
return AGGREGATION_NAME.equals(aggregation) && dataMap.containsKey(termKey) ?
MetaData.newBuilder()
.title(dataMap.get(termKey).getTitle().get(locale))
.description(dataMap.get(termKey).getDescription().get(locale))
.className(dataMap.get(termKey).getClassName())
.build() : null;
}
@Override
public boolean containsAggregation(String aggregation) {
return AGGREGATION_NAME.equals(aggregation);
}
@Override
public void refresh() {
}
}
| obiba/mica2 | mica-search/src/main/java/org/obiba/mica/search/aggregations/PopulationAggregationMetaDataProvider.java | Java | gpl-3.0 | 1,342 |
/**
* This file is part of d:swarm graph extension.
*
* d:swarm graph extension 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.
*
* d:swarm graph extension 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 d:swarm graph extension. If not, see <http://www.gnu.org/licenses/>.
*/
package org.dswarm.graph.delta.match.model.util;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import org.dswarm.graph.delta.match.model.CSEntity;
import org.dswarm.graph.delta.match.model.ValueEntity;
/**
* @author tgaengler
*/
public final class CSEntityUtil {
public static Optional<? extends Collection<ValueEntity>> getValueEntities(final Optional<? extends Collection<CSEntity>> csEntities) {
if (!csEntities.isPresent() || csEntities.get().isEmpty()) {
return Optional.empty();
}
final Set<ValueEntity> valueEntities = new HashSet<>();
for (final CSEntity csEntity : csEntities.get()) {
valueEntities.addAll(csEntity.getValueEntities());
}
return Optional.of(valueEntities);
}
}
| zazi/dswarm-graph-neo4j | src/main/java/org/dswarm/graph/delta/match/model/util/CSEntityUtil.java | Java | gpl-3.0 | 1,515 |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.ClearCanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
// This file is auto-generated by the Macro.Model.SqlServer.CodeGenerator project.
namespace Macro.ImageServer.Model.EntityBrokers
{
using Macro.ImageServer.Enterprise;
public interface IServerRuleApplyTimeEnumBroker: IEnumBroker<ServerRuleApplyTimeEnum>
{ }
}
| 151706061/MacroMedicalSystem | ImageServer/Model/EntityBrokers/IServerRuleApplyTimeEnumBroker.gen.cs | C# | gpl-3.0 | 1,219 |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.ClearCanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
namespace Macro.ImageServer.Common.Exceptions
{
/// <summary>
/// Represents an exception thrown when the study state is invalid for the operation.
/// </summary>
public class InvalidStudyStateOperationException : System.Exception
{
public InvalidStudyStateOperationException(string message):base(message)
{
}
}
}
| 151706061/MacroMedicalSystem | ImageServer/Common/Exceptions/InvalidStudyStateOperationException.cs | C# | gpl-3.0 | 1,334 |
function assign(taskID, assignedTo)
{
$('.assign').width(150);
$('.assign').height(40);
$('.assign').load(createLink('user', 'ajaxGetUser', 'taskID=' + taskID + '&assignedTo=' + assignedTo));
}
function setComment()
{
$('#comment').toggle();
}
| isleon/zentao | module/task/js/view.js | JavaScript | gpl-3.0 | 252 |
/* Image.js
*
* copyright (c) 2010-2017, Christian Mayer and the CometVisu contributers.
*
* 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, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
/**
*
*/
qx.Class.define('cv.parser.widgets.Image', {
type: "static",
/*
******************************************************
STATICS
******************************************************
*/
statics: {
/**
* Parses the widgets XML configuration and extracts the given information
* to a simple key/value map.
*
* @param xml {Element} XML-Element
* @param path {String} internal path of the widget
* @param flavour {String} Flavour of the widget
* @param pageType {String} Page type (2d, 3d, ...)
*/
parse: function (xml, path, flavour, pageType) {
var data = cv.parser.WidgetParser.parseElement(this, xml, path, flavour, pageType, this.getAttributeToPropertyMappings());
cv.parser.WidgetParser.parseRefresh(xml, path);
return data;
},
getAttributeToPropertyMappings: function () {
return {
'width' : { "default": "100%" },
'height' : {},
'src' : {},
'widthfit' : { target: 'widthFit', transform: function(value) {
return value === "true";
}}
};
}
},
defer: function(statics) {
// register the parser
cv.parser.WidgetParser.addHandler("image", statics);
}
});
| joltcoke/CometVisu | source/class/cv/parser/widgets/Image.js | JavaScript | gpl-3.0 | 2,083 |
<?php
echo("Discovery protocols:");
global $link_exists;
$community = $device['community'];
if ($device['os'] == "ironware")
{
echo(" Brocade FDP: ");
$fdp_array = snmpwalk_cache_twopart_oid($device, "snFdpCacheEntry", array(), "FOUNDRY-SN-SWITCH-GROUP-MIB");
if ($fdp_array)
{
unset($fdp_links);
foreach (array_keys($fdp_array) as $key)
{
$interface = dbFetchRow("SELECT * FROM `ports` WHERE `device_id` = ? AND `ifIndex` = ?",array($device['device_id'],$key));
$fdp_if_array = $fdp_array[$key];
foreach (array_keys($fdp_if_array) as $entry_key)
{
$fdp = $fdp_if_array[$entry_key];
$remote_device_id = dbFetchCell("SELECT `device_id` FROM `devices` WHERE `sysName` = ? OR `hostname` = ?",array($fdp['snFdpCacheDeviceId'], $fdp['snFdpCacheDeviceId']));
if (!$remote_device_id)
{
$remote_device_id = discover_new_device($fdp['snFdpCacheDeviceId']);
if ($remote_device_id)
{
$int = ifNameDescr($interface);
log_event("Device autodiscovered through FDP on " . $device['hostname'] . " (port " . $int['label'] . ")", $remote_device_id, 'interface', $int['port_id']);
}
}
if ($remote_device_id)
{
$if = $fdp['snFdpCacheDevicePort'];
$remote_port_id = dbFetchCell("SELECT port_id FROM `ports` WHERE (`ifDescr` = ? OR `ifName = ?) AND `device_id` = ?",array($if,$if,$remote_device_id));
} else { $remote_port_id = "0"; }
discover_link($interface['port_id'], $fdp['snFdpCacheVendorId'], $remote_port_id, $fdp['snFdpCacheDeviceId'], $fdp['snFdpCacheDevicePort'], $fdp['snFdpCachePlatform'], $fdp['snFdpCacheVersion']);
}
}
}
}
echo(" CISCO-CDP-MIB: ");
unset($cdp_array);
$cdp_array = snmpwalk_cache_twopart_oid($device, "cdpCache", array(), "CISCO-CDP-MIB");
if ($cdp_array)
{
unset($cdp_links);
foreach (array_keys($cdp_array) as $key)
{
$interface = dbFetchRow("SELECT * FROM `ports` WHERE device_id = ? AND `ifIndex` = ?", array($device['device_id'], $key));
$cdp_if_array = $cdp_array[$key];
foreach (array_keys($cdp_if_array) as $entry_key)
{
$cdp = $cdp_if_array[$entry_key];
if (is_valid_hostname($cdp['cdpCacheDeviceId']))
{
$remote_device_id = dbFetchCell("SELECT `device_id` FROM `devices` WHERE `sysName` = ? OR `hostname` = ?", array($cdp['cdpCacheDeviceId'], $cdp['cdpCacheDeviceId']));
if (!$remote_device_id)
{
$remote_device_id = discover_new_device($cdp['cdpCacheDeviceId']);
if ($remote_device_id)
{
$int = ifNameDescr($interface);
log_event("Device autodiscovered through CDP on " . $device['hostname'] . " (port " . $int['label'] . ")", $remote_device_id, 'interface', $int['port_id']);
}
}
if ($remote_device_id)
{
$if = $cdp['cdpCacheDevicePort'];
$remote_port_id = dbFetchCell("SELECT port_id FROM `ports` WHERE (`ifDescr` = ? OR `ifName` = ?) AND `device_id` = ?", array($if, $if, $remote_device_id));
} else { $remote_port_id = "0"; }
if ($interface['port_id'] && $cdp['cdpCacheDeviceId'] && $cdp['cdpCacheDevicePort'])
{
discover_link($interface['port_id'], 'cdp', $remote_port_id, $cdp['cdpCacheDeviceId'], $cdp['cdpCacheDevicePort'], $cdp['cdpCachePlatform'], $cdp['cdpCacheVersion']);
}
}
else
{
echo("X");
}
}
}
}
echo(" LLDP-MIB: ");
unset($lldp_array);
$lldp_array = snmpwalk_cache_threepart_oid($device, "lldpRemoteSystemsData", array(), "LLDP-MIB");
$dot1d_array = snmpwalk_cache_oid($device, "dot1dBasePortIfIndex", array(), "BRIDGE-MIB");
if ($lldp_array)
{
$lldp_links = "";
foreach (array_keys($lldp_array) as $key)
{
$lldp_if_array = $lldp_array[$key];
foreach (array_keys($lldp_if_array) as $entry_key)
{
if (is_numeric($dot1d_array[$entry_key]['dot1dBasePortIfIndex']))
{
$ifIndex = $dot1d_array[$entry_key]['dot1dBasePortIfIndex'];
} else {
$ifIndex = $entry_key;
}
$interface = dbFetchRow("SELECT * FROM `ports` WHERE `device_id` = ? AND `ifIndex` = ?",array($device['device_id'],$ifIndex));
$lldp_instance = $lldp_if_array[$entry_key];
foreach (array_keys($lldp_instance) as $entry_instance)
{
$lldp = $lldp_instance[$entry_instance];
$remote_device_id = dbFetchCell("SELECT `device_id` FROM `devices` WHERE `sysName` = ? OR `hostname` = ?",array($lldp['lldpRemSysName'], $lldp['lldpRemSysName']));
if (!$remote_device_id && is_valid_hostname($lldp['lldpRemSysName']))
{
$remote_device_id = discover_new_device($lldp['lldpRemSysName']);
if ($remote_device_id)
{
$int = ifNameDescr($interface);
log_event("Device autodiscovered through LLDP on " . $device['hostname'] . " (port " . $int['label'] . ")", $remote_device_id, 'interface', $int['port_id']);
}
}
if ($remote_device_id)
{
$if = $lldp['lldpRemPortDesc']; $id = $lldp['lldpRemPortId'];
$remote_port_id = dbFetchCell("SELECT `port_id` FROM `ports` WHERE (`ifDescr` = ? OR `ifName` = ? OR `ifDescr` = ? OR `ifName` = ?) AND `device_id` = ?",array($if,$if,$id,$id,$remote_device_id));
} else {
$remote_port_id = "0";
}
if (is_numeric($interface['port_id']) && isset($lldp['lldpRemSysName']) && isset($lldp['lldpRemPortId']))
{
discover_link($interface['port_id'], 'lldp', $remote_port_id, $lldp['lldpRemSysName'], $lldp['lldpRemPortId'], NULL, $lldp['lldpRemSysDesc']);
}
}
}
}
}
if ($debug) { print_r($link_exists); }
$sql = "SELECT * FROM `links` AS L, `ports` AS I WHERE L.local_port_id = I.port_id AND I.device_id = '".$device['device_id']."'";
foreach (dbFetchRows($sql) as $test)
{
$local_port_id = $test['local_port_id'];
$remote_hostname = $test['remote_hostname'];
$remote_port = $test['remote_port'];
if ($debug) { echo("$local_port_id -> $remote_hostname -> $remote_port \n"); }
if (!$link_exists[$local_port_id][$remote_hostname][$remote_port])
{
echo("-");
$rows = dbDelete('links', '`id` = ?', array($test['id']));
if ($debug) { echo("$rows deleted "); }
}
}
unset($link_exists);
echo("\n");
?>
| wojons/librenms | includes/discovery/discovery-protocols.inc.php | PHP | gpl-3.0 | 6,429 |
/*
Copyright 2014 Red Hat, Inc. and/or its affiliates.
This file is part of lightblue.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.redhat.lightblue.hystrix.ldap;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.unboundid.ldap.sdk.LDAPConnection;
public abstract class AbstractLdapHystrixCommand<T> extends HystrixCommand<T>{
public static final String GROUPKEY = "ldap";
private final LDAPConnection connection;
public LDAPConnection getConnection(){
return connection;
}
public AbstractLdapHystrixCommand(LDAPConnection connection, String commandKey){
super(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(GROUPKEY)).
andCommandKey(HystrixCommandKey.Factory.asKey(GROUPKEY + ":" + commandKey)));
this.connection = connection;
}
}
| dcrissman/lightblue-ldap | lightblue-ldap-hystrix/src/main/java/com/redhat/lightblue/hystrix/ldap/AbstractLdapHystrixCommand.java | Java | gpl-3.0 | 1,527 |
#include "intfile.hh"
dcmplx Pf8(const double x[], double es[], double esx[], double em[], double lambda, double lrs[], double bi) {
double x0=x[0];
double x1=x[1];
double x2=x[2];
dcmplx y[149];
dcmplx FOUT;
dcmplx MYI(0.,1.);
y[1]=1./bi;
y[2]=em[0];
y[3]=x0*x0;
y[4]=em[3];
y[5]=em[1];
y[6]=em[2];
y[7]=esx[0];
y[8]=y[1]*y[5];
y[9]=-(y[1]*y[7]);
y[10]=-x1;
y[11]=1.+y[10];
y[12]=x0*y[1]*y[2];
y[13]=y[1]*y[2]*y[3];
y[14]=2.*x2*y[1]*y[2]*y[3];
y[15]=y[1]*y[3]*y[5];
y[16]=x0*y[1]*y[6];
y[17]=x0*y[1]*y[4];
y[18]=2.*x1*y[1]*y[3]*y[4];
y[19]=-(y[1]*y[3]*y[7]);
y[20]=y[12]+y[13]+y[14]+y[15]+y[16]+y[17]+y[18]+y[19];
y[21]=-x0;
y[22]=1.+y[21];
y[23]=x2*x2;
y[24]=x1*x1;
y[25]=lrs[0];
y[26]=x2*y[1]*y[2];
y[27]=2.*x0*x1*y[1]*y[5];
y[28]=x1*y[1]*y[6];
y[29]=x1*y[1]*y[4];
y[30]=2.*x0*y[1]*y[4]*y[24];
y[31]=x1*x2*y[1]*y[2];
y[32]=2.*x0*x1*x2*y[1]*y[2];
y[33]=y[1]*y[2]*y[23];
y[34]=2.*x0*x1*y[1]*y[2]*y[23];
y[35]=x1*y[1]*y[5];
y[36]=x2*y[1]*y[5];
y[37]=2.*x0*x1*x2*y[1]*y[5];
y[38]=x1*x2*y[1]*y[6];
y[39]=y[1]*y[4]*y[24];
y[40]=x1*x2*y[1]*y[4];
y[41]=2.*x0*x2*y[1]*y[4]*y[24];
y[42]=-(x1*y[1]*y[7]);
y[43]=-(x2*y[1]*y[7]);
y[44]=-2.*x0*x1*x2*y[1]*y[7];
y[45]=y[8]+y[26]+y[27]+y[28]+y[29]+y[30]+y[31]+y[32]+y[33]+y[34]+y[35]+y[36]\
+y[37]+y[38]+y[39]+y[40]+y[41]+y[42]+y[43]+y[44];
y[46]=lrs[1];
y[47]=-x2;
y[48]=1.+y[47];
y[49]=y[1]*y[2];
y[50]=x1*y[1]*y[2];
y[51]=2.*x0*x1*y[1]*y[2];
y[52]=2.*x2*y[1]*y[2];
y[53]=4.*x0*x1*x2*y[1]*y[2];
y[54]=-2.*x0*x1*y[1]*y[7];
y[55]=y[8]+y[9]+y[27]+y[28]+y[29]+y[30]+y[49]+y[50]+y[51]+y[52]+y[53]+y[54];
y[56]=lambda*lambda;
y[57]=2.*x0*x2*y[1]*y[2];
y[58]=2.*x0*y[1]*y[2]*y[23];
y[59]=2.*x0*y[1]*y[5];
y[60]=2.*x0*x2*y[1]*y[5];
y[61]=y[1]*y[6];
y[62]=x2*y[1]*y[6];
y[63]=y[1]*y[4];
y[64]=2.*x1*y[1]*y[4];
y[65]=4.*x0*x1*y[1]*y[4];
y[66]=x2*y[1]*y[4];
y[67]=4.*x0*x1*x2*y[1]*y[4];
y[68]=-2.*x0*x2*y[1]*y[7];
y[69]=y[8]+y[9]+y[26]+y[57]+y[58]+y[59]+y[60]+y[61]+y[62]+y[63]+y[64]+y[65]+\
y[66]+y[67]+y[68];
y[70]=x0*x2*y[1]*y[2];
y[71]=x2*y[1]*y[2]*y[3];
y[72]=y[1]*y[2]*y[3]*y[23];
y[73]=x0*y[1]*y[5];
y[74]=x2*y[1]*y[3]*y[5];
y[75]=x0*x2*y[1]*y[6];
y[76]=2.*x0*x1*y[1]*y[4];
y[77]=x0*x2*y[1]*y[4];
y[78]=2.*x1*x2*y[1]*y[3]*y[4];
y[79]=-(x0*y[1]*y[7]);
y[80]=-(x2*y[1]*y[3]*y[7]);
y[81]=y[15]+y[16]+y[17]+y[18]+y[61]+y[70]+y[71]+y[72]+y[73]+y[74]+y[75]+y[76\
]+y[77]+y[78]+y[79]+y[80];
y[82]=lrs[2];
y[83]=2.*x1*x2*y[1]*y[2];
y[84]=2.*x1*y[1]*y[2]*y[23];
y[85]=2.*x1*y[1]*y[5];
y[86]=2.*x1*x2*y[1]*y[5];
y[87]=2.*y[1]*y[4]*y[24];
y[88]=2.*x2*y[1]*y[4]*y[24];
y[89]=-2.*x1*x2*y[1]*y[7];
y[90]=y[83]+y[84]+y[85]+y[86]+y[87]+y[88]+y[89];
y[91]=-(lambda*MYI*x0*y[22]*y[25]*y[90]);
y[92]=-(lambda*MYI*y[22]*y[25]*y[45]);
y[93]=lambda*MYI*x0*y[25]*y[45];
y[94]=1.+y[91]+y[92]+y[93];
y[95]=2.*x0*y[1]*y[4];
y[96]=2.*y[1]*y[3]*y[4];
y[97]=2.*x2*y[1]*y[3]*y[4];
y[98]=y[95]+y[96]+y[97];
y[99]=-(lambda*MYI*x1*y[11]*y[46]*y[98]);
y[100]=-(lambda*MYI*y[11]*y[46]*y[81]);
y[101]=lambda*MYI*x1*y[46]*y[81];
y[102]=1.+y[99]+y[100]+y[101];
y[103]=x0*x1*y[1]*y[2];
y[104]=x1*y[1]*y[2]*y[3];
y[105]=2.*x1*x2*y[1]*y[2]*y[3];
y[106]=x1*y[1]*y[3]*y[5];
y[107]=x0*x1*y[1]*y[6];
y[108]=x0*x1*y[1]*y[4];
y[109]=y[1]*y[3]*y[4]*y[24];
y[110]=-(x1*y[1]*y[3]*y[7]);
y[111]=y[12]+y[57]+y[61]+y[73]+y[79]+y[103]+y[104]+y[105]+y[106]+y[107]+y[10\
8]+y[109]+y[110];
y[112]=-(lambda*MYI*x1*y[11]*y[46]*y[81]);
y[113]=x1+y[112];
y[114]=-(lambda*MYI*x0*y[22]*y[25]*y[45]);
y[115]=x0+y[114];
y[116]=-(lambda*MYI*x2*y[48]*y[82]*y[111]);
y[117]=x2+y[116];
y[118]=pow(bi,-2);
y[119]=x0*x1*y[11]*y[22]*y[25]*y[46]*y[55]*y[56]*y[69];
y[120]=-(lambda*MYI*x1*y[11]*y[20]*y[46]*y[94]);
y[121]=y[119]+y[120];
y[122]=lambda*MYI*x2*y[20]*y[48]*y[82]*y[121];
y[123]=-(x0*x1*y[11]*y[20]*y[22]*y[25]*y[46]*y[56]*y[69]);
y[124]=lambda*MYI*x0*y[22]*y[25]*y[55]*y[102];
y[125]=y[123]+y[124];
y[126]=-(lambda*MYI*x2*y[48]*y[55]*y[82]*y[125]);
y[127]=pow(y[69],2);
y[128]=x0*x1*y[11]*y[22]*y[25]*y[46]*y[56]*y[127];
y[129]=y[94]*y[102];
y[130]=y[128]+y[129];
y[131]=2.*x0*y[1]*y[2];
y[132]=2.*x1*y[1]*y[2]*y[3];
y[133]=y[131]+y[132];
y[134]=-(lambda*MYI*x2*y[48]*y[82]*y[133]);
y[135]=-(lambda*MYI*y[48]*y[82]*y[111]);
y[136]=lambda*MYI*x2*y[82]*y[111];
y[137]=1.+y[134]+y[135]+y[136];
y[138]=y[130]*y[137];
y[139]=y[122]+y[126]+y[138];
y[140]=y[1]*y[113];
y[141]=y[1]*y[113]*y[115];
y[142]=y[1]*y[117];
y[143]=y[1]*y[113]*y[115]*y[117];
y[144]=y[1]+y[140]+y[141]+y[142]+y[143];
y[145]=pow(y[144],-2);
y[146]=pow(y[115],2);
y[147]=pow(y[113],2);
y[148]=pow(y[117],2);
FOUT=myLog(bi)*y[118]*y[139]*y[145]+myLog(x0)*y[118]*y[139]*y[145]+myLog(1.+\
y[92])*y[118]*y[139]*y[145]+3.*myLog(y[144])*y[118]*y[139]*y[145]-2.*myLog(\
y[61]+y[1]*y[6]*y[113]+y[1]*y[5]*y[115]+y[1]*y[4]*y[113]*y[115]+y[1]*y[5]*y\
[113]*y[115]+y[1]*y[6]*y[113]*y[115]-y[1]*y[7]*y[113]*y[115]+y[1]*y[6]*y[11\
7]+y[1]*y[2]*y[115]*y[117]+y[1]*y[5]*y[115]*y[117]-y[1]*y[7]*y[115]*y[117]+\
y[1]*y[2]*y[113]*y[115]*y[117]+y[1]*y[4]*y[113]*y[115]*y[117]+y[1]*y[6]*y[1\
13]*y[115]*y[117]+y[1]*y[5]*y[113]*y[146]+y[1]*y[2]*y[113]*y[117]*y[146]+y[\
1]*y[5]*y[113]*y[117]*y[146]-y[1]*y[7]*y[113]*y[117]*y[146]+y[1]*y[4]*y[115\
]*y[147]+y[1]*y[4]*y[146]*y[147]+y[1]*y[4]*y[117]*y[146]*y[147]+y[1]*y[2]*y\
[115]*y[148]+y[1]*y[2]*y[113]*y[146]*y[148])*y[118]*y[139]*y[145];
return (FOUT);
}
| HEPcodes/FeynHiggs | extse/OasatPdep.app/SecDec3/loop/T1234m1234/together/epstothe1/f8.cc | C++ | gpl-3.0 | 5,226 |
/*
* Syncany, www.syncany.org
* Copyright (C) 2011 Philipp C. Heckel <philipp.heckel@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.stacksync.desktop.watch.local;
import java.io.File;
import org.apache.log4j.Logger;
import com.stacksync.desktop.Environment;
import com.stacksync.desktop.Environment.OperatingSystem;
import com.stacksync.desktop.config.Config;
import com.stacksync.desktop.config.Folder;
import com.stacksync.desktop.config.profile.Profile;
import com.stacksync.desktop.index.Indexer;
import com.stacksync.desktop.util.FileUtil;
/**
*
* @author oubou68, pheckel
*/
public abstract class LocalWatcher {
protected final Logger logger = Logger.getLogger(LocalWatcher.class.getName());
protected static final Environment env = Environment.getInstance();
protected static LocalWatcher instance;
protected Config config;
protected Indexer indexer;
public LocalWatcher() {
initDependencies();
logger.info("Creating watcher ...");
}
private void initDependencies() {
config = Config.getInstance();
indexer = Indexer.getInstance();
}
public void queueCheckFile(Folder root, File file) {
// Exclude ".ignore*" files from everything
if (FileUtil.checkIgnoreFile(root, file)) {
logger.debug("Watcher: Ignoring file "+file.getAbsolutePath());
return;
}
// File vanished!
if (!file.exists()) {
logger.warn("Watcher: File "+file+" vanished. IGNORING.");
return;
}
// Add to queue
logger.info("Watcher: Checking new/modified file "+file);
indexer.queueChecked(root, file);
}
public void queueMoveFile(Folder fromRoot, File fromFile, Folder toRoot, File toFile) {
// Exclude ".ignore*" files from everything
if (FileUtil.checkIgnoreFile(fromRoot, fromFile) || FileUtil.checkIgnoreFile(toRoot, toFile)) {
logger.info("Watcher: Ignoring file "+fromFile.getAbsolutePath());
return;
}
// File vanished!
if (!toFile.exists()) {
logger.warn("Watcher: File "+toFile+" vanished. IGNORING.");
return;
}
// Add to queue
logger.info("Watcher: Moving file "+fromFile+" TO "+toFile+"");
indexer.queueMoved(fromRoot, fromFile, toRoot, toFile);
}
public void queueDeleteFile(Folder root, File file) {
// Exclude ".ignore*" files from everything
if (FileUtil.checkIgnoreFile(root, file)) {
logger.info("Watcher: Ignoring file "+file.getAbsolutePath());
return;
}
// Add to queue
logger.info("Watcher: Deleted file "+file+"");
indexer.queueDeleted(root, file);
}
public static synchronized LocalWatcher getInstance() {
if (instance != null) {
return instance;
}
if (env.getOperatingSystem() == OperatingSystem.Linux
|| env.getOperatingSystem() == OperatingSystem.Windows
|| env.getOperatingSystem() == OperatingSystem.Mac) {
instance = new CommonLocalWatcher();
return instance;
}
throw new RuntimeException("Your operating system is currently not supported: " + System.getProperty("os.name"));
}
public abstract void start();
public abstract void stop();
public abstract void watch(Profile profile);
public abstract void unwatch(Profile profile);
}
| pviotti/stacksync-desktop | src/com/stacksync/desktop/watch/local/LocalWatcher.java | Java | gpl-3.0 | 4,196 |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 5 End-User License
Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
27th April 2017).
End User License Agreement: www.juce.com/juce-5-licence
Privacy Policy: www.juce.com/juce-5-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
class ScrollBar::ScrollbarButton : public Button
{
public:
ScrollbarButton (int direc, ScrollBar& s)
: Button (String()), direction (direc), owner (s)
{
setWantsKeyboardFocus (false);
}
void paintButton (Graphics& g, bool over, bool down) override
{
getLookAndFeel().drawScrollbarButton (g, owner, getWidth(), getHeight(),
direction, owner.isVertical(), over, down);
}
void clicked() override
{
owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
}
int direction;
private:
ScrollBar& owner;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollbarButton)
};
//==============================================================================
ScrollBar::ScrollBar (const bool shouldBeVertical)
: totalRange (0.0, 1.0),
visibleRange (0.0, 0.1),
singleStepSize (0.1),
thumbAreaStart (0),
thumbAreaSize (0),
thumbStart (0),
thumbSize (0),
initialDelayInMillisecs (100),
repeatDelayInMillisecs (50),
minimumDelayInMillisecs (10),
vertical (shouldBeVertical),
isDraggingThumb (false),
autohides (true)
{
setRepaintsOnMouseActivity (true);
setFocusContainer (true);
}
ScrollBar::~ScrollBar()
{
upButton = nullptr;
downButton = nullptr;
}
//==============================================================================
void ScrollBar::setRangeLimits (Range<double> newRangeLimit, NotificationType notification)
{
if (totalRange != newRangeLimit)
{
totalRange = newRangeLimit;
setCurrentRange (visibleRange, notification);
updateThumbPosition();
}
}
void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum, NotificationType notification)
{
jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
setRangeLimits (Range<double> (newMinimum, newMaximum), notification);
}
bool ScrollBar::setCurrentRange (Range<double> newRange, const NotificationType notification)
{
const Range<double> constrainedRange (totalRange.constrainRange (newRange));
if (visibleRange != constrainedRange)
{
visibleRange = constrainedRange;
updateThumbPosition();
if (notification != dontSendNotification)
triggerAsyncUpdate();
if (notification == sendNotificationSync)
handleUpdateNowIfNeeded();
return true;
}
return false;
}
void ScrollBar::setCurrentRange (const double newStart, const double newSize, NotificationType notification)
{
setCurrentRange (Range<double> (newStart, newStart + newSize), notification);
}
void ScrollBar::setCurrentRangeStart (const double newStart, NotificationType notification)
{
setCurrentRange (visibleRange.movedToStartAt (newStart), notification);
}
void ScrollBar::setSingleStepSize (const double newSingleStepSize) noexcept
{
singleStepSize = newSingleStepSize;
}
bool ScrollBar::moveScrollbarInSteps (const int howManySteps, NotificationType notification)
{
return setCurrentRange (visibleRange + howManySteps * singleStepSize, notification);
}
bool ScrollBar::moveScrollbarInPages (const int howManyPages, NotificationType notification)
{
return setCurrentRange (visibleRange + howManyPages * visibleRange.getLength(), notification);
}
bool ScrollBar::scrollToTop (NotificationType notification)
{
return setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()), notification);
}
bool ScrollBar::scrollToBottom (NotificationType notification)
{
return setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()), notification);
}
void ScrollBar::setButtonRepeatSpeed (const int newInitialDelay,
const int newRepeatDelay,
const int newMinimumDelay)
{
initialDelayInMillisecs = newInitialDelay;
repeatDelayInMillisecs = newRepeatDelay;
minimumDelayInMillisecs = newMinimumDelay;
if (upButton != nullptr)
{
upButton ->setRepeatSpeed (newInitialDelay, newRepeatDelay, newMinimumDelay);
downButton->setRepeatSpeed (newInitialDelay, newRepeatDelay, newMinimumDelay);
}
}
//==============================================================================
void ScrollBar::addListener (Listener* const listener)
{
listeners.add (listener);
}
void ScrollBar::removeListener (Listener* const listener)
{
listeners.remove (listener);
}
void ScrollBar::handleAsyncUpdate()
{
double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
}
//==============================================================================
void ScrollBar::updateThumbPosition()
{
const int minimumScrollBarThumbSize = getLookAndFeel().getMinimumScrollbarThumbSize (*this);
int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
: thumbAreaSize);
if (newThumbSize < minimumScrollBarThumbSize)
newThumbSize = jmin (minimumScrollBarThumbSize, thumbAreaSize - 1);
if (newThumbSize > thumbAreaSize)
newThumbSize = thumbAreaSize;
int newThumbStart = thumbAreaStart;
if (totalRange.getLength() > visibleRange.getLength())
newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
/ (totalRange.getLength() - visibleRange.getLength()));
setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength()
&& visibleRange.getLength() > 0.0));
if (thumbStart != newThumbStart || thumbSize != newThumbSize)
{
const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
if (vertical)
repaint (0, repaintStart, getWidth(), repaintSize);
else
repaint (repaintStart, 0, repaintSize, getHeight());
thumbStart = newThumbStart;
thumbSize = newThumbSize;
}
}
void ScrollBar::setOrientation (const bool shouldBeVertical)
{
if (vertical != shouldBeVertical)
{
vertical = shouldBeVertical;
if (upButton != nullptr)
{
upButton->direction = vertical ? 0 : 3;
downButton->direction = vertical ? 2 : 1;
}
updateThumbPosition();
}
}
void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
{
autohides = shouldHideWhenFullRange;
updateThumbPosition();
}
bool ScrollBar::autoHides() const noexcept
{
return autohides;
}
//==============================================================================
void ScrollBar::paint (Graphics& g)
{
if (thumbAreaSize > 0)
{
LookAndFeel& lf = getLookAndFeel();
const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
? thumbSize : 0;
if (vertical)
lf.drawScrollbar (g, *this, 0, thumbAreaStart, getWidth(), thumbAreaSize,
vertical, thumbStart, thumb, isMouseOver(), isMouseButtonDown());
else
lf.drawScrollbar (g, *this, thumbAreaStart, 0, thumbAreaSize, getHeight(),
vertical, thumbStart, thumb, isMouseOver(), isMouseButtonDown());
}
}
void ScrollBar::lookAndFeelChanged()
{
setComponentEffect (getLookAndFeel().getScrollbarEffect());
if (isVisible())
resized();
}
void ScrollBar::resized()
{
const int length = vertical ? getHeight() : getWidth();
LookAndFeel& lf = getLookAndFeel();
const bool buttonsVisible = lf.areScrollbarButtonsVisible();
int buttonSize = 0;
if (buttonsVisible)
{
if (upButton == nullptr)
{
addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
}
buttonSize = jmin (lf.getScrollbarButtonSize (*this), length / 2);
}
else
{
upButton = nullptr;
downButton = nullptr;
}
if (length < 32 + lf.getMinimumScrollbarThumbSize (*this))
{
thumbAreaStart = length / 2;
thumbAreaSize = 0;
}
else
{
thumbAreaStart = buttonSize;
thumbAreaSize = length - 2 * buttonSize;
}
if (upButton != nullptr)
{
Rectangle<int> r (getLocalBounds());
if (vertical)
{
upButton->setBounds (r.removeFromTop (buttonSize));
downButton->setBounds (r.removeFromBottom (buttonSize));
}
else
{
upButton->setBounds (r.removeFromLeft (buttonSize));
downButton->setBounds (r.removeFromRight (buttonSize));
}
}
updateThumbPosition();
}
void ScrollBar::parentHierarchyChanged()
{
lookAndFeelChanged();
}
void ScrollBar::mouseDown (const MouseEvent& e)
{
isDraggingThumb = false;
lastMousePos = vertical ? e.y : e.x;
dragStartMousePos = lastMousePos;
dragStartRange = visibleRange.getStart();
if (dragStartMousePos < thumbStart)
{
moveScrollbarInPages (-1);
startTimer (400);
}
else if (dragStartMousePos >= thumbStart + thumbSize)
{
moveScrollbarInPages (1);
startTimer (400);
}
else
{
isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
&& (thumbAreaSize > thumbSize);
}
}
void ScrollBar::mouseDrag (const MouseEvent& e)
{
const int mousePos = vertical ? e.y : e.x;
if (isDraggingThumb && lastMousePos != mousePos && thumbAreaSize > thumbSize)
{
const int deltaPixels = mousePos - dragStartMousePos;
setCurrentRangeStart (dragStartRange
+ deltaPixels * (totalRange.getLength() - visibleRange.getLength())
/ (thumbAreaSize - thumbSize));
}
lastMousePos = mousePos;
}
void ScrollBar::mouseUp (const MouseEvent&)
{
isDraggingThumb = false;
stopTimer();
repaint();
}
void ScrollBar::mouseWheelMove (const MouseEvent&, const MouseWheelDetails& wheel)
{
float increment = 10.0f * (vertical ? wheel.deltaY : wheel.deltaX);
if (increment < 0)
increment = jmin (increment, -1.0f);
else if (increment > 0)
increment = jmax (increment, 1.0f);
setCurrentRange (visibleRange - singleStepSize * increment);
}
void ScrollBar::timerCallback()
{
if (isMouseButtonDown())
{
startTimer (40);
if (lastMousePos < thumbStart)
setCurrentRange (visibleRange - visibleRange.getLength());
else if (lastMousePos > thumbStart + thumbSize)
setCurrentRangeStart (visibleRange.getEnd());
}
else
{
stopTimer();
}
}
bool ScrollBar::keyPressed (const KeyPress& key)
{
if (isVisible())
{
if (key == KeyPress::upKey || key == KeyPress::leftKey) return moveScrollbarInSteps (-1);
if (key == KeyPress::downKey || key == KeyPress::rightKey) return moveScrollbarInSteps (1);
if (key == KeyPress::pageUpKey) return moveScrollbarInPages (-1);
if (key == KeyPress::pageDownKey) return moveScrollbarInPages (1);
if (key == KeyPress::homeKey) return scrollToTop();
if (key == KeyPress::endKey) return scrollToBottom();
}
return false;
}
| gbevin/HEELP | JuceLibraryCode/modules/juce_gui_basics/layout/juce_ScrollBar.cpp | C++ | gpl-3.0 | 12,905 |
<?php
/*
**************************************************************************************************************************
** CORAL Resources Module v. 1.2
**
** Copyright (c) 2010 University of Notre Dame
**
** This file is part of CORAL.
**
** CORAL 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.
**
** CORAL 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 CORAL. If not, see <http://www.gnu.org/licenses/>.
**
**************************************************************************************************************************
*/
class Resource extends DatabaseObject {
protected function defineRelationships() {}
protected function defineIsbnOrIssn() {}
protected function overridePrimaryKeyName() {}
//returns resource objects by title
public function getResourceByTitle($title){
$query = "SELECT *
FROM Resource
WHERE UPPER(titleText) = '" . str_replace("'", "''", strtoupper($title)) . "'
ORDER BY 1";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceID'])){
$object = new Resource(new NamedArguments(array('primaryKey' => $result['resourceID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Resource(new NamedArguments(array('primaryKey' => $row['resourceID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns resource objects by title
public function getResourceByIsbnOrISSN($isbnOrISSN){
$query = "SELECT DISTINCT(resourceID)
FROM IsbnOrIssn";
$i = 0;
if (!is_array($isbnOrISSN)) {
$value = $isbnOrISSN;
$isbnOrISSN = array($value);
}
foreach ($isbnOrISSN as $value) {
$query .= ($i == 0) ? " WHERE " : " OR ";
$query .= "isbnOrIssn = '" . $this->db->escapeString($value) . "'";
$i++;
}
$query .= " ORDER BY 1";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceID'])){
$object = new Resource(new NamedArguments(array('primaryKey' => $result['resourceID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Resource(new NamedArguments(array('primaryKey' => $row['resourceID'])));
array_push($objects, $object);
}
}
return $objects;
}
public function getIsbnOrIssn() {
$query = "SELECT *
FROM IsbnOrIssn
WHERE resourceID = '" . $this->resourceID . "'
ORDER BY 1";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['isbnOrIssnID'])){
$object = new IsbnOrIssn(new NamedArguments(array('primaryKey' => $result['isbnOrIssnID'])));
array_push($objects, $object);
} else {
foreach ($result as $row) {
$object = new IsbnOrIssn(new NamedArguments(array('primaryKey' => $row['isbnOrIssnID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of parent resource objects
public function getParentResources(){
return $this->getRelatedResources('resourceID');
}
//returns array of child resource objects
public function getChildResources(){
return $this->getRelatedResources('relatedResourceID');
}
// return array of related resource objects
private function getRelatedResources($key) {
$query = "SELECT *
FROM ResourceRelationship
WHERE $key = '" . $this->resourceID . "'
AND relationshipTypeID = '1'
ORDER BY 1";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result[$key])){
$object = new ResourceRelationship(new NamedArguments(array('primaryKey' => $result['resourceRelationshipID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourceRelationship(new NamedArguments(array('primaryKey' => $row['resourceRelationshipID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of purchase site objects
public function getResourcePurchaseSites(){
$query = "SELECT PurchaseSite.* FROM PurchaseSite, ResourcePurchaseSiteLink RPSL where RPSL.purchaseSiteID = PurchaseSite.purchaseSiteID AND resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['purchaseSiteID'])){
$object = new PurchaseSite(new NamedArguments(array('primaryKey' => $result['purchaseSiteID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new PurchaseSite(new NamedArguments(array('primaryKey' => $row['purchaseSiteID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of ResourcePayment objects
public function getResourcePayments(){
$query = "SELECT * FROM ResourcePayment WHERE resourceID = '" . $this->resourceID . "' ORDER BY year DESC, fundName, subscriptionStartDate DESC";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourcePaymentID'])){
$object = new ResourcePayment(new NamedArguments(array('primaryKey' => $result['resourcePaymentID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourcePayment(new NamedArguments(array('primaryKey' => $row['resourcePaymentID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of associated licenses
public function getLicenseArray(){
$config = new Configuration;
//if the lic module is installed get the lic name from lic database
if ($config->settings->licensingModule == 'Y'){
$dbName = $config->settings->licensingDatabaseName;
$resourceLicenseArray = array();
$query = "SELECT * FROM ResourceLicenseLink WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['licenseID'])){
$licArray = array();
//first, get the license name
$query = "SELECT shortName FROM " . $dbName . ".License WHERE licenseID = " . $result['licenseID'];
if ($licResult = $this->db->query($query)){
while ($licRow = $licResult->fetch_assoc()){
$licArray['license'] = $licRow['shortName'];
$licArray['licenseID'] = $result['licenseID'];
}
}
array_push($resourceLicenseArray, $licArray);
}else{
foreach ($result as $row) {
$licArray = array();
//first, get the license name
$query = "SELECT shortName FROM " . $dbName . ".License WHERE licenseID = " . $row['licenseID'];
if ($licResult = $this->db->query($query)){
while ($licRow = $licResult->fetch_assoc()){
$licArray['license'] = $licRow['shortName'];
$licArray['licenseID'] = $row['licenseID'];
}
}
array_push($resourceLicenseArray, $licArray);
}
}
return $resourceLicenseArray;
}
}
//returns array of resource license status objects
public function getResourceLicenseStatuses(){
$query = "SELECT * FROM ResourceLicenseStatus WHERE resourceID = '" . $this->resourceID . "' ORDER BY licenseStatusChangeDate desc;";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceLicenseStatusID'])){
$object = new ResourceLicenseStatus(new NamedArguments(array('primaryKey' => $result['resourceLicenseStatusID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourceLicenseStatus(new NamedArguments(array('primaryKey' => $row['resourceLicenseStatusID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns LicenseStatusID of the most recent resource license status
public function getCurrentResourceLicenseStatus(){
$query = "SELECT licenseStatusID FROM ResourceLicenseStatus RLS WHERE resourceID = '" . $this->resourceID . "' AND licenseStatusChangeDate = (SELECT MAX(licenseStatusChangeDate) FROM ResourceLicenseStatus WHERE ResourceLicenseStatus.resourceID = '" . $this->resourceID . "') LIMIT 0,1;";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['licenseStatusID'])){
return $result['licenseStatusID'];
}
}
//returns array of authorized site objects
public function getResourceAuthorizedSites(){
$query = "SELECT AuthorizedSite.* FROM AuthorizedSite, ResourceAuthorizedSiteLink RPSL where RPSL.authorizedSiteID = AuthorizedSite.authorizedSiteID AND resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['authorizedSiteID'])){
$object = new AuthorizedSite(new NamedArguments(array('primaryKey' => $result['authorizedSiteID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new AuthorizedSite(new NamedArguments(array('primaryKey' => $row['authorizedSiteID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of administering site objects
public function getResourceAdministeringSites(){
$query = "SELECT AdministeringSite.* FROM AdministeringSite, ResourceAdministeringSiteLink RPSL where RPSL.administeringSiteID = AdministeringSite.administeringSiteID AND resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['administeringSiteID'])){
$object = new AdministeringSite(new NamedArguments(array('primaryKey' => $result['administeringSiteID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new AdministeringSite(new NamedArguments(array('primaryKey' => $row['administeringSiteID'])));
array_push($objects, $object);
}
}
return $objects;
}
//deletes all parent resources associated with this resource
public function removeParentResources(){
$query = "DELETE FROM ResourceRelationship WHERE resourceID = '" . $this->resourceID . "'";
return $this->db->processQuery($query);
}
//returns array of alias objects
public function getAliases(){
$query = "SELECT * FROM Alias WHERE resourceID = '" . $this->resourceID . "' order by shortName";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['aliasID'])){
$object = new Alias(new NamedArguments(array('primaryKey' => $result['aliasID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Alias(new NamedArguments(array('primaryKey' => $row['aliasID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of contact objects
public function getUnarchivedContacts($moduleFilter=false){
$config = new Configuration;
$resultArray = array();
$contactsArray = array();
if (!$moduleFilter || $moduleFilter == 'resources') {
//get resource specific contacts first
$query = "SELECT C.*, GROUP_CONCAT(CR.shortName SEPARATOR '<br /> ') contactRoles
FROM Contact C, ContactRole CR, ContactRoleProfile CRP
WHERE (archiveDate = '0000-00-00' OR archiveDate is null)
AND C.contactID = CRP.contactID
AND CRP.contactRoleID = CR.contactRoleID
AND resourceID = '" . $this->resourceID . "'
GROUP BY C.contactID
ORDER BY C.name";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['contactID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($contactsArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($contactsArray, $resultArray);
}
}
}
//if the org module is installed also get the org contacts from org database
if ($config->settings->organizationsModule == 'Y' && (!$moduleFilter || $moduleFilter == 'organizations')) {
$dbName = $config->settings->organizationsDatabaseName;
$query = "SELECT distinct OC.*, O.name organizationName, GROUP_CONCAT(DISTINCT CR.shortName SEPARATOR '<br /> ') contactRoles
FROM " . $dbName . ".Contact OC, " . $dbName . ".ContactRole CR, " . $dbName . ".ContactRoleProfile CRP, " . $dbName . ".Organization O, Resource R, ResourceOrganizationLink ROL
WHERE (OC.archiveDate = '0000-00-00' OR OC.archiveDate is null)
AND R.resourceID = ROL.resourceID
AND ROL.organizationID = OC.organizationID
AND CRP.contactID = OC.contactID
AND CRP.contactRoleID = CR.contactRoleID
AND O.organizationID = OC.organizationID
AND R.resourceID = '" . $this->resourceID . "'
GROUP BY OC.contactID, O.name
ORDER BY OC.name";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['contactID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($contactsArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($contactsArray, $resultArray);
}
}
}
return $contactsArray;
}
//returns array of contact objects
public function getArchivedContacts(){
$config = new Configuration;
$contactsArray = array();
//get resource specific contacts
$query = "SELECT C.*, GROUP_CONCAT(CR.shortName SEPARATOR '<br /> ') contactRoles
FROM Contact C, ContactRole CR, ContactRoleProfile CRP
WHERE (archiveDate != '0000-00-00' && archiveDate != '')
AND C.contactID = CRP.contactID
AND CRP.contactRoleID = CR.contactRoleID
AND resourceID = '" . $this->resourceID . "'
GROUP BY C.contactID
ORDER BY C.name";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['contactID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($contactsArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($contactsArray, $resultArray);
}
}
//if the org module is installed also get the org contacts from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$query = "SELECT DISTINCT OC.*, O.name organizationName, GROUP_CONCAT(DISTINCT CR.shortName SEPARATOR '<br /> ') contactRoles
FROM " . $dbName . ".Contact OC, " . $dbName . ".ContactRole CR, " . $dbName . ".ContactRoleProfile CRP, " . $dbName . ".Organization O, Resource R, ResourceOrganizationLink ROL
WHERE (OC.archiveDate != '0000-00-00' && OC.archiveDate is not null)
AND R.resourceID = ROL.resourceID
AND ROL.organizationID = OC.organizationID
AND CRP.contactID = OC.contactID
AND CRP.contactRoleID = CR.contactRoleID
AND O.organizationID = OC.organizationID
AND R.resourceID = '" . $this->resourceID . "'
GROUP BY OC.contactID, O.name
ORDER BY OC.name";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['contactID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($contactsArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($contactsArray, $resultArray);
}
}
}
return $contactsArray;
}
//returns array of contact objects
public function getCreatorsArray(){
$creatorsArray = array();
$resultArray = array();
//get resource specific creators
$query = "SELECT distinct loginID, firstName, lastName
FROM Resource R, User U
WHERE U.loginID = R.createLoginID
ORDER BY lastName, firstName, loginID";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['loginID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($creatorsArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($creatorsArray, $resultArray);
}
}
return $creatorsArray;
}
//returns array of external login records
public function getExternalLoginArray(){
$config = new Configuration;
$elArray = array();
//get resource specific accounts first
$query = "SELECT EL.*, ELT.shortName externalLoginType
FROM ExternalLogin EL, ExternalLoginType ELT
WHERE EL.externalLoginTypeID = ELT.externalLoginTypeID
AND resourceID = '" . $this->resourceID . "'
ORDER BY ELT.shortName;";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['externalLoginID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($elArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($elArray, $resultArray);
}
}
//if the org module is installed also get the external logins from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$query = "SELECT DISTINCT EL.*, ELT.shortName externalLoginType, O.name organizationName
FROM " . $dbName . ".ExternalLogin EL, " . $dbName . ".ExternalLoginType ELT, " . $dbName . ".Organization O,
Resource R, ResourceOrganizationLink ROL
WHERE EL.externalLoginTypeID = ELT.externalLoginTypeID
AND R.resourceID = ROL.resourceID
AND ROL.organizationID = EL.organizationID
AND O.organizationID = EL.organizationID
AND R.resourceID = '" . $this->resourceID . "'
ORDER BY ELT.shortName;";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['externalLoginID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($elArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($elArray, $resultArray);
}
}
}
return $elArray;
}
//returns array of notes objects
public function getNotes($tabName = NULL){
if ($tabName){
$query = "SELECT * FROM ResourceNote RN
WHERE resourceID = '" . $this->resourceID . "'
AND UPPER(tabName) = UPPER('" . $tabName . "')
ORDER BY updateDate desc";
}else{
$query = "SELECT RN.*
FROM ResourceNote RN
LEFT JOIN NoteType NT ON NT.noteTypeID = RN.noteTypeID
WHERE resourceID = '" . $this->resourceID . "'
ORDER BY updateDate desc, NT.shortName";
}
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceNoteID'])){
$object = new ResourceNote(new NamedArguments(array('primaryKey' => $result['resourceNoteID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourceNote(new NamedArguments(array('primaryKey' => $row['resourceNoteID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of the initial note object
public function getInitialNote(){
$noteType = new NoteType();
$query = "SELECT * FROM ResourceNote RN
WHERE resourceID = '" . $this->resourceID . "'
AND noteTypeID = " . $noteType->getInitialNoteTypeID . "
ORDER BY noteTypeID desc LIMIT 0,1";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceNoteID'])){
$resourceNote = new ResourceNote(new NamedArguments(array('primaryKey' => $result['resourceNoteID'])));
return $resourceNote;
} else{
$resourceNote = new ResourceNote();
return $resourceNote;
}
}
public function getIssues($archivedOnly=false){
$query = "SELECT i.*
FROM Issue i
LEFT JOIN IssueRelationship ir ON ir.issueID=i.issueID
WHERE ir.entityID={$this->resourceID} AND ir.entityTypeID=2";
if ($archivedOnly) {
$query .= " AND i.dateClosed IS NOT NULL";
} else {
$query .= " AND i.dateClosed IS NULL";
}
$query .= " ORDER BY i.dateCreated DESC";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['issueID'])){
$object = new Issue(new NamedArguments(array('primaryKey' => $result['issueID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Issue(new NamedArguments(array('primaryKey' => $row['issueID'])));
array_push($objects, $object);
}
}
return $objects;
}
public function getDowntime($archivedOnly=false){
$query = "SELECT d.*
FROM Downtime d
WHERE d.entityID={$this->resourceID} AND d.entityTypeID=2";
if ($archivedOnly) {
$query .= " AND d.endDate < CURDATE()";
} else {
$query .= " AND (d.endDate >= CURDATE() OR d.endDate IS NULL)";
}
$query .= " ORDER BY d.dateCreated DESC";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['downtimeID'])){
$object = new Downtime(new NamedArguments(array('primaryKey' => $result['downtimeID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Downtime(new NamedArguments(array('primaryKey' => $row['downtimeID'])));
array_push($objects, $object);
}
}
return $objects;
}
public function getExportableIssues($archivedOnly=false){
if ($this->db->config->settings->organizationsModule == 'Y' && $this->db->config->settings->organizationsDatabaseName) {
$contactsDB = $this->db->config->settings->organizationsDatabaseName;
} else {
$contactsDB = $this->db->config->database->name;
}
$query = "SELECT i.*,(SELECT GROUP_CONCAT(CONCAT(sc.name,' - ',sc.emailAddress) SEPARATOR ', ')
FROM IssueContact sic
LEFT JOIN `{$contactsDB}`.Contact sc ON sc.contactID=sic.contactID
WHERE sic.issueID=i.issueID) AS `contacts`,
(SELECT GROUP_CONCAT(se.titleText SEPARATOR ', ')
FROM IssueRelationship sir
LEFT JOIN Resource se ON (se.resourceID=sir.entityID AND sir.entityTypeID=2)
WHERE sir.issueID=i.issueID) AS `appliesto`,
(SELECT GROUP_CONCAT(sie.email SEPARATOR ', ')
FROM IssueEmail sie
WHERE sie.issueID=i.issueID) AS `CCs`
FROM Issue i
LEFT JOIN IssueRelationship ir ON ir.issueID=i.issueID
WHERE ir.entityID={$this->resourceID} AND ir.entityTypeID=2";
if ($archivedOnly) {
$query .= " AND i.dateClosed IS NOT NULL";
} else {
$query .= " AND i.dateClosed IS NULL";
}
$query .= " ORDER BY i.dateCreated DESC";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['issueID'])){
return array($result);
}else{
return $result;
}
}
public function getExportableDowntimes($archivedOnly=false){
$query = "SELECT d.*
FROM Downtime d
WHERE d.entityID={$this->resourceID} AND d.entityTypeID=2";
if ($archivedOnly) {
$query .= " AND d.endDate < CURDATE()";
} else {
$query .= " AND d.endDate >= CURDATE()";
}
$query .= " ORDER BY d.dateCreated DESC";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['downtimeID'])){
return array($result);
}else{
return $result;
}
}
//returns array of attachments objects
public function getAttachments(){
$query = "SELECT * FROM Attachment A, AttachmentType AT
WHERE AT.attachmentTypeID = A.attachmentTypeID
AND resourceID = '" . $this->resourceID . "'
ORDER BY AT.shortName";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['attachmentID'])){
$object = new Attachment(new NamedArguments(array('primaryKey' => $result['attachmentID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Attachment(new NamedArguments(array('primaryKey' => $row['attachmentID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of contact objects
public function getContacts(){
$query = "SELECT * FROM Contact
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['contactID'])){
$object = new Contact(new NamedArguments(array('primaryKey' => $result['contactID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Contact(new NamedArguments(array('primaryKey' => $row['contactID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of externalLogin objects
public function getExternalLogins(){
$query = "SELECT * FROM ExternalLogin
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['externalLoginID'])){
$object = new ExternalLogin(new NamedArguments(array('primaryKey' => $result['externalLoginID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ExternalLogin(new NamedArguments(array('primaryKey' => $row['externalLoginID'])));
array_push($objects, $object);
}
}
return $objects;
}
public static function setSearch($search) {
$config = new Configuration;
if ($config->settings->defaultsort) {
$orderBy = $config->settings->defaultsort;
} else {
$orderBy = "R.createDate DESC, TRIM(LEADING 'THE ' FROM UPPER(R.titleText)) asc";
}
$defaultSearchParameters = array(
"orderBy" => $orderBy,
"page" => 1,
"recordsPerPage" => 25,
);
foreach ($defaultSearchParameters as $key => $value) {
if (!$search[$key]) {
$search[$key] = $value;
}
}
foreach ($search as $key => $value) {
$search[$key] = trim($value);
}
$_SESSION['resourceSearch'] = $search;
}
public static function resetSearch() {
Resource::setSearch(array());
}
public static function getSearch() {
if (!isset($_SESSION['resourceSearch'])) {
Resource::resetSearch();
}
return $_SESSION['resourceSearch'];
}
public static function getSearchDetails() {
// A successful mysqli_connect must be run before mysqli_real_escape_string will function. Instantiating a resource model will set up the connection
$resource = new Resource();
$search = Resource::getSearch();
$whereAdd = array();
$searchDisplay = array();
$config = new Configuration();
//if name is passed in also search alias, organizations and organization aliases
if ($search['name']) {
$nameQueryString = $resource->db->escapeString(strtoupper($search['name']));
$nameQueryString = preg_replace("/ +/", "%", $nameQueryString);
$nameQueryString = "'%" . $nameQueryString . "%'";
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$whereAdd[] = "((UPPER(R.titleText) LIKE " . $nameQueryString . ") OR (UPPER(A.shortName) LIKE " . $nameQueryString . ") OR (UPPER(O.name) LIKE " . $nameQueryString . ") OR (UPPER(OA.name) LIKE " . $nameQueryString . ") OR (UPPER(RP.titleText) LIKE " . $nameQueryString . ") OR (UPPER(RC.titleText) LIKE " . $nameQueryString . ") OR (UPPER(R.recordSetIdentifier) LIKE " . $nameQueryString . "))";
}else{
$whereAdd[] = "((UPPER(R.titleText) LIKE " . $nameQueryString . ") OR (UPPER(A.shortName) LIKE " . $nameQueryString . ") OR (UPPER(O.shortName) LIKE " . $nameQueryString . ") OR (UPPER(RP.titleText) LIKE " . $nameQueryString . ") OR (UPPER(RC.titleText) LIKE " . $nameQueryString . ") OR (UPPER(R.recordSetIdentifier) LIKE " . $nameQueryString . "))";
}
$searchDisplay[] = "Name contains: " . $search['name'];
}
//get where statements together (and escape single quotes)
if ($search['resourceID']) {
$whereAdd[] = "R.resourceID = '" . $resource->db->escapeString($search['resourceID']) . "'";
$searchDisplay[] = "Resource ID: " . $search['resourceID'];
}
if ($search['resourceISBNOrISSN']) {
$resourceISBNOrISSN = $resource->db->escapeString(str_replace("-","",$search['resourceISBNOrISSN']));
$whereAdd[] = "REPLACE(I.isbnOrIssn,'-','') = '" . $resourceISBNOrISSN . "'";
$searchDisplay[] = "ISSN/ISBN: " . $search['resourceISBNOrISSN'];
}
if ($search['fund']) {
$fund = $resource->db->escapeString(str_replace("-","",$search['fund']));
$whereAdd[] = "REPLACE(RPAY.fundName,'-','') = '" . $fund . "'";
$searchDisplay[] = "Fund: " . $search['fund'];
}
if ($search['stepName']) {
$status = new Status();
$completedStatusID = $status->getIDFromName('complete');
$whereAdd[] = "(R.statusID != $completedStatusID AND RS.stepName = '" . $resource->db->escapeString($search['stepName']) . "' AND RS.stepStartDate IS NOT NULL AND RS.stepEndDate IS NULL)";
$searchDisplay[] = "Routing Step: " . $search['stepName'];
}
if ($search['parent'] != null) {
$parentadd = "(" . $search['parent'] . ".relationshipTypeID = 1";
$parentadd .= ")";
$whereAdd[] = $parentadd;
}
if ($search['statusID']) {
$whereAdd[] = "R.statusID = '" . $resource->db->escapeString($search['statusID']) . "'";
$status = new Status(new NamedArguments(array('primaryKey' => $search['statusID'])));
$searchDisplay[] = "Status: " . $status->shortName;
}
if ($search['creatorLoginID']) {
$whereAdd[] = "R.createLoginID = '" . $resource->db->escapeString($search['creatorLoginID']) . "'";
$createUser = new User(new NamedArguments(array('primaryKey' => $search['creatorLoginID'])));
if ($createUser->firstName){
$name = $createUser->lastName . ", " . $createUser->firstName;
}else{
$name = $createUser->loginID;
}
$searchDisplay[] = "Creator: " . $name;
}
if ($search['resourceFormatID']) {
$whereAdd[] = "R.resourceFormatID = '" . $resource->db->escapeString($search['resourceFormatID']) . "'";
$resourceFormat = new ResourceFormat(new NamedArguments(array('primaryKey' => $search['resourceFormatID'])));
$searchDisplay[] = "Resource Format: " . $resourceFormat->shortName;
}
if ($search['acquisitionTypeID']) {
$whereAdd[] = "R.acquisitionTypeID = '" . $resource->db->escapeString($search['acquisitionTypeID']) . "'";
$acquisitionType = new AcquisitionType(new NamedArguments(array('primaryKey' => $search['acquisitionTypeID'])));
$searchDisplay[] = "Acquisition Type: " . $acquisitionType->shortName;
}
if ($search['resourceNote']) {
$whereAdd[] = "UPPER(RN.noteText) LIKE UPPER('%" . $resource->db->escapeString($search['resourceNote']) . "%')";
$searchDisplay[] = "Note contains: " . $search['resourceNote'];
}
if ($search['createDateStart']) {
$whereAdd[] = "R.createDate >= STR_TO_DATE('" . $resource->db->escapeString($search['createDateStart']) . "','%m/%d/%Y')";
if (!$search['createDateEnd']) {
$searchDisplay[] = "Created on or after: " . $search['createDateStart'];
} else {
$searchDisplay[] = "Created between: " . $search['createDateStart'] . " and " . $search['createDateEnd'];
}
}
if ($search['createDateEnd']) {
$whereAdd[] = "R.createDate <= STR_TO_DATE('" . $resource->db->escapeString($search['createDateEnd']) . "','%m/%d/%Y')";
if (!$search['createDateStart']) {
$searchDisplay[] = "Created on or before: " . $search['createDateEnd'];
}
}
if ($search['startWith']) {
$whereAdd[] = "TRIM(LEADING 'THE ' FROM UPPER(R.titleText)) LIKE UPPER('" . $resource->db->escapeString($search['startWith']) . "%')";
$searchDisplay[] = "Starts with: " . $search['startWith'];
}
//the following are not-required fields with dropdowns and have "none" as an option
if ($search['resourceTypeID'] == 'none'){
$whereAdd[] = "((R.resourceTypeID IS NULL) OR (R.resourceTypeID = '0'))";
$searchDisplay[] = "Resource Type: none";
}else if ($search['resourceTypeID']){
$whereAdd[] = "R.resourceTypeID = '" . $resource->db->escapeString($search['resourceTypeID']) . "'";
$resourceType = new ResourceType(new NamedArguments(array('primaryKey' => $search['resourceTypeID'])));
$searchDisplay[] = "Resource Type: " . $resourceType->shortName;
}
if ($search['generalSubjectID'] == 'none'){
$whereAdd[] = "((GDLINK.generalSubjectID IS NULL) OR (GDLINK.generalSubjectID = '0'))";
$searchDisplay[] = "Resource Type: none";
}else if ($search['generalSubjectID']){
$whereAdd[] = "GDLINK.generalSubjectID = '" . $resource->db->escapeString($search['generalSubjectID']) . "'";
$generalSubject = new GeneralSubject(new NamedArguments(array('primaryKey' => $search['generalSubjectID'])));
$searchDisplay[] = "General Subject: " . $generalSubject->shortName;
}
if ($search['detailedSubjectID'] == 'none'){
$whereAdd[] = "((GDLINK.detailedSubjectID IS NULL) OR (GDLINK.detailedSubjectID = '0') OR (GDLINK.detailedSubjectID = '-1'))";
$searchDisplay[] = "Resource Type: none";
}else if ($search['detailedSubjectID']){
$whereAdd[] = "GDLINK.detailedSubjectID = '" . $resource->db->escapeString($search['detailedSubjectID']) . "'";
$detailedSubject = new DetailedSubject(new NamedArguments(array('primaryKey' => $search['detailedSubjectID'])));
$searchDisplay[] = "Detailed Subject: " . $detailedSubject->shortName;
}
if ($search['noteTypeID'] == 'none'){
$whereAdd[] = "(RN.noteTypeID IS NULL) AND (RN.noteText IS NOT NULL)";
$searchDisplay[] = "Note Type: none";
}else if ($search['noteTypeID']){
$whereAdd[] = "RN.noteTypeID = '" . $resource->db->escapeString($search['noteTypeID']) . "'";
$noteType = new NoteType(new NamedArguments(array('primaryKey' => $search['noteTypeID'])));
$searchDisplay[] = "Note Type: " . $noteType->shortName;
}
if ($search['purchaseSiteID'] == 'none'){
$whereAdd[] = "RPSL.purchaseSiteID IS NULL";
$searchDisplay[] = "Purchase Site: none";
}else if ($search['purchaseSiteID']){
$whereAdd[] = "RPSL.purchaseSiteID = '" . $resource->db->escapeString($search['purchaseSiteID']) . "'";
$purchaseSite = new PurchaseSite(new NamedArguments(array('primaryKey' => $search['purchaseSiteID'])));
$searchDisplay[] = "Purchase Site: " . $purchaseSite->shortName;
}
if ($search['authorizedSiteID'] == 'none'){
$whereAdd[] = "RAUSL.authorizedSiteID IS NULL";
$searchDisplay[] = "Authorized Site: none";
}else if ($search['authorizedSiteID']){
$whereAdd[] = "RAUSL.authorizedSiteID = '" . $resource->db->escapeString($search['authorizedSiteID']) . "'";
$authorizedSite = new AuthorizedSite(new NamedArguments(array('primaryKey' => $search['authorizedSiteID'])));
$searchDisplay[] = "Authorized Site: " . $authorizedSite->shortName;
}
if ($search['administeringSiteID'] == 'none'){
$whereAdd[] = "RADSL.administeringSiteID IS NULL";
$searchDisplay[] = "Administering Site: none";
}else if ($search['administeringSiteID']){
$whereAdd[] = "RADSL.administeringSiteID = '" . $resource->db->escapeString($search['administeringSiteID']) . "'";
$administeringSite = new AdministeringSite(new NamedArguments(array('primaryKey' => $search['administeringSiteID'])));
$searchDisplay[] = "Administering Site: " . $administeringSite->shortName;
}
if ($search['authenticationTypeID'] == 'none'){
$whereAdd[] = "R.authenticationTypeID IS NULL";
$searchDisplay[] = "Authentication Type: none";
}else if ($search['authenticationTypeID']){
$whereAdd[] = "R.authenticationTypeID = '" . $resource->db->escapeString($search['authenticationTypeID']) . "'";
$authenticationType = new AuthenticationType(new NamedArguments(array('primaryKey' => $search['authenticationTypeID'])));
$searchDisplay[] = "Authentication Type: " . $authenticationType->shortName;
}
if ($search['catalogingStatusID'] == 'none') {
$whereAdd[] = "(R.catalogingStatusID IS NULL)";
$searchDisplay[] = "Cataloging Status: none";
} else if ($search['catalogingStatusID']) {
$whereAdd[] = "R.catalogingStatusID = '" . $resource->db->escapeString($search['catalogingStatusID']) . "'";
$catalogingStatus = new CatalogingStatus(new NamedArguments(array('primaryKey' => $search['catalogingStatusID'])));
$searchDisplay[] = "Cataloging Status: " . $catalogingStatus->shortName;
}
$orderBy = $search['orderBy'];
$page = $search['page'];
$recordsPerPage = $search['recordsPerPage'];
return array("where" => $whereAdd, "page" => $page, "order" => $orderBy, "perPage" => $recordsPerPage, "display" => $searchDisplay);
}
public function searchQuery($whereAdd, $orderBy = '', $limit = '', $count = false) {
$config = new Configuration();
$status = new Status();
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$orgJoinAdd = "LEFT JOIN " . $dbName . ".Organization O ON O.organizationID = ROL.organizationID
LEFT JOIN " . $dbName . ".Alias OA ON OA.organizationID = ROL.organizationID";
}else{
$orgJoinAdd = "LEFT JOIN Organization O ON O.organizationID = ROL.organizationID";
}
$savedStatusID = intval($status->getIDFromName('saved'));
//also add to not retrieve saved records
$whereAdd[] = "R.statusID != " . $savedStatusID;
if (count($whereAdd) > 0){
$whereStatement = " WHERE " . implode(" AND ", $whereAdd);
}else{
$whereStatement = "";
}
if ($count) {
$select = "SELECT COUNT(DISTINCT R.resourceID) count";
$groupBy = "";
} else {
$select = "SELECT R.resourceID, R.titleText, AT.shortName acquisitionType, R.createLoginID, CU.firstName, CU.lastName, R.createDate, S.shortName status,
GROUP_CONCAT(DISTINCT A.shortName, I.isbnOrIssn ORDER BY A.shortName DESC SEPARATOR '<br />') aliases";
$groupBy = "GROUP BY R.resourceID";
}
$referenced_tables = array();
$table_matches = array();
// Build a list of tables that are referenced by the select and where statements in order to limit the number of joins performed in the search.
preg_match_all("/[A-Z]+(?=[.][A-Z]+)/i", $select, $table_matches);
$referenced_tables = array_unique($table_matches[0]);
preg_match_all("/[A-Z]+(?=[.][A-Z]+)/i", $whereStatement, $table_matches);
$referenced_tables = array_unique(array_merge($referenced_tables, $table_matches[0]));
// These join statements will only be included in the query if the alias is referenced by the select and/or where.
$conditional_joins = explode("\n", "LEFT JOIN ResourceFormat RF ON R.resourceFormatID = RF.resourceFormatID
LEFT JOIN ResourceType RT ON R.resourceTypeID = RT.resourceTypeID
LEFT JOIN AcquisitionType AT ON R.acquisitionTypeID = AT.acquisitionTypeID
LEFT JOIN Status S ON R.statusID = S.statusID
LEFT JOIN User CU ON R.createLoginID = CU.loginID
LEFT JOIN ResourcePurchaseSiteLink RPSL ON R.resourceID = RPSL.resourceID
LEFT JOIN ResourceAuthorizedSiteLink RAUSL ON R.resourceID = RAUSL.resourceID
LEFT JOIN ResourceAdministeringSiteLink RADSL ON R.resourceID = RADSL.resourceID
LEFT JOIN ResourcePayment RPAY ON R.resourceID = RPAY.resourceID
LEFT JOIN ResourceNote RN ON R.resourceID = RN.resourceID
LEFT JOIN ResourceStep RS ON R.resourceID = RS.resourceID
LEFT JOIN IsbnOrIssn I ON R.resourceID = I.resourceID
");
$additional_joins = array();
foreach($conditional_joins as $join) {
$match = array();
preg_match("/[A-Z]+(?= ON )/i", $join, $match);
$table_name = $match[0];
if (in_array($table_name, $referenced_tables)) {
$additional_joins[] = $join;
}
}
$query = $select . "
FROM Resource R
LEFT JOIN Alias A ON R.resourceID = A.resourceID
LEFT JOIN ResourceOrganizationLink ROL ON R.resourceID = ROL.resourceID
" . $orgJoinAdd . "
LEFT JOIN ResourceRelationship RRC ON RRC.relatedResourceID = R.resourceID
LEFT JOIN ResourceRelationship RRP ON RRP.resourceID = R.resourceID
LEFT JOIN ResourceSubject RSUB ON R.resourceID = RSUB.resourceID
LEFT JOIN Resource RC ON RC.resourceID = RRC.resourceID
LEFT JOIN Resource RP ON RP.resourceID = RRP.relatedResourceID
LEFT JOIN GeneralDetailSubjectLink GDLINK ON RSUB.generalDetailSubjectLinkID = GDLINK.generalDetailSubjectLinkID
" . implode("\n", $additional_joins) . "
" . $whereStatement . "
" . $groupBy;
if ($orderBy) {
$query .= "\nORDER BY " . $orderBy;
}
if ($limit) {
$query .= "\nLIMIT " . $limit;
}
return $query;
}
//returns array based on search
public function search($whereAdd, $orderBy, $limit){
$query = $this->searchQuery($whereAdd, $orderBy, $limit, false);
$result = $this->db->processQuery($query, 'assoc');
$searchArray = array();
$resultArray = array();
//need to do this since it could be that there's only one result and this is how the dbservice returns result
if (isset($result['resourceID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($searchArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($searchArray, $resultArray);
}
}
return $searchArray;
}
public function searchCount($whereAdd) {
$query = $this->searchQuery($whereAdd, '', '', true);
$result = $this->db->processQuery($query, 'assoc');
//echo $query;
return $result['count'];
}
//used for A-Z on search (index)
public function getAlphabeticalList(){
$alphArray = array();
$result = $this->db->query("SELECT DISTINCT UPPER(SUBSTR(TRIM(LEADING 'The ' FROM titleText),1,1)) letter, COUNT(SUBSTR(TRIM(LEADING 'The ' FROM titleText),1,1)) letter_count
FROM Resource R
GROUP BY SUBSTR(TRIM(LEADING 'The ' FROM titleText),1,1)
ORDER BY 1;");
while ($row = $result->fetch_assoc()){
$alphArray[$row['letter']] = $row['letter_count'];
}
return $alphArray;
}
//returns array based on search for excel output (export.php)
public function export($whereAdd, $orderBy){
$config = new Configuration();
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$orgJoinAdd = "LEFT JOIN " . $dbName . ".Organization O ON O.organizationID = ROL.organizationID
LEFT JOIN " . $dbName . ".Alias OA ON OA.organizationID = ROL.organizationID";
$orgSelectAdd = "GROUP_CONCAT(DISTINCT O.name ORDER BY O.name DESC SEPARATOR '; ') organizationNames";
}else{
$orgJoinAdd = "LEFT JOIN Organization O ON O.organizationID = ROL.organizationID";
$orgSelectAdd = "GROUP_CONCAT(DISTINCT O.shortName ORDER BY O.shortName DESC SEPARATOR '; ') organizationNames";
}
$licSelectAdd = '';
$licJoinAdd = '';
if ($config->settings->licensingModule == 'Y'){
$dbName = $config->settings->licensingDatabaseName;
$licJoinAdd = " LEFT JOIN ResourceLicenseLink RLL ON RLL.resourceID = R.resourceID
LEFT JOIN " . $dbName . ".License L ON RLL.licenseID = L.licenseID
LEFT JOIN ResourceLicenseStatus RLS ON RLS.resourceID = R.resourceID
LEFT JOIN LicenseStatus LS ON LS.licenseStatusID = RLS.licenseStatusID";
$licSelectAdd = "GROUP_CONCAT(DISTINCT L.shortName ORDER BY L.shortName DESC SEPARATOR '; ') licenseNames,
GROUP_CONCAT(DISTINCT LS.shortName, ': ', DATE_FORMAT(RLS.licenseStatusChangeDate, '%m/%d/%Y') ORDER BY RLS.licenseStatusChangeDate DESC SEPARATOR '; ') licenseStatuses, ";
}
$status = new Status();
//also add to not retrieve saved records
$savedStatusID = intval($status->getIDFromName('saved'));
$whereAdd[] = "R.statusID != " . $savedStatusID;
if (count($whereAdd) > 0){
$whereStatement = " WHERE " . implode(" AND ", $whereAdd);
}else{
$whereStatement = "";
}
//now actually execute query
$query = "SELECT R.resourceID, R.titleText, AT.shortName acquisitionType, CONCAT_WS(' ', CU.firstName, CU.lastName) createName,
R.createDate createDate, CONCAT_WS(' ', UU.firstName, UU.lastName) updateName,
R.updateDate updateDate, S.shortName status,
RT.shortName resourceType, RF.shortName resourceFormat, R.orderNumber, R.systemNumber, R.resourceURL, R.resourceAltURL,
R.currentStartDate, R.currentEndDate, R.subscriptionAlertEnabledInd, AUT.shortName authenticationType,
AM.shortName accessMethod, SL.shortName storageLocation, UL.shortName userLimit, R.authenticationUserName,
R.authenticationPassword, R.coverageText, CT.shortName catalogingType, CS.shortName catalogingStatus, R.recordSetIdentifier, R.bibSourceURL,
R.numberRecordsAvailable, R.numberRecordsLoaded, R.hasOclcHoldings, I.isbnOrIssn,
" . $orgSelectAdd . ",
" . $licSelectAdd . "
GROUP_CONCAT(DISTINCT A.shortName ORDER BY A.shortName DESC SEPARATOR '; ') aliases,
GROUP_CONCAT(DISTINCT PS.shortName ORDER BY PS.shortName DESC SEPARATOR '; ') purchasingSites,
GROUP_CONCAT(DISTINCT AUS.shortName ORDER BY AUS.shortName DESC SEPARATOR '; ') authorizedSites,
GROUP_CONCAT(DISTINCT ADS.shortName ORDER BY ADS.shortName DESC SEPARATOR '; ') administeringSites,
GROUP_CONCAT(DISTINCT RP.titleText ORDER BY RP.titleText DESC SEPARATOR '; ') parentResources,
GROUP_CONCAT(DISTINCT RC.titleText ORDER BY RC.titleText DESC SEPARATOR '; ') childResources,
GROUP_CONCAT(DISTINCT RPAY.fundName, ': ', ROUND(COALESCE(RPAY.paymentAmount, 0) / 100, 2), ' ', RPAY.currencyCode, ' ', OT.shortName ORDER BY RPAY.paymentAmount ASC SEPARATOR '; ') payments
FROM Resource R
LEFT JOIN Alias A ON R.resourceID = A.resourceID
LEFT JOIN ResourceOrganizationLink ROL ON R.resourceID = ROL.resourceID
" . $orgJoinAdd . "
LEFT JOIN ResourceRelationship RRC ON RRC.relatedResourceID = R.resourceID
LEFT JOIN ResourceRelationship RRP ON RRP.resourceID = R.resourceID
LEFT JOIN Resource RC ON RC.resourceID = RRC.resourceID
LEFT JOIN ResourceSubject RSUB ON R.resourceID = RSUB.resourceID
LEFT JOIN Resource RP ON RP.resourceID = RRP.relatedResourceID
LEFT JOIN GeneralDetailSubjectLink GDLINK ON RSUB.generalDetailSubjectLinkID = GDLINK.generalDetailSubjectLinkID
LEFT JOIN ResourceFormat RF ON R.resourceFormatID = RF.resourceFormatID
LEFT JOIN ResourceType RT ON R.resourceTypeID = RT.resourceTypeID
LEFT JOIN AcquisitionType AT ON R.acquisitionTypeID = AT.acquisitionTypeID
LEFT JOIN ResourceStep RS ON R.resourceID = RS.resourceID
LEFT JOIN ResourcePayment RPAY ON R.resourceID = RPAY.resourceID
LEFT JOIN OrderType OT ON RPAY.orderTypeID = OT.orderTypeID
LEFT JOIN Status S ON R.statusID = S.statusID
LEFT JOIN ResourceNote RN ON R.resourceID = RN.resourceID
LEFT JOIN NoteType NT ON RN.noteTypeID = NT.noteTypeID
LEFT JOIN User CU ON R.createLoginID = CU.loginID
LEFT JOIN User UU ON R.updateLoginID = UU.loginID
LEFT JOIN CatalogingStatus CS ON R.catalogingStatusID = CS.catalogingStatusID
LEFT JOIN CatalogingType CT ON R.catalogingTypeID = CT.catalogingTypeID
LEFT JOIN ResourcePurchaseSiteLink RPSL ON R.resourceID = RPSL.resourceID
LEFT JOIN PurchaseSite PS ON RPSL.purchaseSiteID = PS.purchaseSiteID
LEFT JOIN ResourceAuthorizedSiteLink RAUSL ON R.resourceID = RAUSL.resourceID
LEFT JOIN AuthorizedSite AUS ON RAUSL.authorizedSiteID = AUS.authorizedSiteID
LEFT JOIN ResourceAdministeringSiteLink RADSL ON R.resourceID = RADSL.resourceID
LEFT JOIN AdministeringSite ADS ON RADSL.administeringSiteID = ADS.administeringSiteID
LEFT JOIN AuthenticationType AUT ON AUT.authenticationTypeID = R.authenticationTypeID
LEFT JOIN AccessMethod AM ON AM.accessMethodID = R.accessMethodID
LEFT JOIN StorageLocation SL ON SL.storageLocationID = R.storageLocationID
LEFT JOIN UserLimit UL ON UL.userLimitID = R.userLimitID
LEFT JOIN IsbnOrIssn I ON I.resourceID = R.resourceID
" . $licJoinAdd . "
" . $whereStatement . "
GROUP BY R.resourceID
ORDER BY " . $orderBy;
$result = $this->db->processQuery(stripslashes($query), 'assoc');
$searchArray = array();
$resultArray = array();
//need to do this since it could be that there's only one result and this is how the dbservice returns result
if (isset($result['resourceID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($searchArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($searchArray, $resultArray);
}
}
return $searchArray;
}
//search used index page drop down
public function getOrganizationList(){
$config = new Configuration;
$orgArray = array();
//if the org module is installed get the org names from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$query = "SELECT name, organizationID FROM " . $dbName . ".Organization ORDER BY 1;";
//otherwise get the orgs from this database
}else{
$query = "SELECT shortName name, organizationID FROM Organization ORDER BY 1;";
}
$result = $this->db->processQuery($query, 'assoc');
$resultArray = array();
//need to do this since it could be that there's only one result and this is how the dbservice returns result
if (isset($result['organizationID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($orgArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($orgArray, $resultArray);
}
}
return $orgArray;
}
//gets an array of organizations set up for this resource (organizationID, organization, organizationRole)
public function getOrganizationArray(){
$config = new Configuration;
//if the org module is installed get the org name from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$resourceOrgArray = array();
$query = "SELECT * FROM ResourceOrganizationLink WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['organizationID'])){
$orgArray = array();
//first, get the organization name
$query = "SELECT name FROM " . $dbName . ".Organization WHERE organizationID = " . $result['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['name'];
$orgArray['organizationID'] = $result['organizationID'];
}
}
//then, get the role name
$query = "SELECT * FROM " . $dbName . ".OrganizationRole WHERE organizationRoleID = " . $result['organizationRoleID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organizationRoleID'] = $orgRow['organizationRoleID'];
$orgArray['organizationRole'] = $orgRow['shortName'];
}
}
array_push($resourceOrgArray, $orgArray);
}else{
foreach ($result as $row) {
$orgArray = array();
//first, get the organization name
$query = "SELECT name FROM " . $dbName . ".Organization WHERE organizationID = " . $row['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['name'];
$orgArray['organizationID'] = $row['organizationID'];
}
}
//then, get the role name
$query = "SELECT * FROM " . $dbName . ".OrganizationRole WHERE organizationRoleID = " . $row['organizationRoleID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organizationRoleID'] = $orgRow['organizationRoleID'];
$orgArray['organizationRole'] = $orgRow['shortName'];
}
}
array_push($resourceOrgArray, $orgArray);
}
}
//otherwise if the org module is not installed get the org name from this database
}else{
$resourceOrgArray = array();
$query = "SELECT * FROM ResourceOrganizationLink WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['organizationID'])){
$orgArray = array();
//first, get the organization name
$query = "SELECT shortName FROM Organization WHERE organizationID = " . $result['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['shortName'];
$orgArray['organizationID'] = $result['organizationID'];
}
}
//then, get the role name
$query = "SELECT * FROM OrganizationRole WHERE organizationRoleID = " . $result['organizationRoleID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organizationRoleID'] = $orgRow['organizationRoleID'];
$orgArray['organizationRole'] = $orgRow['shortName'];
}
}
array_push($resourceOrgArray, $orgArray);
}else{
foreach ($result as $row) {
$orgArray = array();
//first, get the organization name
$query = "SELECT shortName FROM Organization WHERE organizationID = " . $row['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['shortName'];
$orgArray['organizationID'] = $row['organizationID'];
}
}
//then, get the role name
$query = "SELECT * FROM OrganizationRole WHERE organizationRoleID = " . $row['organizationRoleID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organizationRoleID'] = $orgRow['organizationRoleID'];
$orgArray['organizationRole'] = $orgRow['shortName'];
}
}
array_push($resourceOrgArray, $orgArray);
}
}
}
return $resourceOrgArray;
}
public function getSiblingResourcesArray($organizationID) {
$query = "SELECT DISTINCT r.resourceID, r.titleText FROM ResourceOrganizationLink rol
LEFT JOIN Resource r ON r.resourceID=rol.resourceID
WHERE rol.organizationID=".$organizationID." AND r.archiveDate IS NULL
ORDER BY r.titleText";
$result = $this->db->processQuery($query, 'assoc');
if($result["resourceID"]) {
return array($result);
}
return $result;
}
//gets an array of distinct organizations set up for this resource (organizationID, organization)
public function getDistinctOrganizationArray(){
$config = new Configuration;
//if the org module is installed get the org name from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$resourceOrgArray = array();
$query = "SELECT DISTINCT organizationID FROM ResourceOrganizationLink WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['organizationID'])){
$orgArray = array();
//first, get the organization name
$query = "SELECT name FROM " . $dbName . ".Organization WHERE organizationID = " . $result['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['name'];
$orgArray['organizationID'] = $result['organizationID'];
}
}
array_push($resourceOrgArray, $orgArray);
}else{
foreach ($result as $row) {
$orgArray = array();
//first, get the organization name
$query = "SELECT DISTINCT name FROM " . $dbName . ".Organization WHERE organizationID = " . $row['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['name'];
$orgArray['organizationID'] = $row['organizationID'];
}
}
array_push($resourceOrgArray, $orgArray);
}
}
//otherwise if the org module is not installed get the org name from this database
}else{
$resourceOrgArray = array();
$query = "SELECT DISTINCT organizationID FROM ResourceOrganizationLink WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['organizationID'])){
$orgArray = array();
//first, get the organization name
$query = "SELECT DISTINCT shortName FROM Organization WHERE organizationID = " . $result['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['shortName'];
$orgArray['organizationID'] = $result['organizationID'];
}
}
array_push($resourceOrgArray, $orgArray);
}else{
foreach ($result as $row) {
$orgArray = array();
//first, get the organization name
$query = "SELECT DISTINCT shortName FROM Organization WHERE organizationID = " . $row['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['shortName'];
$orgArray['organizationID'] = $row['organizationID'];
}
}
array_push($resourceOrgArray, $orgArray);
}
}
}
return $resourceOrgArray;
}
public function hasCatalogingInformation() {
return ($this->recordSetIdentifier || $this->recordSetIdentifier || $this->bibSourceURL || $this->catalogingTypeID || $this->catalogingStatusID || $this->numberRecordsAvailable || $this->numberRecordsLoaded || $this->hasOclcHoldings);
}
//removes this resource and its children
public function removeResourceAndChildren(){
// for each children
foreach ($this->getChildResources() as $instance) {
$removeChild = true;
$child = new Resource(new NamedArguments(array('primaryKey' => $instance->resourceID)));
// get parents of this children
$parents = $child->getParentResources();
// If the child ressource belongs to another parent than the one we're removing
foreach ($parents as $pinstance) {
$parentResourceObj = new Resource(new NamedArguments(array('primaryKey' => $pinstance->relatedResourceID)));
if ($parentResourceObj->resourceID != $this->resourceID) {
// We do not delete this child.
$removeChild = false;
}
}
if ($removeChild == true) {
$child->removeResource();
}
}
// Finally, we remove the parent
$this->removeResource();
}
//removes this resource
public function removeResource(){
//delete data from child linked tables
$this->removeResourceRelationships();
$this->removePurchaseSites();
$this->removeAuthorizedSites();
$this->removeAdministeringSites();
$this->removeResourceLicenses();
$this->removeResourceLicenseStatuses();
$this->removeResourceOrganizations();
$this->removeResourcePayments();
$this->removeAllSubjects();
$this->removeAllIsbnOrIssn();
$instance = new Contact();
foreach ($this->getContacts() as $instance) {
$instance->removeContactRoles();
$instance->delete();
}
$instance = new ExternalLogin();
foreach ($this->getExternalLogins() as $instance) {
$instance->delete();
}
$instance = new ResourceNote();
foreach ($this->getNotes() as $instance) {
$instance->delete();
}
$instance = new Attachment();
foreach ($this->getAttachments() as $instance) {
$instance->delete();
}
$instance = new Alias();
foreach ($this->getAliases() as $instance) {
$instance->delete();
}
$this->delete();
}
//removes resource hierarchy records
public function removeResourceRelationships(){
$query = "DELETE
FROM ResourceRelationship
WHERE resourceID = '" . $this->resourceID . "' OR relatedResourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource purchase sites
public function removePurchaseSites(){
$query = "DELETE
FROM ResourcePurchaseSiteLink
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource authorized sites
public function removeAuthorizedSites(){
$query = "DELETE
FROM ResourceAuthorizedSiteLink
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource administering sites
public function removeAdministeringSites(){
$query = "DELETE
FROM ResourceAdministeringSiteLink
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes payment records
public function removeResourcePayments(){
$query = "DELETE
FROM ResourcePayment
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource licenses
public function removeResourceLicenses(){
$query = "DELETE
FROM ResourceLicenseLink
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource license statuses
public function removeResourceLicenseStatuses(){
$query = "DELETE
FROM ResourceLicenseStatus
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource organizations
public function removeResourceOrganizations(){
$query = "DELETE
FROM ResourceOrganizationLink
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource note records
public function removeResourceNotes(){
$query = "DELETE
FROM ResourceNote
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource steps
public function removeResourceSteps(){
$query = "DELETE
FROM ResourceStep
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//search used for the resource autocomplete
public function resourceAutocomplete($q){
$resourceArray = array();
$result = $this->db->query("SELECT titleText, resourceID
FROM Resource
WHERE upper(titleText) like upper('%" . $q . "%')
ORDER BY 1;");
while ($row = $result->fetch_assoc()){
$resourceArray[] = $row['titleText'] . "|" . $row['resourceID'];
}
return $resourceArray;
}
//search used for the organization autocomplete
public function organizationAutocomplete($q){
$config = new Configuration;
$organizationArray = array();
//if the org module is installed get the org name from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$result = $this->db->query("SELECT CONCAT(A.name, ' (', O.name, ')') shortName, O.organizationID
FROM " . $dbName . ".Alias A, " . $dbName . ".Organization O
WHERE A.organizationID=O.organizationID
AND upper(A.name) like upper('%" . $q . "%')
UNION
SELECT name shortName, organizationID
FROM " . $dbName . ".Organization
WHERE upper(name) like upper('%" . $q . "%')
ORDER BY 1;");
}else{
$result = $this->db->query("SELECT organizationID, shortName
FROM Organization O
WHERE upper(O.shortName) like upper('%" . $q . "%')
ORDER BY shortName;");
}
while ($row = $result->fetch_assoc()){
$organizationArray[] = $row['shortName'] . "|" . $row['organizationID'];
}
return $organizationArray;
}
//search used for the license autocomplete
public function licenseAutocomplete($q){
$config = new Configuration;
$licenseArray = array();
//if the org module is installed get the org name from org database
if ($config->settings->licensingModule == 'Y'){
$dbName = $config->settings->licensingDatabaseName;
$result = $this->db->query("SELECT shortName, licenseID
FROM " . $dbName . ".License
WHERE upper(shortName) like upper('%" . $q . "%')
ORDER BY 1;");
}
while ($row = $result->fetch_assoc()){
$licenseArray[] = $row['shortName'] . "|" . $row['licenseID'];
}
return $licenseArray;
}
///////////////////////////////////////////////////////////////////////////////////
//
// Workflow functions follow
//
///////////////////////////////////////////////////////////////////////////////////
//returns array of ResourceStep objects for this Resource
public function getResourceSteps(){
$query = "SELECT * FROM ResourceStep
WHERE resourceID = '" . $this->resourceID . "'
ORDER BY displayOrderSequence, stepID";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceStepID'])){
$object = new ResourceStep(new NamedArguments(array('primaryKey' => $result['resourceStepID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourceStep(new NamedArguments(array('primaryKey' => $row['resourceStepID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns current step location in the workflow for this resource
//used to display the group on the tabs
public function getCurrentStepGroup(){
$query = "SELECT groupName FROM ResourceStep RS, UserGroup UG
WHERE resourceID = '" . $this->resourceID . "'
ORDER BY stepID";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceStepID'])){
}
}
//returns first steps (object) in the workflow for this resource
public function getFirstSteps(){
$query = "SELECT * FROM ResourceStep
WHERE resourceID = '" . $this->resourceID . "'
AND (priorStepID is null OR priorStepID = '0')
ORDER BY stepID";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceStepID'])){
$object = new ResourceStep(new NamedArguments(array('primaryKey' => $result['resourceStepID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourceStep(new NamedArguments(array('primaryKey' => $row['resourceStepID'])));
array_push($objects, $object);
}
}
return $objects;
}
//enters resource into new workflow
public function enterNewWorkflow(){
$config = new Configuration();
//remove any current workflow steps
$this->removeResourceSteps();
//make sure this resource is marked in progress in case it was archived
$status = new Status();
$this->statusID = $status->getIDFromName('progress');
$this->save();
//Determine the workflow this resource belongs to
$workflowObj = new Workflow();
$workflowID = $workflowObj->getWorkflowID($this->resourceTypeID, $this->resourceFormatID, $this->acquisitionTypeID);
if ($workflowID){
$workflow = new Workflow(new NamedArguments(array('primaryKey' => $workflowID)));
//Copy all of the step attributes for this workflow to a new resource step
foreach ($workflow->getSteps() as $step){
$resourceStep = new ResourceStep();
$resourceStep->resourceStepID = '';
$resourceStep->resourceID = $this->resourceID;
$resourceStep->stepID = $step->stepID;
$resourceStep->priorStepID = $step->priorStepID;
$resourceStep->stepName = $step->stepName;
$resourceStep->userGroupID = $step->userGroupID;
$resourceStep->displayOrderSequence = $step->displayOrderSequence;
$resourceStep->save();
}
//Start the first step
//this handles updating the db and sending notifications for approval groups
foreach ($this->getFirstSteps() as $resourceStep){
$resourceStep->startStep();
}
}
//send an email notification to the feedback email address and the creator
$cUser = new User(new NamedArguments(array('primaryKey' => $this->createLoginID)));
$acquisitionType = new AcquisitionType(new NamedArguments(array('primaryKey' => $this->acquisitionTypeID)));
if ($cUser->firstName){
$creator = $cUser->firstName . " " . $cUser->lastName;
}else if ($this->createLoginID){ //for some reason user isn't set up or their firstname/last name don't exist
$creator = $this->createLoginID;
}else{
$creator = "(unknown user)";
}
if (($config->settings->feedbackEmailAddress) || ($cUser->emailAddress)){
$email = new Email();
$util = new Utility();
$email->message = $util->createMessageFromTemplate('NewResourceMain', $this->resourceID, $this->titleText, '', '', $creator);
if ($cUser->emailAddress){
$emailTo[] = $cUser->emailAddress;
}
if ($config->settings->feedbackEmailAddress != ''){
$emailTo[] = $config->settings->feedbackEmailAddress;
}
$email->to = implode(",", $emailTo);
if ($acquisitionType->shortName){
$email->subject = "CORAL Alert: New " . $acquisitionType->shortName . " Resource Added: " . $this->titleText;
}else{
$email->subject = "CORAL Alert: New Resource Added: " . $this->titleText;
}
$email->send();
}
}
//completes a workflow (changes status to complete and sends notifications to creator and "master email")
public function completeWorkflow(){
$config = new Configuration();
$util = new Utility();
$status = new Status();
$statusID = $status->getIDFromName('complete');
if ($statusID){
$this->statusID = $statusID;
$this->save();
}
//send notification to creator and master email address
$cUser = new User(new NamedArguments(array('primaryKey' => $this->createLoginID)));
//formulate emil to be sent
$email = new Email();
$email->message = $util->createMessageFromTemplate('CompleteResource', $this->resourceID, $this->titleText, '', $this->systemNumber, '');
if ($cUser->emailAddress){
$emailTo[] = $cUser->emailAddress;
}
if ($config->settings->feedbackEmailAddress != ''){
$emailTo[] = $config->settings->feedbackEmailAddress;
}
$email->to = implode(",", $emailTo);
$email->subject = "CORAL Alert: Workflow completion for " . $this->titleText;
$email->send();
}
//returns array of subject objects
public function getGeneralDetailSubjectLinkID(){
$query = "SELECT
GDL.generalDetailSubjectLinkID
FROM
Resource R
INNER JOIN ResourceSubject RSUB ON (R.resourceID = RSUB.resourceID)
INNER JOIN GeneralDetailSubjectLink GDL ON (RSUB.generalDetailSubjectLinkID = GDL.generalDetailSubjectLinkID)
LEFT OUTER JOIN GeneralSubject GS ON (GDL.generalSubjectID = GS.generalSubjectID)
LEFT OUTER JOIN DetailedSubject DS ON (GDL.detailedSubjectID = DS.detailedSubjectID)
WHERE
R.resourceID = '" . $this->resourceID . "'
ORDER BY
GS.shortName,
DS.shortName";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['generalDetailSubjectLinkID'])){
$object = new GeneralDetailSubjectLink(new NamedArguments(array('primaryKey' => $result['generalDetailSubjectLinkID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new GeneralDetailSubjectLink(new NamedArguments(array('primaryKey' => $row['generalDetailSubjectLinkID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of subject objects
public function getDetailedSubjects($resourceID, $generalSubjectID){
$query = "SELECT
RSUB.resourceID,
GDL.detailedSubjectID,
DetailedSubject.shortName,
GDL.generalSubjectID
FROM
ResourceSubject RSUB
INNER JOIN GeneralDetailSubjectLink GDL ON (RSUB.GeneralDetailSubjectLinkID = GDL.GeneralDetailSubjectLinkID)
INNER JOIN DetailedSubject ON (GDL.detailedSubjectID = DetailedSubject.detailedSubjectID)
WHERE
RSUB.resourceID = " . $resourceID . " AND GDL.generalSubjectID = " . $generalSubjectID . " ORDER BY DetailedSubject.shortName";
//echo $query . "<br>";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['detailedSubjectID'])){
$object = new DetailedSubject(new NamedArguments(array('primaryKey' => $result['detailedSubjectID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new DetailedSubject(new NamedArguments(array('primaryKey' => $row['detailedSubjectID'])));
array_push($objects, $object);
}
}
return $objects;
}
//removes all resource subjects
public function removeAllSubjects(){
$query = "DELETE
FROM ResourceSubject
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
public function removeAllIsbnOrIssn() {
$query = "DELETE
FROM IsbnOrIssn
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
public function setIsbnOrIssn($isbnorissns) {
$this->removeAllIsbnOrIssn();
foreach ($isbnorissns as $isbnorissn) {
if (trim($isbnorissn) != '') {
$isbnOrIssn = new IsbnOrIssn();
$isbnOrIssn->resourceID = $this->resourceID;
$isbnOrIssn->isbnOrIssn = $isbnorissn;
$isbnOrIssn->save();
}
}
}
}
?>
| TAMULib/CORAL-Resources | admin/classes/domain/Resource.php | PHP | gpl-3.0 | 79,589 |
/*
* Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
* Circulation and User's Management. It's written in Perl, and uses Apache2
* Web-Server, MySQL database and Sphinx 2 indexing.
* Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
*
* This file is part of Meran.
*
* Meran 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.
*
* Meran 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 Meran. If not, see <http://www.gnu.org/licenses/>.
*/
define([],function(){
'use strict'
/**
* Implements unique() using the browser's sort().
*
* @param a
* The array to sort and strip of duplicate values.
* Warning: this array will be modified in-place.
* @param compFn
* A custom comparison function that accepts two values a and
* b from the given array and returns -1, 0, 1 depending on
* whether a < b, a == b, a > b respectively.
*
* If no compFn is provided, the algorithm will use the
* browsers default sort behaviour and loose comparison to
* detect duplicates.
* @return
* The given array.
*/
function sortUnique(a, compFn){
var i;
if (compFn) {
a.sort(compFn);
for (i = 1; i < a.length; i++) {
if (0 === compFn(a[i], a[i - 1])) {
a.splice(i--, 1);
}
}
} else {
a.sort();
for (i = 1; i < a.length; i++) {
// Use loosely typed comparsion if no compFn is given
// to avoid sortUnique( [6, "6", 6] ) => [6, "6", 6]
if (a[i] == a[i - 1]) {
a.splice(i--, 1);
}
}
}
return a;
}
/**
* Shallow comparison of two arrays.
*
* @param a, b
* The arrays to compare.
* @param equalFn
* A custom comparison function that accepts two values a and
* b from the given arrays and returns true or false for
* equal and not equal respectively.
*
* If no equalFn is provided, the algorithm will use the strict
* equals operator.
* @return
* True if all items in a and b are equal, false if not.
*/
function equal(a, b, equalFn) {
var i = 0, len = a.length;
if (len !== b.length) {
return false;
}
if (equalFn) {
for (; i < len; i++) {
if (!equalFn(a[i], b[i])) {
return false;
}
}
} else {
for (; i < len; i++) {
if (a[i] !== b[i]) {
return false;
}
}
}
return true;
}
/**
* ECMAScript map replacement
* See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map
* And http://es5.github.com/#x15.4.4.19
* It's not exactly according to standard, but it does exactly what one expects.
*/
function map(a, fn) {
var i, len, result = [];
for (i = 0, len = a.length; i < len; i++) {
result.push(fn(a[i]));
}
return result;
}
function mapNative(a, fn) {
// Call map directly on the object instead of going through
// Array.prototype.map. This avoids the problem that we may get
// passed an array-like object (NodeList) which may cause an
// error if the implementation of Array.prototype.map can only
// deal with arrays (Array.prototype.map may be native or
// provided by a javscript framework).
return a.map(fn);
}
return {
sortUnique: sortUnique,
equal: equal,
map: Array.prototype.map ? mapNative : map
};
});
| Desarrollo-CeSPI/meran | includes/aloha/util/arrays.js | JavaScript | gpl-3.0 | 3,812 |
// Copyright 2017 Jon Skeet. All rights reserved. Use of this source code is governed by the Apache License 2.0, as found in the LICENSE.txt file.
using System;
namespace NullConditional
{
class LoggingDemo
{
static void Main()
{
int x = 10;
Logger logger = new Logger();
logger.Debug?.Log($"Debug log entry");
logger.Info?.Log($"Info at {DateTime.UtcNow}; x={x}");
}
}
}
| krazymirk/cs7 | CS7/CS7/NullConditional/LoggingDemo.cs | C# | gpl-3.0 | 460 |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssociationContains.cs" company="Allors bvba">
// Copyright 2002-2017 Allors bvba.
//
// Dual Licensed under
// a) the Lesser General Public Licence v3 (LGPL)
// b) the Allors License
//
// The LGPL License is included in the file lgpl.txt.
// The Allors License is an addendum to your contract.
//
// Allors Platform 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.
//
// For more information visit http://www.allors.com/legal
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Allors.Adapters.Object.SqlClient
{
using Allors.Meta;
using Adapters;
internal sealed class AssociationContains : Predicate
{
private readonly IObject allorsObject;
private readonly IAssociationType association;
internal AssociationContains(ExtentFiltered extent, IAssociationType association, IObject allorsObject)
{
extent.CheckAssociation(association);
PredicateAssertions.AssertAssociationContains(association, allorsObject);
this.association = association;
this.allorsObject = allorsObject;
}
internal override bool BuildWhere(ExtentStatement statement, string alias)
{
var schema = statement.Mapping;
if ((this.association.IsMany && this.association.RoleType.IsMany) || !this.association.RelationType.ExistExclusiveClasses)
{
statement.Append("\n");
statement.Append("EXISTS(\n");
statement.Append("SELECT " + alias + "." + Mapping.ColumnNameForObject + "\n");
statement.Append("FROM " + schema.TableNameForRelationByRelationType[this.association.RelationType] + "\n");
statement.Append("WHERE " + Mapping.ColumnNameForAssociation + "=" + this.allorsObject.Strategy.ObjectId + "\n");
statement.Append("AND " + Mapping.ColumnNameForRole + "=" + alias + "." + Mapping.ColumnNameForObject + "\n");
statement.Append(")");
}
else
{
statement.Append(" " + this.association.SingularFullName + "_A." + Mapping.ColumnNameForObject + " = " + this.allorsObject.Strategy.ObjectId);
}
return this.Include;
}
internal override void Setup(ExtentStatement statement)
{
statement.UseAssociation(this.association);
}
}
} | Allors/allors | Platform/Database/Adapters/Allors.Adapters.Object.SqlClient/Predicates/AssociationContains.cs | C# | gpl-3.0 | 2,811 |
using System;
using System.Web;
using System.Web.Mvc;
using SmartStore.Core;
using SmartStore.Core.Domain.Catalog;
using SmartStore.Core.Domain.Customers;
using SmartStore.Core.Domain.Media;
using SmartStore.Core.Html;
using SmartStore.Services.Catalog;
using SmartStore.Services.Media;
using SmartStore.Services.Orders;
using SmartStore.Web.Framework.Controllers;
namespace SmartStore.Web.Controllers
{
public partial class DownloadController : PublicControllerBase
{
private readonly IDownloadService _downloadService;
private readonly IProductService _productService;
private readonly IOrderService _orderService;
private readonly IWorkContext _workContext;
private readonly CustomerSettings _customerSettings;
public DownloadController(
IDownloadService downloadService,
IProductService productService,
IOrderService orderService,
IWorkContext workContext,
CustomerSettings customerSettings)
{
this._downloadService = downloadService;
this._productService = productService;
this._orderService = orderService;
this._workContext = workContext;
this._customerSettings = customerSettings;
}
private ActionResult GetFileContentResultFor(Download download, Product product, byte[] data)
{
if (data == null || data.LongLength == 0)
{
NotifyError(T("Common.Download.NoDataAvailable"));
return new RedirectResult(Url.Action("Info", "Customer"));
}
var fileName = (download.Filename.HasValue() ? download.Filename : download.Id.ToString());
var contentType = (download.ContentType.HasValue() ? download.ContentType : "application/octet-stream");
return new FileContentResult(data, contentType)
{
FileDownloadName = fileName + download.Extension
};
}
private ActionResult GetFileContentResultFor(Download download, Product product)
{
return GetFileContentResultFor(download, product, _downloadService.LoadDownloadBinary(download));
}
public ActionResult Sample(int productId)
{
var product = _productService.GetProductById(productId);
if (product == null)
return HttpNotFound();
if (!product.HasSampleDownload)
{
NotifyError(T("Common.Download.HasNoSample"));
return RedirectToAction("ProductDetails", "Product", new { productId = productId });
}
var download = _downloadService.GetDownloadById(product.SampleDownloadId.GetValueOrDefault());
if (download == null)
{
NotifyError(T("Common.Download.SampleNotAvailable"));
return RedirectToAction("ProductDetails", "Product", new { productId = productId });
}
if (download.UseDownloadUrl)
return new RedirectResult(download.DownloadUrl);
return GetFileContentResultFor(download, product);
}
public ActionResult GetDownload(Guid id, bool agree = false)
{
if (id == Guid.Empty)
return HttpNotFound();
var orderItem = _orderService.GetOrderItemByGuid(id);
if (orderItem == null)
return HttpNotFound();
var order = orderItem.Order;
var product = orderItem.Product;
var hasNotification = false;
if (!_downloadService.IsDownloadAllowed(orderItem))
{
hasNotification = true;
NotifyError(T("Common.Download.NotAllowed"));
}
if (_customerSettings.DownloadableProductsValidateUser)
{
if (_workContext.CurrentCustomer == null)
return new HttpUnauthorizedResult();
if (order.CustomerId != _workContext.CurrentCustomer.Id)
{
hasNotification = true;
NotifyError(T("Account.CustomerOrders.NotYourOrder"));
}
}
var download = _downloadService.GetDownloadById(product.DownloadId);
if (download == null)
{
hasNotification = true;
NotifyError(T("Common.Download.NoDataAvailable"));
}
if (product.HasUserAgreement && !agree)
{
hasNotification = true;
}
if (!product.UnlimitedDownloads && orderItem.DownloadCount >= product.MaxNumberOfDownloads)
{
hasNotification = true;
NotifyError(T("Common.Download.MaxNumberReached", product.MaxNumberOfDownloads));
}
if (hasNotification)
{
return RedirectToAction("UserAgreement", "Customer", new { id = id });
}
if (download.UseDownloadUrl)
{
orderItem.DownloadCount++;
_orderService.UpdateOrder(order);
return new RedirectResult(download.DownloadUrl);
}
else
{
var data = _downloadService.LoadDownloadBinary(download);
if (data == null || data.LongLength == 0)
{
NotifyError(T("Common.Download.NoDataAvailable"));
return RedirectToAction("UserAgreement", "Customer", new { id = id });
}
orderItem.DownloadCount++;
_orderService.UpdateOrder(order);
return GetFileContentResultFor(download, product, data);
}
}
public ActionResult GetLicense(Guid id)
{
if (id == Guid.Empty)
return HttpNotFound();
var orderItem = _orderService.GetOrderItemByGuid(id);
if (orderItem == null)
return HttpNotFound();
var order = orderItem.Order;
var product = orderItem.Product;
if (!_downloadService.IsLicenseDownloadAllowed(orderItem))
{
NotifyError(T("Common.Download.NotAllowed"));
return RedirectToAction("DownloadableProducts", "Customer");
}
if (_customerSettings.DownloadableProductsValidateUser)
{
if (_workContext.CurrentCustomer == null)
return new HttpUnauthorizedResult();
if (order.CustomerId != _workContext.CurrentCustomer.Id)
{
NotifyError(T("Account.CustomerOrders.NotYourOrder"));
return RedirectToAction("DownloadableProducts", "Customer");
}
}
var download = _downloadService.GetDownloadById(orderItem.LicenseDownloadId.HasValue ? orderItem.LicenseDownloadId.Value : 0);
if (download == null)
{
NotifyError(T("Common.Download.NotAvailable"));
return RedirectToAction("DownloadableProducts", "Customer");
}
if (download.UseDownloadUrl)
return new RedirectResult(download.DownloadUrl);
return GetFileContentResultFor(download, product);
}
public ActionResult GetFileUpload(Guid downloadId)
{
var download = _downloadService.GetDownloadByGuid(downloadId);
if (download == null)
{
NotifyError(T("Common.Download.NotAvailable"));
return RedirectToAction("DownloadableProducts", "Customer");
}
if (download.UseDownloadUrl)
return new RedirectResult(download.DownloadUrl);
return GetFileContentResultFor(download, null);
}
public ActionResult GetUserAgreement(int productId, bool? asPlainText)
{
var product = _productService.GetProductById(productId);
if (product == null)
return Content(T("Products.NotFound", productId));
if (!product.IsDownload || !product.HasUserAgreement || product.UserAgreementText.IsEmpty())
return Content(T("DownloadableProducts.HasNoUserAgreement"));
if (asPlainText ?? false)
{
var agreement = HtmlUtils.ConvertHtmlToPlainText(product.UserAgreementText);
agreement = HtmlUtils.StripTags(HttpUtility.HtmlDecode(agreement));
return Content(agreement);
}
return Content(product.UserAgreementText);
}
}
}
| nitware/estore | src/Presentation/SmartStore.Web/Controllers/DownloadController.cs | C# | gpl-3.0 | 8,284 |
<?
function auth_check_login()
{
ob_start();
session_start();
if ( $_SESSION["auth_id"] != "BVS@BIREME" ) {
ob_end_clean();
header("Location: /admin/index.php?error=TIMEOUT");
exit;
}
ob_end_clean();
}
?> | SuporteCTRL/suitesaber | htdocs/site/site/admin/auth_check.php | PHP | gpl-3.0 | 261 |
/*
This source file is part of Rigs of Rods
Copyright 2005-2012 Pierre-Michel Ricordel
Copyright 2007-2012 Thomas Fischer
Copyright 2013-2014 Petr Ohlidal
For more information, see http://www.rigsofrods.com/
Rigs of Rods is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3, as
published by the Free Software Foundation.
Rigs of Rods 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 Rigs of Rods. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SkyXManager.h"
#include "Application.h"
#include "HydraxWater.h"
#include "OgreSubsystem.h"
#include "TerrainManager.h"
#include "TerrainGeometryManager.h"
using namespace Ogre;
using namespace RoR;
SkyXManager::SkyXManager(Ogre::String configFile)
{
InitLight();
//Ogre::ResourceGroupManager::getSingleton().addResourceLocation("..\\resource\\SkyX\\","FileSystem", "SkyX",true); //Temp
mBasicController = new SkyX::BasicController();
mSkyX = new SkyX::SkyX(gEnv->sceneManager, mBasicController);
mCfgFileManager = new SkyX::CfgFileManager(mSkyX, mBasicController, gEnv->mainCamera);
mCfgFileManager->load(configFile);
mSkyX->create();
RoR::App::GetOgreSubsystem()->GetOgreRoot()->addFrameListener(mSkyX);
RoR::App::GetOgreSubsystem()->GetRenderWindow()->addListener(mSkyX);
}
SkyXManager::~SkyXManager()
{
RoR::App::GetOgreSubsystem()->GetRenderWindow()->removeListener(mSkyX);
mSkyX->remove();
mSkyX = nullptr;
delete mBasicController;
mBasicController = nullptr;
}
Vector3 SkyXManager::getMainLightDirection()
{
if (mBasicController != nullptr)
return mBasicController->getSunDirection();
return Ogre::Vector3(0.0,0.0,0.0);
}
Light *SkyXManager::getMainLight()
{
return mLight1;
}
bool SkyXManager::update(float dt)
{
UpdateSkyLight();
mSkyX->update(dt);
return true;
}
bool SkyXManager::UpdateSkyLight()
{
Ogre::Vector3 lightDir = -getMainLightDirection();
Ogre::Vector3 sunPos = gEnv->mainCamera->getDerivedPosition() - lightDir*mSkyX->getMeshManager()->getSkydomeRadius(gEnv->mainCamera);
// Calculate current color gradients point
float point = (-lightDir.y + 1.0f) / 2.0f;
if (App::GetSimTerrain ()->getHydraxManager ())
{
App::GetSimTerrain ()->getHydraxManager ()->GetHydrax ()->setWaterColor (mWaterGradient.getColor (point));
App::GetSimTerrain ()->getHydraxManager ()->GetHydrax ()->setSunPosition (sunPos*0.1);
}
mLight0 = gEnv->sceneManager->getLight("Light0");
mLight1 = gEnv->sceneManager->getLight("Light1");
mLight0->setPosition(sunPos*0.02);
mLight1->setDirection(lightDir);
if (App::GetSimTerrain()->getWater())
{
App::GetSimTerrain()->getWater()->WaterSetSunPosition(sunPos*0.1);
}
//setFadeColour was removed with https://github.com/RigsOfRods/rigs-of-rods/pull/1459
/* Ogre::Vector3 sunCol = mSunGradient.getColor(point);
mLight0->setSpecularColour(sunCol.x, sunCol.y, sunCol.z);
if (App::GetSimTerrain()->getWater()) App::GetSimTerrain()->getWater()->setFadeColour(Ogre::ColourValue(sunCol.x, sunCol.y, sunCol.z));
*/
Ogre::Vector3 ambientCol = mAmbientGradient.getColor(point);
mLight1->setDiffuseColour(ambientCol.x, ambientCol.y, ambientCol.z);
mLight1->setPosition(100,100,100);
if (mBasicController->getTime().x > 12)
{
if (mBasicController->getTime().x > mBasicController->getTime().z)
mLight0->setVisible(false);
else
mLight0->setVisible(true);
}
else
{
if (mBasicController->getTime ().x < mBasicController->getTime ().z)
mLight0->setVisible (false);
else
mLight0->setVisible (true);
}
if (round (mBasicController->getTime ().x) != mLastHour)
{
TerrainGeometryManager* gm = App::GetSimTerrain ()->getGeometryManager ();
if (gm)
gm->updateLightMap ();
mLastHour = round (mBasicController->getTime ().x);
}
return true;
}
bool SkyXManager::InitLight()
{
// Water
mWaterGradient = SkyX::ColorGradient();
mWaterGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.058209,0.535822,0.779105)*0.4, 1));
mWaterGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.058209,0.535822,0.729105)*0.3, 0.8));
mWaterGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.058209,0.535822,0.679105)*0.25, 0.6));
mWaterGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.058209,0.535822,0.679105)*0.2, 0.5));
mWaterGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.058209,0.535822,0.679105)*0.1, 0.45));
mWaterGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.058209,0.535822,0.679105)*0.025, 0));
// Sun
mSunGradient = SkyX::ColorGradient();
mSunGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.8,0.75,0.55)*1.5, 1.0f));
mSunGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.8,0.75,0.55)*1.4, 0.75f));
mSunGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.8,0.75,0.55)*1.3, 0.5625f));
mSunGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.6,0.5,0.2)*1.5, 0.5f));
mSunGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.5,0.5,0.5)*0.25, 0.45f));
mSunGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.5,0.5,0.5)*0.01, 0.0f));
// Ambient
mAmbientGradient = SkyX::ColorGradient();
mAmbientGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(1,1,1)*1, 1.0f));
mAmbientGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(1,1,1)*1, 0.6f));
mAmbientGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(1,1,1)*0.6, 0.5f));
mAmbientGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(1,1,1)*0.3, 0.45f));
mAmbientGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(1,1,1)*0.1, 0.35f));
mAmbientGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(1,1,1)*0.05, 0.0f));
gEnv->sceneManager->setAmbientLight(ColourValue(0.35,0.35,0.35)); //Not needed because terrn2 has ambientlight settings
// Light
mLight0 = gEnv->sceneManager->createLight("Light0");
mLight0->setDiffuseColour(1, 1, 1);
mLight0->setCastShadows(false);
mLight1 = gEnv->sceneManager->createLight("Light1");
mLight1->setType(Ogre::Light::LT_DIRECTIONAL);
return true;
}
size_t SkyXManager::getMemoryUsage()
{
//TODO
return 0;
}
void SkyXManager::freeResources()
{
//TODO
}
| ulteq/rigs-of-rods | source/main/gfx/SkyXManager.cpp | C++ | gpl-3.0 | 6,681 |
/*
Copyright (C) 2011 Andrew Cotter
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/>.
*/
/**
\file helpers.hpp
\brief Helper macros, functions and classes
*/
#ifndef __HELPERS_HPP__
#define __HELPERS_HPP__
#include <boost/static_assert.hpp>
#include <boost/cstdint.hpp>
#include <cmath>
namespace GTSVM {
//============================================================================
// ARRAYLENGTH macro
//============================================================================
#define ARRAYLENGTH( array ) \
( sizeof( array ) / sizeof( array[ 0 ] ) )
//============================================================================
// LIKELY and UNLIKELY macros
//============================================================================
#if defined( __GNUC__ ) && ( __GNUC__ >= 3 )
#define LIKELY( boolean ) __builtin_expect( ( boolean ), 1 )
#define UNLIKELY( boolean ) __builtin_expect( ( boolean ), 0 )
#else /* defined( __GNUC__ ) && ( __GNUC__ >= 3 ) */
#define LIKELY( boolean ) ( boolean )
#define UNLIKELY( boolean ) ( boolean )
#endif /* defined( __GNUC__ ) && ( __GNUC__ >= 3 ) */
#ifdef __cplusplus
//============================================================================
// Power helper template
//============================================================================
template< unsigned int t_Number, unsigned int t_Power >
struct Power {
enum { RESULT = t_Number * Power< t_Number, t_Power - 1 >::RESULT };
};
template< unsigned int t_Number >
struct Power< t_Number, 0 > {
enum { RESULT = 1 };
};
//============================================================================
// Signum helper functions
//============================================================================
template< typename t_Type >
inline t_Type Signum( t_Type const& value ) {
t_Type result = 0;
if ( value < 0 )
result = -1;
else if ( value > 0 )
result = 1;
return result;
}
template< typename t_Type >
inline t_Type Signum( t_Type const& value, t_Type const& scale ) {
t_Type result = 0;
if ( value < 0 )
result = -scale;
else if ( value > 0 )
result = scale;
return result;
}
//============================================================================
// Square helper function
//============================================================================
template< typename t_Type >
inline t_Type Square( t_Type const& value ) {
return( value * value );
}
//============================================================================
// Cube helper function
//============================================================================
template< typename t_Type >
inline t_Type Cube( t_Type const& value ) {
return( value * value * value );
}
//============================================================================
// CountBits helper functions
//============================================================================
inline unsigned char CountBits( boost::uint8_t number ) {
BOOST_STATIC_ASSERT( sizeof( number ) == 1 );
number = ( number & 0x55 ) + ( ( number >> 1 ) & 0x55 );
number = ( number & 0x33 ) + ( ( number >> 2 ) & 0x33 );
number = ( number & 0x0f ) + ( number >> 4 );
return number;
}
inline unsigned short CountBits( boost::uint16_t number ) {
BOOST_STATIC_ASSERT( sizeof( number ) == 2 );
number = ( number & 0x5555 ) + ( ( number >> 1 ) & 0x5555 );
number = ( number & 0x3333 ) + ( ( number >> 2 ) & 0x3333 );
number = ( number & 0x0f0f ) + ( ( number >> 4 ) & 0x0f0f );
number = ( number & 0x00ff ) + ( number >> 8 );
return number;
}
inline unsigned int CountBits( boost::uint32_t number ) {
BOOST_STATIC_ASSERT( sizeof( number ) == 4 );
number = ( number & 0x55555555 ) + ( ( number >> 1 ) & 0x55555555 );
number = ( number & 0x33333333 ) + ( ( number >> 2 ) & 0x33333333 );
number = ( number & 0x0f0f0f0f ) + ( ( number >> 4 ) & 0x0f0f0f0f );
number = ( number & 0x00ff00ff ) + ( ( number >> 8 ) & 0x00ff00ff );
number = ( number & 0x0000ffff ) + ( number >> 16 );
return number;
}
inline unsigned long long CountBits( boost::uint64_t number ) {
BOOST_STATIC_ASSERT( sizeof( number ) == 8 );
number = ( number & 0x5555555555555555ull ) + ( ( number >> 1 ) & 0x5555555555555555ull );
number = ( number & 0x3333333333333333ull ) + ( ( number >> 2 ) & 0x3333333333333333ull );
number = ( number & 0x0f0f0f0f0f0f0f0full ) + ( ( number >> 4 ) & 0x0f0f0f0f0f0f0f0full );
number = ( number & 0x00ff00ff00ff00ffull ) + ( ( number >> 8 ) & 0x00ff00ff00ff00ffull );
number = ( number & 0x0000ffff0000ffffull ) + ( ( number >> 16 ) & 0x0000ffff0000ffffull );
number = ( number & 0x00000000ffffffffull ) + ( number >> 32 );
return number;
}
//============================================================================
// HighBit helper functions
//============================================================================
inline unsigned int HighBit( boost::uint8_t number ) {
BOOST_STATIC_ASSERT( sizeof( number ) == 1 );
unsigned int bit = 0;
if ( number & 0xf0 ) {
bit += 4;
number >>= 4;
}
if ( number & 0x0c ) {
bit += 2;
number >>= 2;
}
if ( number & 0x02 )
++bit;
return bit;
}
inline unsigned int HighBit( boost::uint16_t number ) {
BOOST_STATIC_ASSERT( sizeof( number ) == 2 );
unsigned int bit = 0;
if ( number & 0xff00 ) {
bit += 8;
number >>= 8;
}
if ( number & 0x00f0 ) {
bit += 4;
number >>= 4;
}
if ( number & 0x000c ) {
bit += 2;
number >>= 2;
}
if ( number & 0x0002 )
++bit;
return bit;
}
inline unsigned int HighBit( boost::uint32_t number ) {
BOOST_STATIC_ASSERT( sizeof( number ) == 4 );
unsigned int bit = 0;
if ( number & 0xffff0000 ) {
bit += 16;
number >>= 16;
}
if ( number & 0x0000ff00 ) {
bit += 8;
number >>= 8;
}
if ( number & 0x000000f0 ) {
bit += 4;
number >>= 4;
}
if ( number & 0x0000000c ) {
bit += 2;
number >>= 2;
}
if ( number & 0x00000002 )
++bit;
return bit;
}
inline unsigned int HighBit( boost::uint64_t number ) {
BOOST_STATIC_ASSERT( sizeof( number ) == 8 );
unsigned int bit = 0;
if ( number & 0xffffffff00000000ull ) {
bit += 32;
number >>= 32;
}
if ( number & 0x00000000ffff0000ull ) {
bit += 16;
number >>= 16;
}
if ( number & 0x000000000000ff00ull ) {
bit += 8;
number >>= 8;
}
if ( number & 0x00000000000000f0ull ) {
bit += 4;
number >>= 4;
}
if ( number & 0x000000000000000cull ) {
bit += 2;
number >>= 2;
}
if ( number & 0x0000000000000002ull )
++bit;
return bit;
}
} // namespace GTSVM
#endif /* __cplusplus */
#endif /* __HELPERS_HPP__ */
| mjmg/Rgtsvm | src/helpers.hpp | C++ | gpl-3.0 | 7,286 |
/**
* This file is part of a demo that shows how to use RT2D, a 2D OpenGL framework.
*
* - Copyright 2015 Rik Teerling <rik@onandoffables.com>
* - Initial commit
* - Copyright 2015 Your Name <you@yourhost.com>
* - What you did
*/
#include "scene01.h"
Scene01::Scene01() : SuperScene()
{
// Start Timer t
t.start();
text[0]->message("Scene01: Parent/child, Sprite, Spritesheet, blendcolor");
text[4]->message("<SPACE> reset UV animation");
text[5]->message("<Arrow keys> move camera");
// Create an Entity with a custom pivot point.
default_entity = new BasicEntity();
default_entity->addSprite("assets/default.tga", 0.75f, 0.25f, 3, 0); // custom pivot point, filter, wrap (0=repeat, 1=mirror, 2=clamp)
default_entity->position = Point2(SWIDTH/3, SHEIGHT/2);
// To create a Sprite with specific properties, create it first, then add it to an Entity later.
// It will be unique once you added it to an Entity. Except for non-dynamic Texture wrapping/filtering if it's loaded from disk and handled by the ResourceManager.
// You must delete it yourself after you've added it to all the Entities you want.
Sprite* f_spr = new Sprite();
f_spr->setupSprite("assets/grayscale.tga", 0.5f, 0.5f, 1.0f, 1.0f, 1, 2); // filename, pivot.x, pivot.y, uvdim.x, uvdim.y, filter, wrap
f_spr->color = GREEN; // green
child1_entity = new BasicEntity();
child1_entity->position = Point2(100, -100); // position relative to parent (default_entity)
child1_entity->addSprite(f_spr);
delete f_spr;
// Create an Entity that's going to be a Child of default_entity.
// Easiest way to create a Sprite with sensible defaults. @see Sprite::setupSprite()
child2_entity = new BasicEntity();
child2_entity->addSprite("assets/grayscale.tga");
child2_entity->sprite()->color = RED; // red
child2_entity->position = Point2(64, 64); // position relative to parent (child1_entity)
// An example of using a SpriteSheet ("animated texture").
// Remember you can also animate UV's of any Sprite (uvoffset).
animated_entity = new BasicEntity();
animated_entity->addLine("assets/default.line"); // Add a line (default line fits nicely)
animated_entity->addSpriteSheet("assets/spritesheet.tga", 4, 4); // divide Texture in 4x4 slices
animated_entity->position = Point2(SWIDTH/3*2, SHEIGHT/2);
// Create a UI entity
ui_element = new BasicEntity();
//ui_element->position = Point2(SWIDTH-150, 20); // sticks to camera in update()
// filter + wrap inherited from default_entity above (is per texturename. "assets/default.tga" already loaded).
ui_element->addSprite("assets/default.tga", 0.5f, 0.0f); // Default texture. Pivot point top middle. Pivot(0,0) is top left.
ui_element->sprite()->size = Point2(256, 64); // texture is 512x512. Make Mesh half the width, 1 row of squares (512/8).
ui_element->sprite()->uvdim = Point2(0.5f, 0.125f); // UV 1/8 of the height.
ui_element->sprite()->uvoffset = Point2(0.0f, 0.0f); // Show bottom row. UV(0,0) is bottom left.
// create a tree-structure to send to the Renderer
// by adding them to each other and/or the scene ('this', or one of the layers[])
child1_entity->addChild(child2_entity);
default_entity->addChild(child1_entity);
layers[1]->addChild(default_entity);
layers[1]->addChild(animated_entity);
layers[top_layer]->addChild(ui_element);
}
Scene01::~Scene01()
{
// deconstruct and delete the Tree
child1_entity->removeChild(child2_entity);
default_entity->removeChild(child1_entity);
layers[1]->removeChild(default_entity);
layers[1]->removeChild(animated_entity);
layers[top_layer]->removeChild(ui_element);
delete animated_entity;
delete child2_entity;
delete child1_entity;
delete default_entity;
delete ui_element;
}
void Scene01::update(float deltaTime)
{
// ###############################################################
// Make SuperScene do what it needs to do
// - Escape key stops Scene
// - Move Camera
// ###############################################################
SuperScene::update(deltaTime);
SuperScene::moveCamera(deltaTime);
// ###############################################################
// Mouse cursor in screen coordinates
// ###############################################################
int mousex = input()->getMouseX();
int mousey = input()->getMouseY();
std::string cursortxt = "cursor (";
cursortxt.append(std::to_string(mousex));
cursortxt.append(",");
cursortxt.append(std::to_string(mousey));
cursortxt.append(")");
text[9]->message(cursortxt);
// ###############################################################
// Rotate default_entity
// ###############################################################
default_entity->rotation -= 90 * DEG_TO_RAD * deltaTime; // 90 deg. per sec.
if (default_entity->rotation < TWO_PI) { default_entity->rotation += TWO_PI; }
// ###############################################################
// alpha child1_entity + child2_entity
// ###############################################################
static float counter = 0;
child1_entity->sprite()->color.a = abs(sin(counter)*255);
child2_entity->sprite()->color.a = abs(cos(counter)*255);
counter+=deltaTime/2; if (counter > TWO_PI) { counter = 0; }
// ###############################################################
// Animate animated_entity
// ###############################################################
animated_entity->rotation += 22.5 * DEG_TO_RAD * deltaTime;
if (animated_entity->rotation > -TWO_PI) { animated_entity->rotation -= TWO_PI; }
static int f = 0;
if (f > 15) { f = 0; }
animated_entity->sprite()->frame(f);
if (t.seconds() > 0.25f) {
static RGBAColor rgb = RED;
animated_entity->sprite()->color = rgb;
rgb = Color::rotate(rgb, 0.025f);
f++;
t.start();
}
// ###############################################################
// ui_element uvoffset
// ###############################################################
static float xoffset = 0.0f;
xoffset += deltaTime / 2;
if (input()->getKey( GLFW_KEY_SPACE )) {
xoffset = 0.0f;
}
ui_element->sprite()->uvoffset.x = xoffset;
ui_element->position = Point2(camera()->position.x + SWIDTH/2 - 150, camera()->position.y - SHEIGHT/2 + 20);
}
| Thalliuss/RT2D_Project | demo/scene01.cpp | C++ | gpl-3.0 | 6,195 |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using Frontiers.World;
[CustomEditor(typeof(BannerEditor))]
public class BannerEditorEditor : Editor
{
protected BannerEditor be;
public void Awake()
{
be = (BannerEditor)target;
}
public override void OnInspectorGUI()
{
EditorStyles.textField.wordWrap = true;
DrawDefaultInspector();
be.DrawEditor();
}
}
| SignpostMarv/FRONTIERS | Assets/Editor/Frontiers/BannerEditorEditor.cs | C# | gpl-3.0 | 436 |
<?php
// Heading
$_['heading_title'] = 'Cliente';
// Text
$_['text_login'] = 'Login';
$_['text_success'] = 'Hai modificato con successo i clienti!';
$_['text_approved'] = 'Hai attivato %s account!';
$_['text_wait'] = 'Attendi!';
$_['text_balance'] = 'Saldo:';
// Column
$_['column_name'] = 'Nome cliente';
$_['column_email'] = 'E-Mail';
$_['column_customer_group'] = 'Gruppo clienti';
$_['column_status'] = 'Stato';
$_['column_approved'] = 'Approvato';
$_['column_date_added'] = 'Data inserimento';
$_['column_description'] = 'Descrizione';
$_['column_amount'] = 'Imporot';
$_['column_points'] = 'Punti';
$_['column_ip'] = 'IP';
$_['column_total'] = 'Account Totali';
$_['column_action'] = 'Azione';
// Entry
$_['entry_firstname'] = 'Nome:';
$_['entry_lastname'] = 'Cognome:';
$_['entry_email'] = 'E-Mail:';
$_['entry_telephone'] = 'Telefono:';
$_['entry_fax'] = 'Fax:';
$_['entry_newsletter'] = 'Newsletter:';
$_['entry_customer_group'] = 'Gruppo clienti:';
$_['entry_status'] = 'Stato:';
$_['entry_password'] = 'Password:';
$_['entry_confirm'] = 'Conferma:';
$_['entry_company'] = 'Azienda:';
$_['entry_address_1'] = 'Indirizzo 1:';
$_['entry_address_2'] = 'Indirizzo 2:';
$_['entry_city'] = 'Città:';
$_['entry_postcode'] = 'CAP:';
$_['entry_country'] = 'Nazione:';
$_['entry_zone'] = 'Provincia:';
$_['entry_default'] = 'Indirizzo di Default:';
$_['entry_amount'] = 'Importo:';
$_['entry_points'] = 'Punti:';
$_['entry_description'] = 'Descrizione:';
// Error
$_['error_warning'] = 'Attenzione: Controlla il modulo, ci sono alcuni errori!';
$_['error_permission'] = 'Attenzione: Non hai i permessi necessari per modificare i clienti!';
$_['error_firstname'] = 'Il nome deve essere maggiore di 1 carattere e minore di 32!';
$_['error_lastname'] = 'Il cognome deve essere maggiore di 1 carattere e minore di 32!';
$_['error_email'] = 'L\'indirizzo e-mail sembra essere non valido!';
$_['error_telephone'] = 'Il Telefono deve essere maggiore di 3 caratteri e minore di 32!';
$_['error_password'] = 'La password deve essere maggiore di 3 caratteri e minore di 20!';
$_['error_confirm'] = 'Le due password non coincodono!';
$_['error_address_1'] = 'L\'indirizzo deve essere lungo almeno 3 caratteri e non più di 128 caratteri!';
$_['error_city'] = 'La città deve essere lungo almeno 3 caratteri e non più di 128 caratteri!';
$_['error_postcode'] = 'Il CAP deve essere tra i 2 ed i 10 caratteri per questa nazione!';
$_['error_country'] = 'Per favore seleziona lo stato!';
$_['error_zone'] = 'Per favore seleziona la provincia';
?> | censam/open_cart | multilanguage/OC-Europa-1-5-1-3-9.part01/upload/admin/language/italian/sale/customer.php | PHP | gpl-3.0 | 3,022 |
<?php
class OperationData {
public static $tablename = "operation";
public function OperationData(){
$this->name = "";
$this->product_id = "";
$this->q = "";
$this->cut_id = "";
$this->operation_type_id = "";
$this->is_oficial = "0";
$this->created_at = "NOW()";
}
public function add(){
$sql = "insert into ".self::$tablename." (product_id,q,operation_type_id,is_oficial,sell_id,created_at) ";
$sql .= "value (\"$this->product_id\",\"$this->q\",$this->operation_type_id,\"$this->is_oficial\",$this->sell_id,$this->created_at)";
return Executor::doit($sql);
}
public function add_q(){
$sql = "update ".self::$tablename." set q=$this->q where id=$this->id";
Executor::doit($sql);
}
public static function delById($id){
$sql = "delete from ".self::$tablename." where id=$id";
Executor::doit($sql);
}
public function del(){
$sql = "delete from ".self::$tablename." where id=$this->id";
Executor::doit($sql);
}
// partiendo de que ya tenemos creado un objecto OperationData previamente utilizamos el contexto
public function update(){
$sql = "update ".self::$tablename." set product_id=\"$this->product_id\",q=\"$this->q\",is_oficial=\"$this->is_oficial\" where id=$this->id";
Executor::doit($sql);
}
public static function getById($id){
$sql = "select * from ".self::$tablename." where id=$id";
$query = Executor::doit($sql);
$found = null;
$data = new OperationData();
while($r = $query[0]->fetch_array()){
$data->id = $r['id'];
$data->product_id = $r['product_id'];
$data->q = $r['q'];
$data->is_oficial = $r['is_oficial'];
$data->operation_type_id = $r['operation_type_id'];
$data->sell_id = $r['sell_id'];
$data->created_at = $r['created_at'];
$found = $data;
break;
}
return $found;
}
public static function getAll(){
$sql = "select * from ".self::$tablename." order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllDates(){
$sql = "select *,date(created_at) as d from ".self::$tablename." group by date(created_at) order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$array[$cnt]->d = $r['d'];
$cnt++;
}
return $array;
}
public static function getAllByDate($start){
$sql = "select *,price_out as price,product.name as name,category.name as cname from ".self::$tablename." inner join product on (operation.product_id=product.id) inner join category on (product.category_id=category.id) inner join sell on (sell.id=operation.sell_id) where date(operation.created_at) = \"$start\" and is_applied=1 order by operation.created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->price = $r['price'];
$array[$cnt]->name = $r['name'];
$array[$cnt]->cname = $r['cname'];
$array[$cnt]->unit = $r['unit'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllByDateAndCategoryId($start,$cat_id){
$sql = "select *,price_out as price,product.name as name,category.name as cname,product.unit as punit from ".self::$tablename." inner join sell on (sell.id=operation.sell_id) inner join product on (operation.product_id=product.id) inner join category on (product.category_id=category.id) where date(operation.created_at) = \"$start\" and product.category_id=$cat_id and sell.is_applied=1 order by operation.created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->price = $r['price'];
$array[$cnt]->name = $r['name'];
$array[$cnt]->cname = $r['cname'];
$array[$cnt]->unit = $r['punit'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllByDateOfficial($start,$end){
$sql = "select * from ".self::$tablename." where date(created_at) > \"$start\" and date(created_at) <= \"$end\" order by created_at desc";
if($start == $end){
$sql = "select * from ".self::$tablename." where date(created_at) = \"$start\" order by created_at desc";
}
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllByDateOfficialBP($product, $start,$end){
$sql = "select * from ".self::$tablename." where date(created_at) > \"$start\" and date(created_at) <= \"$end\" and product_id=$product order by created_at desc";
if($start == $end){
$sql = "select * from ".self::$tablename." where date(created_at) = \"$start\" and product_id=$product order by created_at desc";
}
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public function getProduct(){
return ProductData::getById($this->product_id);
}
public function getOperationType(){
return OperationTypeData::getById($this->operation_type_id);
}
////////////////////////////////////////////////////////////////////
public static function getQ($product_id,$cut_id){
$q=0;
$operations = self::getAllByProductIdCutId($product_id,$cut_id);
$input_id = OperationTypeData::getByName("entrada")->id;
$output_id = OperationTypeData::getByName("salida")->id;
foreach($operations as $operation){
if($operation->operation_type_id==$input_id){ $q+=$operation->q; }
else if($operation->operation_type_id==$output_id){ $q+=(-$operation->q); }
}
// print_r($data);
return $q;
}
public static function getQYesF($product_id,$cut_id){
$q=0;
$operations = self::getAllByProductIdCutId($product_id,$cut_id);
$input_id = OperationTypeData::getByName("entrada")->id;
$output_id = OperationTypeData::getByName("salida")->id;
foreach($operations as $operation){
if($operation->is_oficial){
if($operation->operation_type_id==$input_id){ $q+=$operation->q; }
else if($operation->operation_type_id==$output_id){ $q+=(-$operation->q); }
}
}
// print_r($data);
return $q;
}
public static function getQNoF($product_id,$cut_id){
$q = self::getQ($product_id,$cut_id);
$f = self::getQYesF($product_id,$cut_id);
return $q-$f;
}
public static function getAllByProductIdCutId($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllByProductIdCutIdOficial($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllByProductIdCutIdUnOficial($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id and is_oficial=0 order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllProductsBySellId($sell_id){
$sql = "select * from ".self::$tablename." where sell_id=$sell_id order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllByProductIdCutIdYesF($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllByProductIdCutIdNoF($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id and is_oficial=0 order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
public static function getOutputQ($product_id,$cut_id){
$q=0;
$operations = self::getOutputByProductIdCutId($product_id,$cut_id);
$input_id = OperationTypeData::getByName("entrada")->id;
$output_id = OperationTypeData::getByName("salida")->id;
foreach($operations as $operation){
if($operation->operation_type_id==$input_id){ $q+=$operation->q; }
else if($operation->operation_type_id==$output_id){ $q+=(-$operation->q); }
}
// print_r($data);
return $q;
}
public static function getOutputQYesF($product_id,$cut_id){
$q=0;
$operations = self::getOutputByProductIdCutIdYesF($product_id,$cut_id);
$input_id = OperationTypeData::getByName("entrada")->id;
$output_id = OperationTypeData::getByName("salida")->id;
foreach($operations as $operation){
if($operation->operation_type_id==$input_id){ $q+=$operation->q; }
else if($operation->operation_type_id==$output_id){ $q+=(-$operation->q); }
}
// print_r($data);
return $q;
}
public static function getOutputQNoF($product_id,$cut_id){
$q=0;
$operations = self::getOutputByProductIdCutIdNoF($product_id,$cut_id);
$input_id = OperationTypeData::getByName("entrada")->id;
$output_id = OperationTypeData::getByName("salida")->id;
foreach($operations as $operation){
if($operation->operation_type_id==$input_id){ $q+=$operation->q; }
else if($operation->operation_type_id==$output_id){ $q+=(-$operation->q); }
}
// print_r($data);
return $q;
}
public static function getOutputByProductIdCutId($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id and operation_type_id=2 order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getOutputByProductIdCutIdYesF($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id and operation_type_id=2 order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getOutputByProductIdCutIdNoF($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id and is_oficial=0 and operation_type_id=2 order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
public static function getInputQ($product_id,$cut_id){
$q=0;
$operations = self::getInputByProductIdCutId($product_id,$cut_id);
$input_id = OperationTypeData::getByName("entrada")->id;
$output_id = OperationTypeData::getByName("salida")->id;
foreach($operations as $operation){
if($operation->operation_type_id==$input_id){ $q+=$operation->q; }
else if($operation->operation_type_id==$output_id){ $q+=(-$operation->q); }
}
// print_r($data);
return $q;
}
public static function getInputQYesF($product_id,$cut_id){
$q=0;
$operations = self::getInputByProductIdCutIdYesF($product_id,$cut_id);
$input_id = OperationTypeData::getByName("entrada")->id;
$output_id = OperationTypeData::getByName("salida")->id;
foreach($operations as $operation){
if($operation->operation_type_id==$input_id){ $q+=$operation->q; }
else if($operation->operation_type_id==$output_id){ $q+=(-$operation->q); }
}
// print_r($data);
return $q;
}
public static function getInputQNoF($product_id,$cut_id){
$q=0;
$operations = self::getInputByProductIdCutIdNoF($product_id,$cut_id);
$input_id = OperationTypeData::getByName("entrada")->id;
$output_id = OperationTypeData::getByName("salida")->id;
foreach($operations as $operation){
if($operation->operation_type_id==$input_id){ $q+=$operation->q; }
else if($operation->operation_type_id==$output_id){ $q+=(-$operation->q); }
}
// print_r($data);
return $q;
}
public static function getInputByProductIdCutId($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id and operation_type_id=1 order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getInputByProductIdCutIdYesF($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id and operation_type_id=1 order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getInputByProductIdCutIdNoF($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id and is_oficial=0 and operation_type_id=1 order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
////////////////////////////////////////////////////////////////////////////
}
?> | cyberiaVirtual/kaluna_vta | core/modules/index/model/OperationData.php | PHP | gpl-3.0 | 19,750 |
/****************************************************************************
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* The main class of Armature, it plays armature animation, manages and updates bones' state.
* @class
* @extends ccs.Node
*
* @property {ccs.Bone} parentBone - The parent bone of the armature node
* @property {ccs.ArmatureAnimation} animation - The animation
* @property {ccs.ArmatureData} armatureData - The armature data
* @property {String} name - The name of the armature
* @property {cc.SpriteBatchNode} batchNode - The batch node of the armature
* @property {Number} version - The version
* @property {Object} body - The body of the armature
* @property {ccs.ColliderFilter} colliderFilter - <@writeonly> The collider filter of the armature
*/
ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{
animation: null,
armatureData: null,
batchNode: null,
_parentBone: null,
_boneDic: null,
_topBoneList: null,
_armatureIndexDic: null,
_offsetPoint: null,
version: 0,
_armatureTransformDirty: true,
_body: null,
_blendFunc: null,
_className: "Armature",
/**
* Create a armature node.
* Constructor of ccs.Armature
* @param {String} name
* @param {ccs.Bone} parentBone
* @example
* var armature = new ccs.Armature();
*/
ctor: function (name, parentBone) {
cc.Node.prototype.ctor.call(this);
this._name = "";
this._topBoneList = [];
this._armatureIndexDic = {};
this._offsetPoint = cc.p(0, 0);
this._armatureTransformDirty = true;
this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST};
name && ccs.Armature.prototype.init.call(this, name, parentBone);
// Hack way to avoid RendererWebGL from skipping Armature
this._texture = {};
},
/**
* Initializes a CCArmature with the specified name and CCBone
* @param {String} [name]
* @param {ccs.Bone} [parentBone]
* @return {Boolean}
*/
init: function (name, parentBone) {
if (parentBone)
this._parentBone = parentBone;
this.removeAllChildren();
this.animation = new ccs.ArmatureAnimation();
this.animation.init(this);
this._boneDic = {};
this._topBoneList.length = 0;
//this._name = name || "";
var armatureDataManager = ccs.armatureDataManager;
var animationData;
if (name !== "") {
//animationData
animationData = armatureDataManager.getAnimationData(name);
cc.assert(animationData, "AnimationData not exist!");
this.animation.setAnimationData(animationData);
//armatureData
var armatureData = armatureDataManager.getArmatureData(name);
cc.assert(armatureData, "ArmatureData not exist!");
this.armatureData = armatureData;
//boneDataDic
var boneDataDic = armatureData.getBoneDataDic();
for (var key in boneDataDic) {
var bone = this.createBone(String(key));
//! init bone's Tween to 1st movement's 1st frame
do {
var movData = animationData.getMovement(animationData.movementNames[0]);
if (!movData) break;
var _movBoneData = movData.getMovementBoneData(bone.getName());
if (!_movBoneData || _movBoneData.frameList.length <= 0) break;
var frameData = _movBoneData.getFrameData(0);
if (!frameData) break;
bone.getTweenData().copy(frameData);
bone.changeDisplayWithIndex(frameData.displayIndex, false);
} while (0);
}
this.update(0);
this.updateOffsetPoint();
} else {
name = "new_armature";
this.armatureData = new ccs.ArmatureData();
this.armatureData.name = name;
animationData = new ccs.AnimationData();
animationData.name = name;
armatureDataManager.addArmatureData(name, this.armatureData);
armatureDataManager.addAnimationData(name, animationData);
this.animation.setAnimationData(animationData);
}
this._renderCmd.initShaderCache();
this.setCascadeOpacityEnabled(true);
this.setCascadeColorEnabled(true);
return true;
},
visit: function (parent) {
var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null;
// quick return if not visible
if (!this._visible) {
cmd._propagateFlagsDown(parentCmd);
return;
}
cmd.visit(parentCmd);
cmd._dirtyFlag = 0;
},
addChild: function (child, localZOrder, tag) {
if (child instanceof ccui.Widget) {
cc.log("Armature doesn't support to add Widget as its child, it will be fix soon.");
return;
}
cc.Node.prototype.addChild.call(this, child, localZOrder, tag);
},
/**
* create a bone with name
* @param {String} boneName
* @return {ccs.Bone}
*/
createBone: function (boneName) {
var existedBone = this.getBone(boneName);
if (existedBone)
return existedBone;
var boneData = this.armatureData.getBoneData(boneName);
var parentName = boneData.parentName;
var bone = null;
if (parentName) {
this.createBone(parentName);
bone = new ccs.Bone(boneName);
this.addBone(bone, parentName);
} else {
bone = new ccs.Bone(boneName);
this.addBone(bone, "");
}
bone.setBoneData(boneData);
bone.getDisplayManager().changeDisplayWithIndex(-1, false);
return bone;
},
/**
* Add a Bone to this Armature
* @param {ccs.Bone} bone The Bone you want to add to Armature
* @param {String} parentName The parent Bone's name you want to add to. If it's null, then set Armature to its parent
*/
addBone: function (bone, parentName) {
cc.assert(bone, "Argument must be non-nil");
var locBoneDic = this._boneDic;
if (bone.getName())
cc.assert(!locBoneDic[bone.getName()], "bone already added. It can't be added again");
if (parentName) {
var boneParent = locBoneDic[parentName];
if (boneParent)
boneParent.addChildBone(bone);
else
this._topBoneList.push(bone);
} else
this._topBoneList.push(bone);
bone.setArmature(this);
locBoneDic[bone.getName()] = bone;
this.addChild(bone);
},
/**
* Remove a bone with the specified name. If recursion it will also remove child Bone recursively.
* @param {ccs.Bone} bone The bone you want to remove
* @param {Boolean} recursion Determine whether remove the bone's child recursion.
*/
removeBone: function (bone, recursion) {
cc.assert(bone, "bone must be added to the bone dictionary!");
bone.setArmature(null);
bone.removeFromParent(recursion);
cc.arrayRemoveObject(this._topBoneList, bone);
delete this._boneDic[bone.getName()];
this.removeChild(bone, true);
},
/**
* Gets a bone with the specified name
* @param {String} name The bone's name you want to get
* @return {ccs.Bone}
*/
getBone: function (name) {
return this._boneDic[name];
},
/**
* Change a bone's parent with the specified parent name.
* @param {ccs.Bone} bone The bone you want to change parent
* @param {String} parentName The new parent's name
*/
changeBoneParent: function (bone, parentName) {
cc.assert(bone, "bone must be added to the bone dictionary!");
var parentBone = bone.getParentBone();
if (parentBone) {
cc.arrayRemoveObject(parentBone.getChildren(), bone);
bone.setParentBone(null);
}
if (parentName) {
var boneParent = this._boneDic[parentName];
if (boneParent) {
boneParent.addChildBone(bone);
cc.arrayRemoveObject(this._topBoneList, bone);
} else
this._topBoneList.push(bone);
}
},
/**
* Get CCArmature's bone dictionary
* @return {Object} Armature's bone dictionary
*/
getBoneDic: function () {
return this._boneDic;
},
/**
* Set contentSize and Calculate anchor point.
*/
updateOffsetPoint: function () {
// Set contentsize and Calculate anchor point.
var rect = this.getBoundingBox();
this.setContentSize(rect);
var locOffsetPoint = this._offsetPoint;
locOffsetPoint.x = -rect.x;
locOffsetPoint.y = -rect.y;
if (rect.width !== 0 && rect.height !== 0)
this.setAnchorPoint(locOffsetPoint.x / rect.width, locOffsetPoint.y / rect.height);
},
getOffsetPoints: function () {
return {x: this._offsetPoint.x, y: this._offsetPoint.y};
},
/**
* Sets animation to this Armature
* @param {ccs.ArmatureAnimation} animation
*/
setAnimation: function (animation) {
this.animation = animation;
},
/**
* Gets the animation of this Armature.
* @return {ccs.ArmatureAnimation}
*/
getAnimation: function () {
return this.animation;
},
/**
* armatureTransformDirty getter
* @returns {Boolean}
*/
getArmatureTransformDirty: function () {
return this._armatureTransformDirty;
},
/**
* The update callback of ccs.Armature, it updates animation's state and updates bone's state.
* @override
* @param {Number} dt
*/
update: function (dt) {
this.animation.update(dt);
var locTopBoneList = this._topBoneList;
for (var i = 0; i < locTopBoneList.length; i++)
locTopBoneList[i].update(dt);
this._armatureTransformDirty = false;
},
/**
* The callback when ccs.Armature enter stage.
* @override
*/
onEnter: function () {
cc.Node.prototype.onEnter.call(this);
this.scheduleUpdate();
},
/**
* The callback when ccs.Armature exit stage.
* @override
*/
onExit: function () {
cc.Node.prototype.onExit.call(this);
this.unscheduleUpdate();
},
/**
* This boundingBox will calculate all bones' boundingBox every time
* @returns {cc.Rect}
*/
getBoundingBox: function () {
var minX, minY, maxX, maxY = 0;
var first = true;
var boundingBox = cc.rect(0, 0, 0, 0), locChildren = this._children;
var len = locChildren.length;
for (var i = 0; i < len; i++) {
var bone = locChildren[i];
if (bone) {
var r = bone.getDisplayManager().getBoundingBox();
if (r.x === 0 && r.y === 0 && r.width === 0 && r.height === 0)
continue;
if (first) {
minX = r.x;
minY = r.y;
maxX = r.x + r.width;
maxY = r.y + r.height;
first = false;
} else {
minX = r.x < boundingBox.x ? r.x : boundingBox.x;
minY = r.y < boundingBox.y ? r.y : boundingBox.y;
maxX = r.x + r.width > boundingBox.x + boundingBox.width ?
r.x + r.width : boundingBox.x + boundingBox.width;
maxY = r.y + r.height > boundingBox.y + boundingBox.height ?
r.y + r.height : boundingBox.y + boundingBox.height;
}
boundingBox.x = minX;
boundingBox.y = minY;
boundingBox.width = maxX - minX;
boundingBox.height = maxY - minY;
}
}
return cc.rectApplyAffineTransform(boundingBox, this.getNodeToParentTransform());
},
/**
* when bone contain the point ,then return it.
* @param {Number} x
* @param {Number} y
* @returns {ccs.Bone}
*/
getBoneAtPoint: function (x, y) {
var locChildren = this._children;
for (var i = locChildren.length - 1; i >= 0; i--) {
var child = locChildren[i];
if (child instanceof ccs.Bone && child.getDisplayManager().containPoint(x, y))
return child;
}
return null;
},
/**
* Sets parent bone of this Armature
* @param {ccs.Bone} parentBone
*/
setParentBone: function (parentBone) {
this._parentBone = parentBone;
var locBoneDic = this._boneDic;
for (var key in locBoneDic) {
locBoneDic[key].setArmature(this);
}
},
/**
* Return parent bone of ccs.Armature.
* @returns {ccs.Bone}
*/
getParentBone: function () {
return this._parentBone;
},
/**
* draw contour
*/
drawContour: function () {
cc._drawingUtil.setDrawColor(255, 255, 255, 255);
cc._drawingUtil.setLineWidth(1);
var locBoneDic = this._boneDic;
for (var key in locBoneDic) {
var bone = locBoneDic[key];
var detector = bone.getColliderDetector();
if (!detector)
continue;
var bodyList = detector.getColliderBodyList();
for (var i = 0; i < bodyList.length; i++) {
var body = bodyList[i];
var vertexList = body.getCalculatedVertexList();
cc._drawingUtil.drawPoly(vertexList, vertexList.length, true);
}
}
},
setBody: function (body) {
if (this._body === body)
return;
this._body = body;
this._body.data = this;
var child, displayObject, locChildren = this._children;
for (var i = 0; i < locChildren.length; i++) {
child = locChildren[i];
if (child instanceof ccs.Bone) {
var displayList = child.getDisplayManager().getDecorativeDisplayList();
for (var j = 0; j < displayList.length; j++) {
displayObject = displayList[j];
var detector = displayObject.getColliderDetector();
if (detector)
detector.setBody(this._body);
}
}
}
},
getShapeList: function () {
if (this._body)
return this._body.shapeList;
return null;
},
getBody: function () {
return this._body;
},
/**
* Sets the blendFunc to ccs.Armature
* @param {cc.BlendFunc|Number} blendFunc
* @param {Number} [dst]
*/
setBlendFunc: function (blendFunc, dst) {
if (dst === undefined) {
this._blendFunc.src = blendFunc.src;
this._blendFunc.dst = blendFunc.dst;
} else {
this._blendFunc.src = blendFunc;
this._blendFunc.dst = dst;
}
},
/**
* Returns the blendFunc of ccs.Armature
* @returns {cc.BlendFunc}
*/
getBlendFunc: function () {
return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst);
},
/**
* set collider filter
* @param {ccs.ColliderFilter} filter
*/
setColliderFilter: function (filter) {
var locBoneDic = this._boneDic;
for (var key in locBoneDic)
locBoneDic[key].setColliderFilter(filter);
},
/**
* Returns the armatureData of ccs.Armature
* @return {ccs.ArmatureData}
*/
getArmatureData: function () {
return this.armatureData;
},
/**
* Sets armatureData to this Armature
* @param {ccs.ArmatureData} armatureData
*/
setArmatureData: function (armatureData) {
this.armatureData = armatureData;
},
getBatchNode: function () {
return this.batchNode;
},
setBatchNode: function (batchNode) {
this.batchNode = batchNode;
},
/**
* version getter
* @returns {Number}
*/
getVersion: function () {
return this.version;
},
/**
* version setter
* @param {Number} version
*/
setVersion: function (version) {
this.version = version;
},
_createRenderCmd: function () {
if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new ccs.Armature.CanvasRenderCmd(this);
else
return new ccs.Armature.WebGLRenderCmd(this);
}
});
var _p = ccs.Armature.prototype;
/** @expose */
_p.parentBone;
cc.defineGetterSetter(_p, "parentBone", _p.getParentBone, _p.setParentBone);
/** @expose */
_p.body;
cc.defineGetterSetter(_p, "body", _p.getBody, _p.setBody);
/** @expose */
_p.colliderFilter;
cc.defineGetterSetter(_p, "colliderFilter", null, _p.setColliderFilter);
_p = null;
/**
* Allocates an armature, and use the ArmatureData named name in ArmatureDataManager to initializes the armature.
* @param {String} [name] Bone name
* @param {ccs.Bone} [parentBone] the parent bone
* @return {ccs.Armature}
* @deprecated since v3.1, please use new construction instead
*/
ccs.Armature.create = function (name, parentBone) {
return new ccs.Armature(name, parentBone);
};
| corumcorp/redsentir | redsentir/static/juego/frameworks/cocos2d-html5/extensions/cocostudio/armature/CCArmature.js | JavaScript | gpl-3.0 | 18,849 |
#include "jednostki.h"
#include "generatormt.h"
#include "nucleus_data.h"
#include "calg5.h"
#include "util2.h"
using namespace std;
template < class T >
static inline T pow2 (T x)
{
return x * x;
}
static inline double bessj0(double x)
{
if(fabs(x)<0.000001)
return cos(x);
else
return sin(x)/x;
}
static double MI2(double rms2, double q,double r)
{
double qr=q*r;
double r2=r*r;
double cosqr=cos(qr);
double sinqr=sin(qr);
return (((((cosqr*qr/6-sinqr/2)*qr-cosqr)*qr+sinqr)*rms2/r2 + sinqr)/r - cosqr*q)/r2;
}
static double MI(double rms2, double q,double r)
{
double qr=q*r;
double r2=r*r;
double r3=r2*r;
double cosqr=cos(qr);
double sinqr=sin(qr);
return (-cosqr*qr+sinqr)/r3
// + (((cosqr*qr/6-sinqr/2)*qr -cosqr)*qr+sinqr)*rms2/r2/r3;
+(cosqr*qr*qr-2*cosqr-2*sinqr*qr)/r2/r2/6;
}
static double prfMI(double t[3], double r)
{
static double const twoPi2=2*Pi*Pi;
if(r==0)
r=0.00001;
double rms2=t[0]*t[0];
return max(0.0, (MI2(rms2,200,r)-MI2(rms2,0.01,r))/twoPi2);
}
///density profile for the HO model
static double prfHO(double t[3], double r)
{
double x=r/t[0],x2=x*x;
return t[2]*(1+t[1]*x2)*exp(-x2);
}
///density profile for the MHO model
static double prfMHO(double t[3], double r)
{
double x=r/t[0];
return (t[2]*(1+t[1]*x*x)*exp(-x*x));
}
///density profile for the 2pF model
static double prf2pF(double t[3], double r)
{
return t[2]/(1.+exp((r-t[0])/t[1]));
}
///density profile for the 3pF model
static double prf3pF(double t[4], double r)
{
double x=r/t[0];
return t[3]*
(1+t[2]*x*x)
/(1+exp((r-t[0])/t[1]));
}
///density profile for the 3pG model
static double prf3pG(double t[4], double r)
{
double x=r/t[0], x2=x*x;
return max(0.,t[3]*(1+t[2]*x2)/(1+exp((r*r-t[0]*t[0])/(t[1]*t[1]))));
}
///density profile for the FB model
static double prfFB(double fb[], double r)
{
if(r>fb[0]) // fb[0]- radius
return 0;
double suma=0;
double x=Pi*r/fb[0];
for(int j=1; j<=17 and fb[j] ; j++)
{
suma+=fb[j]*bessj0(j*x);
}
return max(0.,suma);
}
///density profile for the SOG model
static double prfSOG(double sog[],double r)
{
static const double twoPi32=2*Pi*sqrt(Pi);
//double rms=sog[0];
double g=sog[1]/sqrt(1.5);
double coef=twoPi32*g*g*g;
double suma=0;
for(int j=2; j<25 ; j+=2)
{
double Ri=sog[j];
double Qi=sog[j+1];
double Ai=Qi/(coef*(1+2*pow2(Ri/g)));
suma+=Ai*(exp(-pow2((r-Ri)/g))+exp(-pow2((r+Ri)/g)));
}
return max(0.,suma);
}
static double prfUG(double ug[],double r)
{
double xi=1.5/ug[0]/ug[0];
return ug[1]*exp( -r*r*xi);
}
// Uniform Gaussian model
static double ug_11_12 [2]= {2.946, 0.296785};
// Harmonic-oscillator model (HO): a, alfa, rho0(calculated)
static double ho_3_4 [3]= {1.772 , 0.327, 0.151583};
static double ho_4_5 [3]= {1.776 , 0.631, 0.148229};
static double ho_5_5 [3]= {1.718 , 0.837, 0.157023};
static double ho_5_6 [3]= {1.698 , 0.811, 0.182048};
static double ho_8_8 [3]= {1.83314, 1.544, 0.140667};
static double ho_8_9 [3]= {1.79818, 1.498, 0.161712};
static double ho_8_10[3]= {1.84114, 1.513, 0.158419};
// Modified harmonic-oscillator model (MHO): a, alfa, rho0(calculated)
static double mho_6_7[3]= {1.6359, 1.40316, 0.171761};
static double mho_6_8[3]= {1.734 , 1.3812 , 0.156987};
// show MI złe rms-y
static double mi_1_0[4]= {0.86212 , 0.36 , 1.18 ,1};
static double mi_1_1[4]= {2.1166 , 0.21 , 0.77 ,1};
static double mi_2_1[4]= {1.976 , 0.45 , 1.92 ,1};
static double mi_2_2[4]= {1.67114 , 0.51 , 2.01 ,1};
// Two-parameter Fermi model: c=a , z=alfa, rho0(calculated)
static double _2pF_9_10 [3]= {2.58 ,0.567 ,0.178781};
static double _2pF_10_10[3]= {2.740 ,0.572 ,0.162248};
static double _2pF_10_12[3]= {2.782 ,0.549 ,0.176167};
static double _2pF_12_12[3]= {2.98 ,0.55132,0.161818};
static double _2pF_12_14[3]= {3.05 ,0.523 ,0.16955 };
static double _2pF_13_14[3]= {2.84 ,0.569 ,0.201502};
static double _2pF_18_18[3]= {3.54 ,0.507 ,0.161114};
static double _2pF_18_22[3]= {3.53 ,0.542 ,0.176112};
static double _2pF_22_26[3]= {3.84315,0.5885 ,0.163935};
static double _2pF_23_28[3]= {3.94 ,0.505 ,0.17129 };
static double _2pF_24_26[3]= {3.941 ,0.5665 ,0.161978};
static double _2pF_24_28[3]= {4.01015,0.5785 ,0.159698};
static double _2pF_24_29[3]= {4.000 ,0.557 ,0.165941};
static double _2pF_25_30[3]= {3.8912 ,0.567 ,0.184036};
static double _2pF_26_28[3]= {4.074 ,0.536 ,0.162833};
static double _2pF_26_30[3]= {4.111 ,0.558 ,0.162816};
static double _2pF_26_32[3]= {4.027 ,0.576 ,0.176406};
static double _2pF_27_32[3]= {4.158 ,0.575 ,0.164824};
static double _2pF_29_34[3]= {4.218 ,0.596 ,0.167424};
static double _2pF_29_36[3]= {4.252 ,0.589 ,0.169715};
static double _2pF_30_34[3]= {4.285 ,0.584 ,0.164109};
static double _2pF_30_36[3]= {4.340 ,0.559 ,0.165627};
static double _2pF_30_38[3]= {4.393 ,0.544 ,0.166314};
static double _2pF_30_40[3]= {4.426 ,0.551 ,0.167171};
static double _2pF_32_38[3]= {4.442 ,0.5857 ,0.162741};
static double _2pF_32_40[3]= {4.452 ,0.5737 ,0.167365};
static double _2pF_38_50[3]= {4.83 ,0.49611,0.168863};
static double _2pF_39_50[3]= {4.76 ,0.57129,0.172486};
static double _2pF_41_52[3]= {4.875 ,0.57329,0.168620};
static double _2pF_79_118[3]={6.386 ,0.53527, 0.168879};
static double _2pF_Th232a[3]={6.7915 ,0.57115, 0.165272};
static double _2pF_Th232b[3]={6.851 ,0.518 , 0.163042};
static double _2pF_U238a[3]= {6.8054 ,0.60516, 0.167221};
static double _2pF_U238b[3]= {6.874 ,0.556 , 0.164318};
// Three-parameter Fermi model: c=a , z=alfa, w, rho0 (calculated)
static double _3pF_7_7[4]= {2.57000 ,0.5052 ,-0.18070 ,0.0127921 };
static double _3pF_7_8[4]= {2.33430 ,0.4985 , 0.13930 ,0.011046 };
static double _3pF_12_12a[4]={3.10833 ,0.6079 ,-0.16330 ,0.00707021};
static double _3pF_12_12b[4]={3.19234 ,0.6046 ,-0.24920 ,0.00742766};
static double _3pF_12_13[4]= {3.22500 ,0.5840 ,-0.23634 ,0.00714492};
static double _3pF_14_14[4]= {3.34090 ,0.5803 ,-0.23390 ,0.00646414};
static double _3pF_14_15[4]= {3.33812 ,0.5472 ,-0.20312 ,0.00631729};
static double _3pF_14_16[4]= {3.25221 ,0.5532 ,-0.07822 ,0.00585623};
static double _3pF_15_16[4]= {3.36925 ,0.5826 ,-0.17324 ,0.00584405};
static double _3pF_17_18[4]= {3.47632 ,0.5995 ,-0.102 ,0.00489787};
static double _3pF_17_20[4]= {3.55427 ,0.5885 ,-0.132 ,0.0048052 };
static double _3pF_19_20[4]= {3.74325 ,0.5856 ,-0.2012 ,0.00451813};
static double _3pF_20_20[4]= {3.76623 ,0.5865 ,-0.16123 ,0.00424562};
static double _3pF_20_28[4]= {3.7369 ,0.5245 ,-0.030 ,0.00393303};
static double _3pF_28_30[4]= {4.3092 ,0.5169 ,-0.1308 ,0.00291728};
static double _3pF_28_32[4]= {4.4891 ,0.5369 ,-0.2668 ,0.00293736};
static double _3pF_28_33[4]= {4.4024 ,0.5401 ,-0.1983 ,0.00290083};
static double _3pF_28_34[4]= {4.4425 ,0.5386 ,-0.2090 ,0.0028575 };
static double _3pF_28_36[4]= {4.5211 ,0.5278 ,-0.2284 ,0.00277699};
// Three-parameter Gaussian model: c=a, z=alfa, w , rho0 (calculated)
static double _3pG_16_16[4]= {2.549 ,2.1911 ,0.16112 ,0.00700992};
static double _3pG_40_50[4]= {4.434 ,2.5283 ,0.35025 ,0.00184643};
static double _3pG_40_51[4]= {4.32520 ,2.5813 ,0.43325 ,0.00181638};
static double _3pG_40_52[4]= {4.45520 ,2.5503 ,0.33425 ,0.00183439};
static double _3pG_40_54[4]= {4.49420 ,2.5853 ,0.29625 ,0.00182715};
static double _3pG_40_56[4]= {4.50320 ,2.6023 ,0.34125 ,0.00175563};
static double _3pG_42_50[4]= {4.6110 ,2.527 ,0.1911 ,0.0018786 };
//H3(1,2)Be84
static double fb_1_2[18]={3.5, 0.25182e-1, 0.34215e-1, 0.15257e-1,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0};
//He3(2,1)Re84bs
static double fb_2_1[18]={5, 0.20020e-1, 0.41934e-1, 0.36254e-1, 0.17941e-1, 0.46608e-2,
0.46834e-2, 0.52042e-2, 0.38280e-2, 0.25661e-2, 0.14182e-2,
0.61390e-3, 0.22929e-3};
//C12(6,6)Ca80
static double fb_6_6a[18]={8.0, 0.15721e-1, 0.38732e-1, 0.36808e-1, 0.14671e-1,-0.43277e-2,
-0.97752e-2,-0.68908e-2,-0.27631e-2,-0.63568e-3, 0.71809e-5,
0.18441e-3, 0.75066e-4, 0.51069e-4, 0.14308e-4, 0.23170e-5,
0.68465e-6, 0};
//C12(6,6)Re82
static double fb_6_6b[18]={8.0, 0.15737e-1, 0.38897e-1, 0.37085e-1, 0.14795e-1,-0.44831e-2,
-0.10057e-1,-0.68696e-2,-0.28813e-2,-0.77229e-3, 0.66908e-4,
0.10636e-3,-0.36864e-4,-0.50135e-5, 0.94550e-5,-0.47687e-5,
0, 0};
//N15(7,8)Vr86
static double fb_7_8[18]={7.0, 0.25491e-1, 0.50618e-1, 0.29822e-1, -0.55196e-2, -0.15913e-1,
-0.76184e-2,-0.23992e-2,-0.47940e-3, 0, 0,
0, 0, 0, 0, 0,
0, 0};
//O16(8,8)La82
static double fb_8_8[18]= {8.0, 0.20238e-1, 0.44793e-1, 0.33533e-1, 0.35030e-2,-0.12293e-1,
-0.10329e-1,-0.34036e-2,-0.41627e-3,-0.94435e-3,-0.25771e-3,
0.23759e-3,-0.10603e-3, 0.41480e-4, 0,0,
0, 0};
//Al27(13,14)Ro86
static double fb_13_14[18]={7.0, 0.43418e-1, 0.60298e-1, 0.28950e-2,-0.23522e-1,-0.79791e-2,
0.23010e-2, 0.10794e-2, 0.12574e-3,-0.13021e-3, 0.56563e-4,
-0.18011e-4, 0.42869e-5, 0, 0, 0,
0,0};
//Si28(14,14)Mi82
static double fb_14_14[18]={8.0, 0.33495e-1, 0.59533e-1, 0.20979e-1,-0.16900e-1,-0.14998e-1,
-0.93248e-3, 0.33266e-2, 0.59244e-3,-0.40013e-3, 0.12242e-3,
-0.12994e-4,-0.92784e-5, 0.72595e-5,-0.42096e-5, 0,
0, 0};
//Si29(14,15)Mi82
static double fb_14_15[18]={8.0, 0.33521e-1, 0.59679e-1, 0.20593e-1,-0.18646e-1,-0.1655e-1,
-0.11922e-2, 0.28025e-2,-0.67353e-4,-0.34619e-3, 0.17611e-3,
-0.57173e-5, 0.12371e-4, 0, 0, 0,
0, 0};
//Si30(14,16)Mi82
static double fb_14_16[18]={8.5, 0.28397e-1, 0.54163e-1, 0.25167e-1,-0.12858e-1,-0.17592e-1,
-0.46722e-2, 0.24804e-2, 0.14760e-2,-0.30168e-3, 0.48346e-4,
0.00000e0, -0.51570e-5, 0.30261e-5, 0, 0,
0, 0};
//P31(15,16)Mi82
static double fb_15_16[18]={8.0, 0.35305e-1, 0.59642e-1, 0.17274e-1,-0.19303e-1,-0.13545e-1,
0.63209e-3, 0.35462e-2, 0.83653e-3,-0.47904e-3, 0.19099e-3,
-0.69611e-4, 0.23196e-4, -0.77780e-5,0,0,
0,0};
//S32(16,16)Ry83b
static double fb_16_16[18]={8.0, 0.37251e-1, 0.60248e-1, 0.14748e-1,-0.18352e-1,-0.10347e-1,
0.30461e-2, 0.35277e-2,-0.39834e-4,-0.97177e-4, 0.92279e-4,
-0.51931e-4, 0.22958e-4,-0.86609e-5, 0.28879e-5,-0.86632e-6,
0, 0};
//S34(16,18)Ry83b
static double fb_16_18[18]={8,0.37036e-1, 0.58506e-1, 0.12082e-1,-0.19022e-1,-0.83421e-2,
0.45434e-2, 0.28346e-2,-0.52304e-3, 0.27754e-4, 0.59403e-4,
-0.42794e-4, 0.20407e-4,-0.79934e-5, 0.27354e-5,-0.83914e-6,
0, 0};
//S36(16,29)Ry83b
static double fb_16_20[18]={8,0.37032e-1, 0.57939e-1, 0.10049e-1,-0.19852e-1,-0.67176e-2,
0.61882e-2, 0.37795e-2,-0.55272e-3,-0.12904e-3, 0.15845e-3,
-0.84063e-4, 0.34010e-4,-0.11663e-4, 0.35204e-5, 0.95135e-6,
0, 0};
//Ar40(18,22)Ot82
static double fb_18_22[18]={9.0, 0.30451e-1, 0.55337e-1, 0.20203e-1,-0.16765e-1,-0.13578e-1,
-0.43204e-4, 0.91988e-3,-0.41205e-3, 0.11971e-3,-0.19801e-4,
-0.43204e-5, 0.61205e-5,-0.37803e-5, 0.18001e-5,-0.77407e-6,
0, 0};
//Ca40(20,20)Em83b
static double fb_20_20[18]={8.0, 0.44846e-1, 0.61326e-1,-0.16818e-2,-0.26217e-1,-0.29725e-2,
0.85534e-2, 0.35322e-2,-0.48258e-3,-0.39346e-3, 0.20338e-3,
0.25461e-4,-0.17794e-4, 0.67394e-5,-0.21033e-5, 0,
0,0};
//Ca48(20,24)Em83b
static double fb_20_24[18]={8.0, 0.44782e-1, 0.59523e-1,-0.74148e-2,-0.29466e-1,-0.28350e-3,
0.10829e-1, 0.30465e-2,-0.10237e-2,-0.17830e-3, 0.55391e-4,
-0.22644e-4, 0.82671e-5,-0.27343e-5, 0.82461e-6,-0.22780e-6,
0,0};
//Ti48(22,26)Se85
static double fb_22_26[18]={10.0, 0.27850e-1, 0.55432e-1, 0.26369e-1,-0.17091e-1,-0.21798e-1,
-0.24889e-2, 0.76631e-2, 0.34554e-2,-0.67477e-3, 0.10764e-3,
-0.16564e-5,-0.55566e-5, 0, 0, 0,
0, 0};
//Ti48(22,28)Se85
static double fb_22_28[18]={9.5, 0.31818e-1, 0.58556e-1, 0.19637e-1,-0.24309e-1,-0.18748e-1,
0.33741e-2, 0.89961e-2, 0.37954e-2,-0.41238e-3, 0.12540e-3,
0, 0, 0, 0, 0,
0, 0};
//Cr50(24,26)Li83c
static double fb_24_26[18]={9.0, 0.39174e-1, 0.61822e-1, 0.68550e-2,-0.30170e-1,-0.98745e-2,
0.87944e-2, 0.68502e-2,-0.93609e-3,-0.24962e-2,-0.15361e-2,
-0.73687e-3, 0,0,0,0,
0,0};
//Cr52(24,28)Li83c
static double fb_24_28[18]={9.0, 0.39287e-1, 0.62477e-1, 0.62482e-2,-0.32885e-1,-0.10648e-1,
0.10520e-1, 0.85478e-2,-0.24003e-3,-0.20499e-2,-0.12001e-2,
-0.56649e-3, 0 ,0 ,0,0,
0,0};
//Cr54(24,30)Li83c
static double fb_24_30[18]={9.0, 0.39002e-1, 0.60305e-1, 0.45845e-2,-0.30723e-1,-0.91355e-2,
0.93251e-2, 0.60583e-2,-0.15602e-2,-0.76809e-3, 0.76809e-3,
-0.34804e-3, 0, 0, 0, 0,
0, 0};
//Fe54(26,28)Wo76
static double fb_26_28[18]={9.0, 0.42339e-1, 0.64428e-1, 0.15840e-2,-0.35171e-1,-0.10116e-1,
0.12069e-1, 0.62230e-2,-0.12045e-2, 0.13561e-3, 0.10428e-4,
-0.16980e-4, 0.91817e-5,-0.39988e-5, 0.15731e-5,-0.57862e-6,
0.20186e-6,-0.67892e-7};
//Fe56(26,30)Wo76
static double fb_26_30[18]={9.0, 0.42018e-1, 0.62337e-1, 0.23995e-3,-0.32776e-1,-0.79941e-2,
0.10844e-1, 0.49123e-2,-0.22144e-2,-0.18146e-3, 0.37261e-3,
-0.23296e-3, 0.11494e-3,-0.50596e-4, 0.20652e-4,-0.79428e-5,
0.28986e-5,-0.10075e-5};
//Fe58(26,32)Wo76
static double fb_26_32[18]={9.0, 0.41791e-1, 0.60524e-1,-0.14978e-2,-0.31183e-1,-0.58013e-2,
0.10611e-1, 0.41629e-2,-0.29045e-5, 0.54106e-3,-0.38689e-3,
0.20514e-3,-0.95237e-4, 0.40707e-4,-0.16346e-1, 0.62233e-5,
-0.22568e-5, 0.78077e-6};
//Co59(27,32)Sc77
static double fb_27_32[18]={9.0, 0.43133e-1, 0.61249e-1,-0.32523e-2,-0.32681e-1,-0.49583e-2,
0.11494e-1, 0.55428e-2, 0.31398e-3,-0.70578e-4, 0.53725e-5,
-0.74650e-6, 0.19793e-5,-0.28059e-5, 0.27183e-5,-0.19454e-5,
0.10963e-5,-0.51114e-6};
//Ni58(28,30)Be83
static double fb_28_30a[18]={9.0, 0.44880e-1, 0.64756e-1,-0.27899e-2,-0.37016e-1,-0.71915e-2,
0.13594e-1, 0.66331e-2,-0.14095e-2,-0.10141e-2, 0.38616e-3,
-0.13871e-3, 0.47788e-4,-0.15295e-4, 0.59131e-5,-0.67880e-5,
0,0};
//Ni58(28,30)Wo76
static double fb_28_30b[18]={9.0, 0.45030e-1, 0.65044e-1,-0.32843e-2,-0.36241e-1,-0.67442e-2,
0.13146e-1, 0.50903e-2,-0.20787e-2, 0.12901e-3, 0.14828e-3,
-0.11530e-3, 0.60881e-4,-0.27676e-4, 0.11506e-4, 0.44764e-5,
0.16468e-5,-0.57496e-6};
//Ni60(28,32)Be83
static double fb_28_32a[18]={9.0, 0.44668e-1, 0.63072e-1,-0.42797e-2,-0.34806e-1,-0.48625e-2,
0.12794e-1, 0.54401e-2,-0.14075e-2,-0.76976e-3, 0.33487e-3,
-0.13141e-3, 0.52132e-4,-0.20394e-4, 0.59131e-5,-0.67880e-5,
0,0};
//Ni60(28,32)Wo76
static double fb_28_32b[18]={9.0, 0.44855e-1, 0.63476e-1,-0.51001e-2,-0.34496e-1,-0.43132e-2,
0.12767e-1, 0.49935e-2,-0.92940e-3, 0.28281e-3,-0.76557e-4,
0.18677e-4, 0.36855e-5,-0.32276e-6, 0.19843e-6, 0.16275e-6,
-0.82891e-7,-0.34896e-7};
//Ni60(28,32)Wo80
static double fb_28_32c[18]={9.0, 0.44142e-1, 0.62987e-1,-0.49864e-2,-0.34306e-1,-0.44060e-2,
0.12810e-1, 0.46914e-2,-0.84373e-3, 0.36928e-3,-0.15003e-3,
0.59665e-4,-0.23215e-4, 0.88005e-5,-0.32305e-5, 0.11496e-5,
-0.39658e-6, 0.13145e-6};
//Ni62(28,34)Wo76
static double fb_28_34[18]={9.0, 0.44581e-1, 0.61478e-1,-0.69425e-2,-0.33126e-1,-0.24964e-2,
0.12674e-1, 0.37148e-2,-0.20881e-2, 0.30193e-3, 0.57573e-4,
-0.77965e-4, 0.46906e-4,-0.22724e-4, 0.98243e-5,-0.39250e-5,
0.14732e-5, 0.52344e-6};
//Ni64(28,36)Wo76
static double fb_28_36[18]={9.0, 0.44429e-1, 0.60116e-1,-0.92003e-2,-0.33452e-1,-0.52856e-3,
0.13156e-1, 0.35152e-2,-0.21671e-2, 0.46497e-4, 0.25366e-3,
-0.18438e-2, 0.96874e-4,-0.44224e-4, 0.18493e-4,-0.72361e-5,
-0.72361e-5,-0.93929e-6};
//Cu63(29,34)Sc77
static double fb_29_34[18]={9.0, 0.45598e-1, 0.60706e-1,-0.78616e-2,-0.31638e-1,-0.14447e-2,
0.10953e-1, 0.42578e-2,-0.24224e-3,-0.30067e-3, 0.23903e-3,
-0.12910e-3, 0.60195e-4,-0.25755e-4, 0.10332e-4,-0.39330e-5,
0.14254e-5,-0.49221e-6};
//Cu65(29,36)Sc77
static double fb_29_36[18]={9.0, 0.45444e-1, 0.59544e-1,-0.94968e-2,-0.31561e-1, 0.22898e-3,
0.11189e-1, 0.37360e-2,-0.64873e-3,-0.51133e-3, 0.43765e-3,
-0.24276e-3, 0.11507e-3, 0.11507e-3, 0.20140e-4,-0.76945e-5,
0.28055e-5,-0.97411e-6};
//Zn64(30,34)Wo76
static double fb_30_34[18]={9.0, 0.47038e-1, 0.61536e-1, 0.90045e-2,-0.30669e-1,-0.78705e-3,
0.10034e-1, 0.14053e-2,-0.20640e-2, 0.35105e-3, 0.27303e-4,
-0.63811e-4, 0.40893e-4,-0.20311e-4, 0.88986e-5,-0.35849e-5,
0.13522e-5,-0.38635e-6};
//Zn66(30,36)Wo76
static double fb_30_36[18]={9.0, 0.46991e-1, 0.60995e-1,-0.96693e-2,-0.30457e-1,-0.53435e-3,
0.97083e-2, 0.14091e-2,-0.70813e-3, 0.20809e-3,-0.48275e-4,
0.12680e-5, 0.91369e-6,-0.14874e-5, 0.88831e-6,-0.41689e-6,
0.17283e-6,-0.65968e-7};
//Zn68(30,38)Wo76
static double fb_30_38[18]={9.0, 0.46654e-1, 0.58827e-1,-0.12283e-1,-0.29865e-1, 0.25669e-2,
0.10235e-1, 0.31861e-2,-0.17351e-3,-0.42979e-3, 0.33700e-3,
-0.18435e-3, 0.87043e-4,-0.37612e-4, 0.15220e-4,-0.58282e-5,
0.21230e-5,-0.73709e-6};
//Zn70(30,40)Wo76
static double fb_30_40[18]={9.0, 0.46363e-1, 0.57130e-1,-0.13877e-1,-0.30030e-1, 0.35341e-2,
0.10113e-1, 0.41029e-2, 0.76469e-3,-0.10138e-2, 0.60837e-3,
-0.29929e-3, 0.13329e-3,-0.55502e-4, 0.21893e-4,-0.82286e-5,
0.29559e-5,-0.10148e-5};
//Ge70(32,38)Ma84
static double fb_32_38[18]={10.0, 0.38182e-1, 0.60306e-1, 0.64346e-2,-0.29427e-1,-0.95888e-2,
0.87849e-2, 0.49187e-2,-0.15189e-2,-0.17385e-2,-0.16794e-3,
-0.11746e-3, 0.65768e-4,-0.30691e-4, 0.13051e-5,-0.52251e-5,
0,0};
//Ge72(32,40)Ma84
static double fb_32_40[18]={10.0, 0.38083e-1, 0.59342e-1, 0.47718e-2,-0.29953e-1,-0.88476e-2,
0.96205e-2, 0.47901e-2,-0.16869e-2,-0.15406e-2,-0.97230e-4,
-0.47640e-4,-0.15669e-5, 0.67076e-5,-0.44500e-5, 0.22158e-5,
0,0};
//Ge74(32,42)Ma84
static double fb_32_42[18]={10, 0.37989e-1, 0.58298e-1, 0.27406e-2,-0.30666e-1,-0.81505e-2,
0.10231e-1, 0.49382e-2,-0.16270e-2,-0.13937e-2, 0.15476e-3,
0.14396e-3,-0.73075e-4, 0.31998e-4,-0.12822e-4, 0.48406e-5,
0, 0};
//Ge76(32,44)Ma84
static double fb_32_44[18]={10, 0.37951e-1, 0.57876e-1, 0.15303e-2,-0.31822e-1,-0.76875e-2,
0.11237e-1, 0.50780e-2,-0.17293e-2,-0.15523e-2, 0.72439e-4,
0.16560e-3,-0.86631e-4, 0.39159e-4,-0.16259e-4, 0.63681e-5,
0, 0};
//Sr88(38,40)St76
static double fb_38_40[18]={9.0, 0.56435e-1, 0.55072e-1,-0.33363e-1,-0.26061e-1, 0.15749e-1,
0.75233e-2,-0.55044e-2,-0.23643e-2, 0.39362e-3,-0.22733e-3,
0.12519e-3,-0.61176e-4, 0.27243e-4,-0.11285e-4, 0.43997e-5,
-0.16248e-5, 0.57053e-6};
//Zr90(40,50)Ro76
static double fb_40_50[18]={10.0, 0.46188e-1, 0.61795e-1,-0.12315e-1,-0.36915e-1, 0.25175e-2,
0.15234e-1,-0.55146e-3,-0.60631e-2,-0.12198e-2, 0.36200e-3,
-0.16466e-3, 0.53305e-4,-0.50873e-5,-0.85658e-5, 0.86095e-5,
0,0};
//Zr92(40,52)Ro76
static double fb_40_52[18]={10.0, 0.45939e-1, 0.60104e-1,-0.13341e-1,-0.35106e-1, 0.31760e-2,
0.13753e-1,-0.82682e-3,-0.53001e-2,-0.97579e-3, 0.26489e-3,
-0.15873e-3, 0.69301e-4,-0.22278e-4, 0.39533e-5, 0.10609e-5,
0,0};
//Zr94(40,54)Ro76
static double fb_40_54[18]={10.0, 0.45798e-1 ,0.59245e-1,-0.13389e-1,-0.33252e-1, 0.39888e-2,
0.12750e-1,-0.15793e-2,-0.56692e-2,-0.15698e-2, 0.54394e-4,
-0.24032e-4, 0.38401e-4,-0.31690e-4, 0.18481e-4,-0.85367e-5,
0,0};
//Mo92(42,50)La86
static double fb_42_50[18]={12.0, 0.30782e-1, 0.59896e-1, 0.22016e-1,-0.28945e-1,-0.26707e-1,
0.40426e-2, 0.14429e-1, 0.31696e-2,-0.63061e-2,-0.45119e-2,
0.46236e-3, 0.94909e-3,-0.38930e-3,-0.14808e-3, 0.19622e-3,
-0.40197e-4,-0.71949e-4};
//Mo94(42,52)La86
static double fb_42_52[18]={12, 0.30661e-1, 0.58828e-1, 0.20396e-1,-0.28830e-1,-0.25077e-1,
0.44768e-2, 0.13127e-1, 0.19548e-2,-0.61403e-2,-0.35825e-2,
0.73790e-3, 0.61882e-3,-0.40556e-3,-0.55748e-5,-0.12453e-3,
-0.57812e-4,-0.21657e-4};
//Mo96(42,54)La86
static double fb_42_54[18]={12, 0.30564e-1, 0.58013e-1, 0.19255e-1,-0.28372e-1,-0.23304e-1,
0.49894e-2, 0.12126e-1, 0.10496e-2,-0.62592e-2,-0.32814e-2,
0.89668e-3, 0.50636e-3,-0.43412e-3, 0.71531e-4, 0.76745e-4,
-0.54316e-4, 0.23386e-6};
//Mo98(42,56)Dr75
static double fb_42_56[18]={12, 0.30483e-1, 0.57207e-1, 0.17888e-1,-0.28388e-1,-0.21778e-1,
0.56780e-2, 0.11236e-1, 0.82176e-3,-0.50390e-2,-0.23877e-2,
0.71492e-3, 0.29839e-3,-0.31408e-3, 0.80177e-3, 0.43682e-4,
-0.51394e-4, 0.22293e-4};
//Mo100(42,58)Dr75
static double fb_42_58[18]={12, 0.30353e-1, 0.56087e-1, 0.16057e-1,-0.28767e-1,-0.20683e-1,
0.62429e-2, 0.11058e-1, 0.11502e-2,-0.39395e-2,-0.14978e-2,
0.76350e-3, 0.10554e-3,-0.25658e-3, 0.10964e-3, 0.10015e-4,
-0.40341e-4, 0.25744e-4};
//Pd104(46,58)La86
static double fb_46_58[18]={11, 0.41210e-1, 0.62846e-1,-0.21202e-2,-0.38359e-1,-0.44693e-2,
0.16656e-1, 0.36873e-2,-0.57534e-2,-0.32499e-2, 0.69844e-3,
0.16304e-2, 0.59882e-3, 0, 0, 0,
0, 0};
//Pd106(46,60)La86
static double fb_46_60[18]={11, 0.41056e-1, 0.61757e-1,-0.29891e-2,-0.37356e-1,-0.35348e-2,
0.16085e-1, 0.28502e-2,-0.55764e-2,-0.15433e-2, 0.22281e-2,
0.13160e-2, 0.16508e-4, 0, 0, 0,
0,0};
//Pd108(46,62)La86
static double fb_46_62[18]={11, 0.40754e-1, 0.59460e-1,-0.54077e-2,-0.36305e-1,-0.21987e-2,
0.15418e-1, 0.25927e-2,-0.52781e-2,-0.19757e-2, 0.10339e-2,
0.22891e-3,-0.33464e-3,0, 0, 0,
0, 0};
//Pd110(46,64)La86
static double fb_46_64[18]={11.0,0.40668e-1, 0.58793e-1,-0.61375e-2,-0.35983e-1,-0.17447e-2,
0.14998e-1, 0.19994e-2,-0.53170e-2,-0.14289e-2, 0.16033e-2,
0.31574e-3,-0.42195e-3,0,0,0,
0,0};
//Sm144(62,82)Mo81
static double fb_62_82[18]={9.25,0.74734e-1, 0.26145e-1,-0.63832e-1, 0.10432e-1, 0.19183e-1,
-0.12572e-1,-0.39707e-2,-0.18703e-2, 0.12602e-2,-0.11902e-2,
-0.15703e-2,0,0,0,0,
0,0};
//Sm148(62,86)Ho80
static double fb_62_86a[18]={9.5, 0.70491e-1, 0.32601e-1,-0.55421e-1, 0.50111e-2, 0.20216e-1,
-0.85944e-2,-0.40106e-2, 0.19303e-2,-0.49689e-3,-0.17040e-3,
0,0,0,0,0,
0,0};
//Sm148(62,86)Mo81
static double fb_62_86b[18]={9.25,0.73859e-1, 0.24023e-1,-0.59437e-1, 0.10761e-1, 0.17022e-1,
-0.11401e-1,-0.18102e-2, 0.93011e-3, 0.98012e-3,-0.12601e-2,
-0.17402e-2,0,0,0,0,
0,0};
//Sm150(62,88)Mo81
static double fb_62_88[18]={9.25,0.73338e-1, 0.24626e-1,-0.52773e-1, 0.10582e-1, 0.15353e-1,
-0.95624e-2,-0.18804e-2,-0.79019e-3, 0.10102e-2,-0.26606e-2,
-0.18304e-2,0,0,0,0,
0,0};
//Sm152(62,90)Ho80
static double fb_62_90a[18]={10.5,0.56097e-1, 0.45123e-1,-0.40310e-1,-0.18171e-1, 0.20515e-1,
0.49023e-2,-0.67674e-2,-0.18927e-2, 0.15333e-2, 0,
0,0,0,0,0,
0,0};
//Sm152(62,90)Mo81
static double fb_62_90b[18]={9.25,0.72646e-1, 0.21824e-1,-0.54112e-1, 0.98321e-2, 0.16213e-1,
-0.65614e-2, 0.53611e-2,-0.14103e-2,-0.99022e-3,-0.23005e-2,
0,0,0,0,0,
0,0};
//Sm154(62,92)Ho80
static double fb_62_92[18]={10.5,0.55859e-1, 0.44002e-1,-0.40342e-1,-0.17989e-1, 0.19817e-1,
0.51643e-2,-0.60212e-2,-0.23127e-2, 0.47024e-3, 0,
0,0,0,0,0,
0,0};
//Gd154(64,90)He82
static double fb_64_90[18]={10.0,0.63832e-1, 0.36983e-1,-0.48193e-1,-0.51046e-2, 0.19805e-1,
-0.82574e-3,-0.46942e-2,0,0,0,
0,0,0,0,0,
0,0};
//Gd158(64,94)Mu84
static double fb_64_94[18]={10.5,0.57217e-1, 0.43061e-1,-0.41996e-1,-0.17203e-1, 0.19933e-1,
0.51060e-2,-0.73665e-2,-0.20926e-2, 0.21883e-2,0,
0,0,0,0,0,
0,0};
//Er166(68,98)Ca78
static double fb_68_98[18]={11.0,0.54426e-1, 0.47165e-1,-0.38654e-1,-0.19672e-1, 0.22092e-1,
0.78708e-2,-0.53005e-2, 0.50005e-3, 0.52005e-3,-0.35003e-3,
0.12001e-3,0,0,0,0,
0,0};
//Yb174(70,104)Sa79
static double fb_70_104[18]={11.0,0.54440e-1, 0.40034e-1,-0.45606e-1,-0.20932e-1, 0.20455e-1,
0.27061e-2,-0.60489e-2,-0.15918e-3, 0.11938e-2, 0,
0,0,0,0,0,
0,0};
//Lu175(71,104)Sa79
static double fb_71_104[18]={11.0,0.55609e-1, 0.42243e-1,-0.45028e-1,-0.19491e-1, 0.22514e-1,
0.38982e-2,-0.72395e-2, 0.31822e-3,-0.23866e-3,0,
0,0,0,0,0,
0,0};
//Os192(76,116)Re84
static double fb_76_116[18]={11.0,0.59041e-1, 0.41498e-1,-0.49900e-1,-0.10183e-1, 0.29067e-1,
-0.57382e-2,-0.92348e-2, 0.36170e-2, 0.28736e-2, 0.24194e-3,
-0.16766e-2, 0.73610e-3, 0,0,0,
0,0};
//Pt196(78,118)Bo83
static double fb_78_118[18]={12.0,0.50218e-1, 0.53722e-1,-0.35015e-1,-0.34588e-1, 0.23564e-1,
0.14340e-1,-0.13270e-1,-0.51212e-2, 0.56088e-2, 0.14890e-2,
-0.10928e-2, 0.55662e-3,-0.50557e-4,-0.19708e-3, 0.24016e-3,
0,0};
//Tl203(81,122)Eu78
static double fb_81_122[18]={12.0,0.51568e-1, 0.51562e-1,-0.39299e-1,-0.30826e-1, 0.27491e-1,
0.10795e-1,-0.15922e-1,-0.25527e-2, 0.58548e-2, 0.19324e-3,
-0.17925e-3, 0.14307e-3,-0.91669e-4, 0.53497e-4,-0.29492e-4,
0.15625e-4,-0.80141e-5};
//Tl205(81,124)Eu78
static double fb_81_124[18]={12.0,0.51518e-1, 0.51165e-1,-0.39559e-1,-0.30118e-1, 0.27600e-1,
0.10412e-1,-0.15725e-1,-0.26546e-2, 0.70184e-2, 0.82116e-3,
-0.51805e-3, 0.32560e-3,-0.18670e-3, 0.10202e-3,-0.53857e-4,
0.27672e-4,-0.13873e-4};
//Pb204(82,122)Eu78
static double fb_82_122[18]={12.0,0.52102e-1, 0.51786e-1,-0.39188e-1,-0.29242e-1, 0.28992e-1,
0.11040e-1,-0.14591e-1,-0.94917e-3, 0.71349e-2, 0.24780e-3,
-0.61656e-3, 0.42335e-3,-0.25250e-3, 0.14106e-3,-0.75446e-4,
0.39143e-4,-0.19760e-4};
//Pb206(82,124)Eu78
static double fb_82_124[18]={12.0,0.52019e-1, 0.51190e-1,-0.39459e-1,-0.28405e-1, 0.28862e-1,
0.10685e-1,-0.14550e-1,-0.13519e-2, 0.77624e-2,-0.41882e-4,
-0.97010e-3, 0.69611e-3,-0.42410e-3, 0.23857e-3,-0.12828e-3,
0.66663e-4,-0.33718e-4};
//Pb207(82,125)Eu78
static double fb_82_125[18]={12.0,0.51981e-1, 0.51059e-1,-0.39447e-1,-0.28428e-1, 0.28988e-1,
0.10329e-1,-0.14029e-1,-0.46728e-3, 0.67984e-2, 0.56905e-3,
-0.50430e-3, 0.32796e-3,-0.19157e-3, 0.10565e-3,-0.56200e-4,
0.29020e-4,-0.14621e-4};
//Pb208(82,126)Eu78
static double fb_82_126a[18]={12.0,0.51936e-1, 0.50768e-1,-0.39646e-1,-0.28218e-1, 0.28916e-1,
0.98910e-2,-0.14388e-1,-0.98262e-3, 0.72578e-2, 0.82318e-3,
-0.14823e-2, 0.13245e-3,-0.84345e-4, 0.48417e-4,-0.26562e-4,
0.14035e-4,-0.71863e-5};
//Pb208(82,126)Fr77b
static double fb_82_126b[18]={11.0,0.62732e-1, 0.38542e-1,-0.55105e-1,-0.26990e-2, 0.31016e-1,
-0.99486e-2,-0.93012e-2, 0.76653e-2, 0.20885e-2,-0.17840e-2,
-0.74876e-4, 0.32278e-3,-0.11353e-3,0,0,
0,0};
//Bi209(83,126)Eu78
static double fb_83_126[18]={12.0,0.52448e-1, 0.50400e-1,-0.41014e-1,-0.27927e-1, 0.29587e-1,
0.98017e-2,-0.14930e-1,-0.31967e-3, 0.77252e-2, 0.57533e-3,
-0.82529e-3, 0.25728e-3,-0.11043e-3, 0.51930e-4,-0.24767e-4,
0.11863e-4,-0.56554e-5};
// Sum Of Gausians { rms, RP, R1, Q1,R2, Q2, ...,R12 ,Q12}
//H3(1,2)Ju85s
static double sog_1_2[26]=
{
1.764,0.80,
0.0, 0.035952,
0.2, 0.027778,
0.5, 0.131291,
0.8, 0.221551,
1.2, 0.253691,
1.6, 0.072905,
2.0, 0.152243,
2.5, 0.051564,
3.0, 0.053023,
0,0,
0,0,
0,0
};
//He3(2,1)MC77
static double sog_2_1[26]=
{
1.835, 1.10,
0.0, 0.000029,
0.6, 0.606482,
1.0, 0.066077,
1.3, 0.000023,
1.8, 0.204417,
2.3, 0.115236,
2.7, 0.000001,
3.2, 0.006974,
4.1, 0.000765,
0,0,
0,0,
0,0
};
//He4(2,2)Si82
static double sog_2_2[26]=
{
1.6768,1.00,
0.2, 0.034724,
0.6, 0.430761,
0.9, 0.203166,
1.4, 0.192986,
1.9, 0.083866,
2.3, 0.033007,
2.6, 0.014201,
3.1, 0.000000,
3.5, 0.006860,
4.2, 0.000000,
4.9, 0.000438,
5.2, 0.000000
};
//C12(6,6)Si82
static double sog_6_6[26]=
{
2.4696, 1.20,
0.0, 0.016690,
0.4, 0.050325,
1.0, 0.128621,
1.3, 0.180515,
1.7, 0.219097,
2.3, 0.278416,
2.7, 0.058779,
3.5, 0.057817,
4.3, 0.007739,
5.4, 0.002001,
6.7, 0.000007,
0, 0
};
//O16(8,8)Si70b
static double sog_8_8[26]=
{
2.711, 1.30,
0.4, 0.057056,
1.1, 0.195701,
1.9, 0.311188,
2.2, 0.224321,
2.7, 0.059946,
3.3, 0.135714,
4.1, 0.000024,
4.6, 0.013961,
5.3, 0.000007,
5.6, 0.000002,
5.9, 0.002096,
6.4, 0.000002
};
//Mg24(12,12)Li74
static double sog_12_12[26]=
{
3.027, 1.25,
0.1, 0.007372,
0.6, 0.061552,
1.1, 0.056984,
1.5, 0.035187,
1.9, 0.291692,
2.6, 0.228920,
3.2, 0.233532,
4.1, 0.074086,
4.7, 0.000002,
5.2, 0.010876,
6.1, 0.000002,
7.0, 0.000002
};
//Si28(14,14)Li74
static double sog_14_14[26]=
{
3.121, 1.30,
0.4, 0.033149,
1.0, 0.106452,
1.9, 0.206866,
2.4, 0.286391,
3.2, 0.250448,
3.6, 0.056944,
4.1, 0.016829,
4.6, 0.039630,
5.1, 0.000002,
5.5, 0.000938,
6.0, 0.000002,
6.9, 0.002366
};
//S32(16,16)Li74
static double sog_16_16[26]=
{
3.258, 1.35,
0.4, 0.045356,
1.1, 0.067478,
1.7, 0.172560,
2.5, 0.324870,
3.2, 0.254889,
4.0, 0.101799,
4.6, 0.022166,
5.0, 0.002081,
5.5, 0.005616,
6.3, 0.000020,
7.3, 0.000020,
7.7, 0.003219
};
//K39(19,20)Si74
static double sog_19_20[26]=
{
3.427, 1.45,
0.4, 0.043308,
0.9, 0.036283,
1.7, 0.110517,
2.1, 0.147676,
2.6, 0.189541,
3.2, 0.274173,
3.7, 0.117691,
4.2, 0.058273,
4.7, 0.000006,
5.5, 0.021380,
5.9, 0.000002,
6.9, 0.001145
};
//Ca40(20,20)Si79
static double sog_20_20[26]=
{
3.4803, 1.45,
0.4, 0.042870,
1.2, 0.056020,
1.8, 0.167853,
2.7, 0.317962,
3.2, 0.155450,
3.6, 0.161897,
4.3, 0.053763,
4.6, 0.032612,
5.4, 0.004803,
6.3, 0.004541,
6.6, 0.000015,
8.1, 0.002218
};
//Ca48(20,28)Si74
static double sog_20_28[26]=
{
3.460, 1.45,
0.6, 0.063035,
1.1, 0.011672,
1.7, 0.064201,
2.1, 0.203813,
2.9, 0.259070,
3.4, 0.307899,
4.3, 0.080585,
5.2, 0.008498,
5.7, 0.000025,
6.2, 0.000005,
6.5, 0.000004,
7.4, 0.001210
};
//Ni58(28,30)Ca80b
static double sog_28_30[26]=
{
3.7724, 1.45,
0.5, 0.035228,
1.4, 0.065586,
2.2, 0.174552,
3.0, 0.199916,
3.4, 0.232360,
3.9, 0.118496,
4.2, 0.099325,
4.6, 0.029860,
5.2, 0.044912,
5.9, 0.000232,
6.6, 0.000002,
7.9, 0.000010
};
//Sn116(50,66)Ca82a
static double sog_50_66[26]=
{
4.6271, 1.60,
0.1, 0.005727,
0.7, 0.009643,
1.3, 0.038209,
1.8, 0.009466,
2.3, 0.096665,
3.1, 0.097840,
3.8, 0.269373,
4.8, 0.396671,
5.5, 0.026390,
6.1, 0.048157,
7.1, 0.001367,
8.1, 0.000509
};
//Sn124(50,74)Ca82a
static double sog_50_74[26]=
{
4.6771, 1.60,
0.1, 0.004877,
0.7, 0.010685,
1.3, 0.030309,
1.8, 0.015857,
2.3, 0.088927,
3.1, 0.091917,
3.8, 0.257379,
4.8, 0.401877,
5.5, 0.053646,
6.1, 0.043193,
7.1, 0.001319,
8.1, 0.000036
};
//Tl205(81,124)Fr83
static double sog_81_124[26]=
{
5.479, 1.70,
0.6, 0.007818,
1.1, 0.022853,
2.1, 0.000084,
2.6, 0.105635,
3.1, 0.022340,
3.8, 0.059933,
4.4, 0.235874,
5.0, 0.000004,
5.7, 0.460292,
6.8, 0.081621,
7.2, 0.002761,
8.6, 0.000803
};
//Pb206(82,124)Fr83
static double sog_82_124[26]=
{
5.490, 1.70,
0.6, 0.010615,
1.1, 0.021108,
2.1, 0.000060,
2.6, 0.102206,
3.1, 0.023476,
3.8, 0.065884,
4.4, 0.226032,
5.0, 0.000005,
5.7, 0.459690,
6.8, 0.086351,
7.2, 0.004589,
8.6, 0.000011
};
//Pb208(82,126)Fr77a
static double sog_82_126[26]=
{
5.5032, 1.70,
0.1, 0.003845,
0.7, 0.009724,
1.6, 0.033093,
2.1, 0.000120,
2.7, 0.083107,
3.5, 0.080869,
4.2, 0.139957,
5.1, 0.260892,
6.0, 0.336013,
6.6, 0.033637,
7.6, 0.018729,
8.7, 0.000020
};
nucleus_data dens_data[]=
{
nucleus_data( 1, 2, prfFB, fb_1_2 ),
nucleus_data( 2, 1, prfFB, fb_2_1 ),
nucleus_data( 6, 6, prfFB, fb_6_6a ),
nucleus_data( 6, 6, prfFB, fb_6_6b ),
nucleus_data( 7, 8, prfFB, fb_7_8 ),
nucleus_data( 8, 8, prfFB, fb_8_8 ),
nucleus_data(13, 14, prfFB, fb_13_14 ),
nucleus_data(14, 14, prfFB, fb_14_14 ),
nucleus_data(14, 15, prfFB, fb_14_15 ),
nucleus_data(14, 16, prfFB, fb_14_16 ),
nucleus_data(15, 16, prfFB, fb_15_16 ),
nucleus_data(16, 16, prfFB, fb_16_16 ),
nucleus_data(16, 18, prfFB, fb_16_18 ),
nucleus_data(16, 20, prfFB, fb_16_20 ),
nucleus_data(18, 22, prfFB, fb_18_22 ),
nucleus_data(20, 20, prfFB, fb_20_20 ),
nucleus_data(20, 24, prfFB, fb_20_24 ),
nucleus_data(22, 26, prfFB, fb_22_26 ),
nucleus_data(22, 28, prfFB, fb_22_28 ),
nucleus_data(24, 26, prfFB, fb_24_26 ),
nucleus_data(24, 28, prfFB, fb_24_28 ),
nucleus_data(24, 30, prfFB, fb_24_30 ),
nucleus_data(26, 28, prfFB, fb_26_28 ),
nucleus_data(26, 30, prfFB, fb_26_30 ),
nucleus_data(26, 32, prfFB, fb_26_32 ),
nucleus_data(27, 32, prfFB, fb_27_32 ),
nucleus_data(28, 30, prfFB, fb_28_30a ),
nucleus_data(28, 30, prfFB, fb_28_30b ),
nucleus_data(28, 32, prfFB, fb_28_32a ),
nucleus_data(28, 32, prfFB, fb_28_32b ),
nucleus_data(28, 32, prfFB, fb_28_32c ),
nucleus_data(28, 34, prfFB, fb_28_34 ),
nucleus_data(28, 36, prfFB, fb_28_36 ),
nucleus_data(29, 34, prfFB, fb_29_34 ),
nucleus_data(29, 36, prfFB, fb_29_36 ),
nucleus_data(30, 34, prfFB, fb_30_34 ),
nucleus_data(30, 36, prfFB, fb_30_36 ),
nucleus_data(30, 38, prfFB, fb_30_38 ),
nucleus_data(30, 40, prfFB, fb_30_40 ),
nucleus_data(32, 38, prfFB, fb_32_38 ),
nucleus_data(32, 40, prfFB, fb_32_40 ),
nucleus_data(32, 42, prfFB, fb_32_42 ),
nucleus_data(32, 44, prfFB, fb_32_44 ),
nucleus_data(38, 40, prfFB, fb_38_40 ),
nucleus_data(40, 50, prfFB, fb_40_50 ),
nucleus_data(40, 52, prfFB, fb_40_52 ),
nucleus_data(40, 54, prfFB, fb_40_54 ),
nucleus_data(42, 50, prfFB, fb_42_50 ),
nucleus_data(42, 52, prfFB, fb_42_52 ),
nucleus_data(42, 54, prfFB, fb_42_54 ),
nucleus_data(42, 56, prfFB, fb_42_56 ),
nucleus_data(42, 58, prfFB, fb_42_58 ),
nucleus_data(46, 58, prfFB, fb_46_58 ),
nucleus_data(46, 60, prfFB, fb_46_60 ),
nucleus_data(46, 62, prfFB, fb_46_62 ),
nucleus_data(46, 64, prfFB, fb_46_64 ),
nucleus_data(62, 82, prfFB, fb_62_82 ),
nucleus_data(62, 86, prfFB, fb_62_86a ),
nucleus_data(62, 86, prfFB, fb_62_86b ),
nucleus_data(62, 88, prfFB, fb_62_88 ),
nucleus_data(62, 90, prfFB, fb_62_90a ),
nucleus_data(62, 90, prfFB, fb_62_90b ),
nucleus_data(62, 92, prfFB, fb_62_92 ),
nucleus_data(64, 90, prfFB, fb_64_90 ),
nucleus_data(64, 94, prfFB, fb_64_94 ),
nucleus_data(68, 98, prfFB, fb_68_98 ),
nucleus_data(70,104, prfFB, fb_70_104 ),
nucleus_data(71,104, prfFB, fb_71_104 ),
nucleus_data(76,116, prfFB, fb_76_116 ),
nucleus_data(78,118, prfFB, fb_78_118 ),
nucleus_data(81,122, prfFB, fb_81_122 ),
nucleus_data(81,124, prfFB, fb_81_124 ),
nucleus_data(82,122, prfFB, fb_82_122 ),
nucleus_data(82,124, prfFB, fb_82_124 ),
nucleus_data(82,125, prfFB, fb_82_125 ),
nucleus_data(82,126, prfFB, fb_82_126a),
nucleus_data(82,126, prfFB, fb_82_126b),
nucleus_data(83,126, prfFB, fb_83_126 ),
nucleus_data( 1, 2, prfSOG, sog_1_2 ),
nucleus_data( 2, 1, prfSOG, sog_2_1 ),
nucleus_data( 2, 2, prfSOG, sog_2_2 ),
nucleus_data( 6, 6, prfSOG, sog_6_6 ),
nucleus_data( 8, 8, prfSOG, sog_8_8 ),
nucleus_data(12, 12, prfSOG, sog_12_12 ),
nucleus_data(14, 14, prfSOG, sog_14_14 ),
nucleus_data(16, 16, prfSOG, sog_16_16 ),
nucleus_data(19, 20, prfSOG, sog_19_20 ),
nucleus_data(20, 20, prfSOG, sog_20_20 ),
nucleus_data(20, 28, prfSOG, sog_20_28 ),
nucleus_data(28, 30, prfSOG, sog_28_30 ),
nucleus_data(50, 66, prfSOG, sog_50_66 ),
nucleus_data(50, 74, prfSOG, sog_50_74 ),
nucleus_data(81,124, prfSOG, sog_81_124),
nucleus_data(82,124, prfSOG, sog_82_124),
nucleus_data(82,126, prfSOG, sog_82_126),
nucleus_data( 3, 4, prfHO, ho_3_4 ),
nucleus_data( 4, 5, prfHO, ho_4_5 ),
nucleus_data( 5, 5, prfHO, ho_5_5 ),
nucleus_data( 5, 6, prfHO, ho_5_6 ),
nucleus_data( 8, 8, prfHO, ho_8_8 ),
nucleus_data( 8, 9, prfHO, ho_8_9 ),
nucleus_data( 8, 10, prfHO, ho_8_10 ),
nucleus_data( 6, 7, prfMHO, mho_6_7 ),
nucleus_data( 6, 8, prfMHO, mho_6_8 ),
nucleus_data(7, 7, prf3pF, _3pF_7_7 ),
nucleus_data(7 , 8, prf3pF, _3pF_7_8 ),
nucleus_data(12, 12, prf3pF, _3pF_12_12a),
nucleus_data(12, 12, prf3pF, _3pF_12_12b),
nucleus_data(12, 13, prf3pF, _3pF_12_13),
nucleus_data(14, 14, prf3pF, _3pF_14_14),
nucleus_data(14, 15, prf3pF, _3pF_14_15),
nucleus_data(14, 16, prf3pF, _3pF_14_16),
nucleus_data(15, 16, prf3pF, _3pF_15_16),
nucleus_data(17, 18, prf3pF, _3pF_17_18),
nucleus_data(17, 20, prf3pF, _3pF_17_20),
nucleus_data(19, 20, prf3pF, _3pF_19_20),
nucleus_data(20, 20, prf3pF, _3pF_20_20),
nucleus_data(20, 28, prf3pF, _3pF_20_28),
nucleus_data(28, 30, prf3pF, _3pF_28_30),
nucleus_data(28, 32, prf3pF, _3pF_28_32),
nucleus_data(28, 33, prf3pF, _3pF_28_33),
nucleus_data(28, 34, prf3pF, _3pF_28_34),
nucleus_data(28, 36, prf3pF, _3pF_28_36),
nucleus_data(16, 16, prf3pG, _3pG_16_16),
nucleus_data(40, 50, prf3pG, _3pG_40_50),
nucleus_data(40, 51, prf3pG, _3pG_40_51),
nucleus_data(40, 52, prf3pG, _3pG_40_52),
nucleus_data(40, 54, prf3pG, _3pG_40_54),
nucleus_data(40, 56, prf3pG, _3pG_40_56),
nucleus_data(42, 50, prf3pG, _3pG_42_50),
nucleus_data( 9, 10, prf2pF, _2pF_9_10 ),
nucleus_data(10, 10, prf2pF, _2pF_10_10),
nucleus_data(10, 12, prf2pF, _2pF_10_12),
nucleus_data(12, 12, prf2pF, _2pF_12_12),
nucleus_data(12, 14, prf2pF, _2pF_12_14),
nucleus_data(13, 14, prf2pF, _2pF_13_14),
nucleus_data(18, 18, prf2pF, _2pF_18_18),
nucleus_data(18, 22, prf2pF, _2pF_18_22),
nucleus_data(22, 26, prf2pF, _2pF_22_26),
nucleus_data(23, 28, prf2pF, _2pF_23_28),
nucleus_data(24, 26, prf2pF, _2pF_24_26),
nucleus_data(24, 28, prf2pF, _2pF_24_28),
nucleus_data(24, 29, prf2pF, _2pF_24_29),
nucleus_data(25, 30, prf2pF, _2pF_25_30),
nucleus_data(26, 28, prf2pF, _2pF_26_28),
nucleus_data(26, 30, prf2pF, _2pF_26_30),
nucleus_data(26, 32, prf2pF, _2pF_26_32),
nucleus_data(27, 32, prf2pF, _2pF_27_32),
nucleus_data(29, 34, prf2pF, _2pF_29_34),
nucleus_data(29, 36, prf2pF, _2pF_29_36),
nucleus_data(30, 34, prf2pF, _2pF_30_34),
nucleus_data(30, 36, prf2pF, _2pF_30_36),
nucleus_data(30, 38, prf2pF, _2pF_30_38),
nucleus_data(30, 40, prf2pF, _2pF_30_40),
nucleus_data(32, 38, prf2pF, _2pF_32_38),
nucleus_data(32, 40, prf2pF, _2pF_32_40),
nucleus_data(38, 50, prf2pF, _2pF_38_50),
nucleus_data(39, 50, prf2pF, _2pF_39_50),
nucleus_data(41, 52, prf2pF, _2pF_41_52),
nucleus_data(79, 118, prf2pF, _2pF_79_118),
nucleus_data(90, 142, prf2pF, _2pF_Th232a),
nucleus_data(90, 142, prf2pF, _2pF_Th232b),
nucleus_data(92, 146, prf2pF, _2pF_U238a),
nucleus_data(92, 146, prf2pF, _2pF_U238b),
// nucleus_data( 1, 0, prfMI, mi_1_0 ),
// nucleus_data( 1, 1, prfMI, mi_1_1 ),
// nucleus_data( 2, 1, prfMI, mi_2_1 ),
// nucleus_data( 2, 2, prfMI, mi_2_2 ),
nucleus_data( 11, 12, prfUG, ug_11_12 ),
nucleus_data( 0, 0, 0, 0)
};
double nucleus_data::dens(double r)
{
double X=dens_fun(dens_params,r/fermi)/fermi3;
if(dens_fun==prf3pF
|| dens_fun==prf3pG
|| dens_fun==prfSOG)
return X*(_p+_n);
if(dens_fun==prfFB)
return X*(_p+_n)/_p;
return X;
}
const char* nucleus_data::name()
{
//return el[p].name;
if(dens_fun==prfFB) return " FB";
if(dens_fun==prfSOG) return "SOG";
if(dens_fun==prf2pF) return "2pF";
if(dens_fun==prf3pF) return "3pF";
if(dens_fun==prf3pG) return "3pG";
if(dens_fun==prfHO) return " HO";
if(dens_fun==prfMHO) return "MHO";
if(dens_fun==prfMI) return " MI";
if(dens_fun==prfUG) return " UG";
return "";
}
double nucleus_data::r()
{
if(_r==0)
{
if(dens_fun==prfFB)
return _r=dens_params[0]*fermi;
double r0=0;
double r1=20.0*fermi;
double oldrs=r1;
double rs=0;
double ds0=1e-7*dens(0);
do
{
oldrs=rs;
rs=(r0+r1)/2;
double ds=dens(rs);
if(ds>ds0)
r0=rs;
else
r1=rs;
}
while(rs!=oldrs);
_r=rs;
}
return _r;
}
double nucleus_data::random_r()
{
if(_max_rr_dens==0)
{
double R=r(),d=0;
for(double a=0;a<R;a+=R/100)
_max_rr_dens=max(_max_rr_dens,a*a*dens(a));
}
static int i=0,j=0;
++j;
double r0=r(),r1;
do
{
++i;
r1 = r0*frandom();
}
while ( r1*r1*dens(r1) < frandom ()*_max_rr_dens);
// cout<<i*1./j<<endl;
return r1;
}
double nucleus_data::kF()
{
if(_kF==0)
{
_kF=calg5a(makefun(*this,&nucleus_data::kf_helper),0,r())/
calg5a(makefun(*this,&nucleus_data::dens_helper),0,r())
;
}
return _kF;
}
double nucleus_data::Mf()
{
if(_Mf==0)
{
// _Mf=calg5a(makefun(*this,&nucleus_data::mf_helper),0,r())/
// calg5a(makefun(*this,&nucleus_data::dens_helper),0,r());
_Mf=Meff(kF());
}
return _Mf;
}
nucleus_data* best_data(int p, int n)
{
int p0=p,n0=n,x=1000000000;
nucleus_data *d=dens_data;
for(nucleus_data *data=dens_data; data->p() >0; data++)
{
int x1=pow2(data->p()-p0)+pow2(data->n()-n0)+pow2(data->p()+data->n()-p0-n0);
if(x1<x)
{
x=x1;
d=data;
if(x==0)
return data;
}
}
return d;
}
double density(double r_,int p, int n)
{
double A=p+n;
if(p>83) ///< for big nuclei use rescaled Pb profile
return ::density(r_*cbrt((82+126)/A),82,126);
double r=r_;
nucleus_data *d=best_data(p,n);
r*=cbrt(A/d->A()); // and scale its size if needed
return max(d->dens(r),0.);
}
double Meff(double kf)
{
static const double MEF[3000]=
{
938.919,938.918,938.918,938.918,938.917,938.915,938.913,938.909,938.904,
938.899,938.891,938.882,938.871,938.858,938.843,938.826,938.806,938.784,
938.759,938.731,938.699,938.665,938.627,938.585,938.54,938.491,938.437,
938.38,938.318,938.251,938.179,938.103,938.021,937.935,937.843,937.745,
937.641,937.532,937.417,937.295,937.167,937.032,936.891,936.743,936.587,
936.425,936.255,936.077,935.892,935.699,935.498,935.289,935.072,934.845,
934.611,934.367,934.114,933.853,933.582,933.301,933.011,932.711,932.401,
932.08,931.75,931.409,931.057,930.695,930.322,929.937,929.541,929.134,
928.716,928.285,927.843,927.388,926.921,926.442,925.951,925.446,924.929,
924.399,923.855,923.298,922.728,922.144,921.546,920.934,920.308,919.667,
919.012,918.343,917.658,916.959,916.245,915.515,914.77,914.009,913.233,
912.44,911.632,910.807,909.966,909.109,908.235,907.344,906.436,905.511,
904.568,903.608,902.631,901.635,900.622,899.591,898.541,897.473,896.387,
895.282,894.157,893.014,891.852,890.671,889.47,888.249,887.009,885.749,
884.469,883.168,881.848,880.506,879.144,877.762,876.358,874.933,873.488,
872.02,870.531,869.021,867.489,865.934,864.358,862.76,861.139,859.495,
857.829,856.14,854.429,852.694,850.936,849.155,847.35,845.521,843.669,
841.793,839.893,837.969,836.021,834.048,832.051,830.029,827.983,825.911,
823.815,821.694,819.547,817.375,815.177,812.954,810.706,808.431,806.131,
803.805,801.452,799.074,796.669,794.237,791.78,789.295,786.784,784.246,
781.682,779.09,776.472,773.826,771.153,768.453,765.726,762.972,760.19,
757.38,754.543,751.679,748.787,745.867,742.92,739.944,736.942,733.911,
730.853,727.767,724.653,721.511,718.341,715.144,711.919,708.667,705.386,
702.078,698.743,695.38,691.99,688.572,685.127,681.654,678.155,674.628,
671.075,667.495,663.889,660.256,656.596,652.911,649.2,645.463,641.701,
637.913,634.101,630.264,626.402,622.516,618.607,614.674,610.718,606.74,
602.739,598.716,594.671,590.606,586.52,582.414,578.288,574.144,569.981,
565.8,561.603,557.388,553.158,548.913,544.653,540.38,536.093,531.795,
527.486,523.166,518.837,514.499,510.154,505.802,501.445,497.083,492.718,
488.351,483.983,479.615,475.248,470.883,466.522,462.166,457.816,453.474,
449.14,444.817,440.505,436.205,431.92,427.65,423.397,419.162,414.947,
410.752,406.579,402.43,398.305,394.206,390.134,386.091,382.077,378.094,
374.142,370.223,366.338,362.488,358.673,354.895,351.154,347.452,343.788,
340.163,336.579,333.035,329.532,326.071,322.652,319.275,315.94,312.648,
309.399,306.193,303.03,299.91,296.833,293.799,290.808,287.859,284.953,
282.088,279.266,276.485,273.746,271.048,268.39,265.772,263.193,260.655,
258.154,255.692,253.268,250.881,248.531,246.217,243.939,241.696,239.488,
237.313,235.172,233.065,230.989,228.946,226.933,224.952,223,221.079,
219.186,217.323,215.487,213.679,211.898,210.143,208.415,206.712,205.034,
203.381,201.752,200.146,198.564,197.005,195.467,193.952,192.459,190.986,
189.534,188.102,186.69,185.298,183.925,182.57,181.234,179.916,178.616,
177.333,176.066,174.817,173.584,172.367,171.166,169.98,168.81,167.654,
166.513,165.386,164.274,163.175,162.09,161.018,159.959,158.913,157.88,
156.859,155.85,154.853,153.868,152.894,151.932,150.981,150.041,149.111,
148.192,147.284,146.385,145.497,144.618,143.75,142.89,142.04,141.2,
140.368,139.545,138.731,137.926,137.129,136.34,135.56,134.788,134.023,
133.267,132.518,131.777,131.043,130.317,129.597,128.885,128.18,127.482,
126.791,126.106,125.428,124.757,124.092,123.433,122.78,122.134,121.493,
120.859,120.23,119.607,118.99,118.379,117.773,117.173,116.578,115.988,
115.403,114.824,114.25,113.68,113.116,112.557,112.002,111.453,110.908,
110.367,109.831,109.3,108.773,108.251,107.733,107.219,106.709,106.204,
105.703,105.206,104.712,104.223,103.738,103.257,102.779,102.305,101.836,
101.369,100.907,100.448,99.9921,99.5401,99.0916,98.6466,98.205,97.7667,
97.3317,96.9001,96.4716,96.0464,95.6243,95.2054,94.7896,94.3768,93.9671,
93.5604,93.1566,92.7557,92.3578,91.9627,91.5704,91.181,90.7943,90.4104,
90.0292,89.6506,89.2748,88.9015,88.5308,88.1628,87.7972,87.4342,87.0737,
86.7156,86.36,86.0068,85.656,85.3075,84.9614,84.6177,84.2762,83.937,
83.6,83.2653,82.9327,82.6024,82.2742,81.9482,81.6242,81.3024,80.9827,
80.665,80.3494,80.0357,79.7241,79.4145,79.1068,78.8011,78.4972,78.1953,
77.8953,77.5972,77.3009,77.0065,76.7138,76.423,76.134,75.8467,75.5612,
75.2775,74.9954,74.7151,74.4365,74.1595,73.8842,73.6105,73.3385,73.0681,
72.7993,72.5321,72.2665,72.0025,71.7399,71.479,71.2195,70.9616,70.7051,
70.4502,70.1967,69.9447,69.6941,69.445,69.1972,68.9509,68.706,68.4625,
68.2204,67.9796,67.7402,67.5021,67.2653,67.0299,66.7958,66.563,66.3314,
66.1012,65.8722,65.6445,65.418,65.1928,64.9687,64.746,64.5244,64.304,
64.0848,63.8668,63.65,63.4343,63.2198,63.0064,62.7941,62.583,62.373,
62.1641,61.9564,61.7497,61.5441,61.3395,61.1361,60.9337,60.7323,60.532,
60.3328,60.1345,59.9373,59.7411,59.5459,59.3517,59.1585,58.9663,58.7751,
58.5848,58.3955,58.2071,58.0197,57.8333,57.6478,57.4632,57.2795,57.0968,
56.9149,56.734,56.5539,56.3748,56.1965,56.0191,55.8426,55.6669,55.4921,
55.3182,55.1451,54.9728,54.8014,54.6308,54.4611,54.2921,54.124,53.9567,
53.7902,53.6244,53.4595,53.2954,53.132,52.9694,52.8076,52.6465,52.4863,
52.3267,52.1679,52.0099,51.8526,51.696,51.5402,51.3851,51.2307,51.077,
50.924,50.7718,50.6202,50.4694,50.3192,50.1697,50.021,49.8728,49.7254,
49.5786,49.4326,49.2871,49.1423,48.9982,48.8548,48.7119,48.5698,48.4282,
48.2873,48.147,48.0074,47.8683,47.7299,47.5921,47.4549,47.3184,47.1824,
47.047,46.9122,46.778,46.6444,46.5114,46.379,46.2471,46.1158,45.9851,
45.855,45.7254,45.5964,45.4679,45.34,45.2126,45.0858,44.9595,44.8338,
44.7086,44.584,44.4598,44.3362,44.2132,44.0906,43.9686,43.8471,43.7261,
43.6056,43.4856,43.3661,43.2471,43.1286,43.0107,42.8932,42.7761,42.6596,
42.5436,42.428,42.313,42.1984,42.0842,41.9706,41.8574,41.7446,41.6324,
41.5206,41.4092,41.2983,41.1879,41.0779,40.9683,40.8592,40.7506,40.6424,
40.5346,40.4272,40.3203,40.2138,40.1078,40.0021,39.8969,39.7921,39.6877,
39.5838,39.4802,39.3771,39.2744,39.1721,39.0701,38.9686,38.8675,38.7668,
38.6665,38.5666,38.467,38.3679,38.2691,38.1708,38.0728,37.9752,37.8779,
37.7811,37.6846,37.5885,37.4928,37.3974,37.3024,37.2078,37.1135,37.0196,
36.9261,36.8329,36.7401,36.6476,36.5555,36.4637,36.3723,36.2812,36.1904,
36.1001,36.01,35.9203,35.8309,35.7419,35.6532,35.5648,35.4768,35.3891,
35.3017,35.2146,35.1279,35.0415,34.9554,34.8697,34.7842,34.6991,34.6143,
34.5297,34.4456,34.3617,34.2781,34.1948,34.1119,34.0292,33.9468,33.8648,
33.783,33.7016,33.6204,33.5395,33.459,33.3787,33.2987,33.219,33.1396,
33.0604,32.9816,32.903,32.8248,32.7468,32.669,32.5916,32.5144,32.4375,
32.3609,32.2846,32.2085,32.1327,32.0572,31.9819,31.9069,31.8322,31.7577,
31.6835,31.6096,31.5359,31.4624,31.3893,31.3164,31.2437,31.1713,31.0991,
31.0272,30.9556,30.8842,30.813,30.7421,30.6715,30.601,30.5309,30.4609,
30.3912,30.3218,30.2526,30.1836,30.1149,30.0463,29.9781,29.91,29.8422,
29.7747,29.7073,29.6402,29.5733,29.5067,29.4402,29.374,29.308,29.2423,
29.1767,29.1114,29.0463,28.9814,28.9168,28.8523,28.7881,28.7241,28.6603,
28.5967,28.5333,28.4701,28.4072,28.3444,28.2819,28.2196,28.1574,28.0955,
28.0338,27.9723,27.911,27.8499,27.789,27.7283,27.6678,27.6075,27.5473,
27.4874,27.4277,27.3682,27.3088,27.2497,27.1908,27.132,27.0734,27.0151,
26.9569,26.8989,26.8411,26.7835,26.726,26.6688,26.6117,26.5548,26.4981,
26.4416,26.3852,26.3291,26.2731,26.2173,26.1617,26.1062,26.0509,25.9959,
25.9409,25.8862,25.8316,25.7772,25.723,25.6689,25.615,25.5613,25.5078,
25.4544,25.4012,25.3481,25.2952,25.2425,25.19,25.1376,25.0853,25.0333,
24.9814,24.9296,24.8781,24.8267,24.7754,24.7243,24.6734,24.6226,24.5719,
24.5215,24.4711,24.421,24.371,24.3211,24.2714,24.2219,24.1725,24.1232,
24.0741,24.0252,23.9764,23.9277,23.8792,23.8309,23.7827,23.7346,23.6867,
23.6389,23.5913,23.5438,23.4965,23.4493,23.4022,23.3553,23.3085,23.2619,
23.2154,23.1691,23.1228,23.0768,23.0308,22.985,22.9394,22.8938,22.8484,
22.8032,22.758,22.713,22.6682,22.6235,22.5789,22.5344,22.4901,22.4459,
22.4018,22.3579,22.314,22.2704,22.2268,22.1834,22.1401,22.0969,22.0538,
22.0109,21.9681,21.9254,21.8829,21.8405,21.7982,21.756,21.7139,21.672,
21.6302,21.5885,21.5469,21.5055,21.4641,21.4229,21.3818,21.3408,21.3,
21.2592,21.2186,21.1781,21.1377,21.0974,21.0572,21.0172,20.9772,20.9374,
20.8977,20.8581,20.8186,20.7792,20.74,20.7008,20.6618,20.6229,20.584,
20.5453,20.5067,20.4682,20.4298,20.3916,20.3534,20.3153,20.2774,20.2395,
20.2018,20.1641,20.1266,20.0892,20.0518,20.0146,19.9775,19.9405,19.9035,
19.8667,19.83,19.7934,19.7569,19.7205,19.6842,19.648,19.6119,19.5759,
19.54,19.5041,19.4684,19.4328,19.3973,19.3619,19.3266,19.2913,19.2562,
19.2212,19.1862,19.1514,19.1166,19.082,19.0474,19.0129,18.9786,18.9443,
18.9101,18.876,18.842,18.8081,18.7742,18.7405,18.7069,18.6733,18.6399,
18.6065,18.5732,18.54,18.5069,18.4739,18.441,18.4081,18.3754,18.3427,
18.3101,18.2776,18.2452,18.2129,18.1807,18.1485,18.1165,18.0845,18.0526,
18.0208,17.989,17.9574,17.9258,17.8944,17.863,17.8317,17.8004,17.7693,
17.7382,17.7072,17.6763,17.6455,17.6147,17.5841,17.5535,17.523,17.4926,
17.4622,17.432,17.4018,17.3717,17.3416,17.3117,17.2818,17.252,17.2223,
17.1926,17.163,17.1335,17.1041,17.0748,17.0455,17.0163,16.9872,16.9582,
16.9292,16.9003,16.8715,16.8427,16.814,16.7854,16.7569,16.7284,16.7001,
16.6717,16.6435,16.6153,16.5872,16.5592,16.5313,16.5034,16.4755,16.4478,
16.4201,16.3925,16.365,16.3375,16.3101,16.2828,16.2555,16.2283,16.2012,
16.1741,16.1472,16.1202,16.0934,16.0666,16.0399,16.0132,15.9866,15.9601,
15.9336,15.9072,15.8809,15.8546,15.8285,15.8023,15.7763,15.7502,15.7243,
15.6984,15.6726,15.6469,15.6212,15.5956,15.57,15.5445,15.5191,15.4937,
15.4684,15.4431,15.4179,15.3928,15.3678,15.3428,15.3178,15.2929,15.2681,
15.2433,15.2186,15.194,15.1694,15.1449,15.1204,15.096,15.0717,15.0474,
15.0232,14.999,14.9749,14.9508,14.9268,14.9029,14.879,14.8552,14.8314,
14.8077,14.7841,14.7605,14.7369,14.7134,14.69,14.6666,14.6433,14.6201,
14.5969,14.5737,14.5506,14.5276,14.5046,14.4816,14.4588,14.4359,14.4132,
14.3904,14.3678,14.3452,14.3226,14.3001,14.2777,14.2553,14.2329,14.2106,
14.1884,14.1662,14.144,14.122,14.0999,14.0779,14.056,14.0341,14.0123,
13.9905,13.9688,13.9471,13.9255,13.9039,13.8824,13.8609,13.8395,13.8181,
13.7968,13.7755,13.7543,13.7331,13.7119,13.6909,13.6698,13.6488,13.6279,
13.607,13.5861,13.5654,13.5446,13.5239,13.5032,13.4826,13.4621,13.4416,
13.4211,13.4007,13.3803,13.36,13.3397,13.3195,13.2993,13.2791,13.259,
13.239,13.219,13.199,13.1791,13.1592,13.1394,13.1196,13.0999,13.0802,
13.0605,13.0409,13.0214,13.0018,12.9824,12.9629,12.9436,12.9242,12.9049,
12.8857,12.8664,12.8473,12.8281,12.8091,12.79,12.771,12.7521,12.7331,
12.7143,12.6954,12.6766,12.6579,12.6392,12.6205,12.6019,12.5833,12.5648,
12.5463,12.5278,12.5094,12.491,12.4726,12.4543,12.4361,12.4179,12.3997,
12.3815,12.3634,12.3454,12.3274,12.3094,12.2914,12.2735,12.2557,12.2378,
12.22,12.2023,12.1846,12.1669,12.1493,12.1317,12.1141,12.0966,12.0791,
12.0617,12.0443,12.0269,12.0096,11.9923,11.975,11.9578,11.9406,11.9235,
11.9064,11.8893,11.8723,11.8553,11.8383,11.8214,11.8045,11.7876,11.7708,
11.754,11.7373,11.7206,11.7039,11.6872,11.6706,11.6541,11.6375,11.621,
11.6046,11.5881,11.5717,11.5554,11.5391,11.5228,11.5065,11.4903,11.4741,
11.4579,11.4418,11.4257,11.4097,11.3937,11.3777,11.3617,11.3458,11.3299,
11.3141,11.2983,11.2825,11.2667,11.251,11.2353,11.2197,11.204,11.1885,
11.1729,11.1574,11.1419,11.1264,11.111,11.0956,11.0802,11.0649,11.0496,
11.0343,11.0191,11.0039,10.9887,10.9736,10.9585,10.9434,10.9283,10.9133,
10.8983,10.8834,10.8684,10.8535,10.8387,10.8238,10.809,10.7943,10.7795,
10.7648,10.7501,10.7355,10.7208,10.7063,10.6917,10.6772,10.6626,10.6482,
10.6337,10.6193,10.6049,10.5906,10.5762,10.5619,10.5477,10.5334,10.5192,
10.505,10.4909,10.4767,10.4626,10.4486,10.4345,10.4205,10.4065,10.3925,
10.3786,10.3647,10.3508,10.337,10.3232,10.3094,10.2956,10.2819,10.2682,
10.2545,10.2408,10.2272,10.2136,10.2,10.1865,10.173,10.1595,10.146,
10.1326,10.1191,10.1058,10.0924,10.0791,10.0658,10.0525,10.0392,10.026,
10.0128,9.99961,9.98646,9.97333,9.96024,9.94716,9.93411,9.92109,9.90809,
9.89512,9.88218,9.86926,9.85636,9.84349,9.83065,9.81783,9.80503,9.79226,
9.77952,9.76679,9.7541,9.74143,9.72878,9.71616,9.70356,9.69099,9.67844,
9.66592,9.65342,9.64094,9.62849,9.61606,9.60366,9.59128,9.57892,9.56659,
9.55428,9.542,9.52973,9.5175,9.50528,9.49309,9.48093,9.46878,9.45666,
9.44456,9.43249,9.42044,9.40841,9.3964,9.38442,9.37246,9.36052,9.34861,
9.33672,9.32485,9.313,9.30118,9.28938,9.2776,9.26584,9.25411,9.2424,
9.23071,9.21904,9.20739,9.19577,9.18417,9.17259,9.16103,9.14949,9.13798,
9.12649,9.11502,9.10357,9.09214,9.08073,9.06935,9.05798,9.04664,9.03532,
9.02402,9.01274,9.00148,8.99024,8.97903,8.96783,8.95666,8.9455,8.93437,
8.92326,8.91217,8.9011,8.89005,8.87902,8.86801,8.85702,8.84605,8.8351,
8.82417,8.81327,8.80238,8.79151,8.78066,8.76984,8.75903,8.74824,8.73747,
8.72673,8.716,8.70529,8.6946,8.68393,8.67328,8.66265,8.65204,8.64145,
8.63088,8.62033,8.6098,8.59928,8.58879,8.57831,8.56786,8.55742,8.547,
8.5366,8.52622,8.51586,8.50552,8.49519,8.48489,8.4746,8.46433,8.45409,
8.44385,8.43364,8.42345,8.41327,8.40312,8.39298,8.38286,8.37276,8.36267,
8.35261,8.34256,8.33253,8.32252,8.31253,8.30255,8.29259,8.28265,8.27273,
8.26283,8.25294,8.24307,8.23322,8.22339,8.21357,8.20378,8.194,8.18423,
8.17449,8.16476,8.15505,8.14535,8.13568,8.12602,8.11637,8.10675,8.09714,
8.08755,8.07797,8.06842,8.05888,8.04935,8.03985,8.03036,8.02088,8.01143,
8.00199,7.99257,7.98316,7.97377,7.9644,7.95504,7.9457,7.93637,7.92707,
7.91777,7.9085,7.89924,7.89,7.88077,7.87156,7.86237,7.85319,7.84403,
7.83488,7.82575,7.81664,7.80754,7.79846,7.78939,7.78034,7.7713,7.76228,
7.75328,7.74429,7.73532,7.72636,7.71742,7.70849,7.69958,7.69069,7.68181,
7.67294,7.66409,7.65526,7.64644,7.63764,7.62885,7.62008,7.61132,7.60257,
7.59385,7.58513,7.57643,7.56775,7.55908,7.55043,7.54179,7.53317,7.52456,
7.51596,7.50738,7.49882,7.49027,7.48173,7.47321,7.4647,7.45621,7.44773,
7.43927,7.43082,7.42238,7.41396,7.40556,7.39717,7.38879,7.38042,7.37208,
7.36374,7.35542,7.34711,7.33882,7.33054,7.32228,7.31402,7.30579,7.29756,
7.28935,7.28116,7.27298,7.26481,7.25665,7.24851,7.24039,7.23227,7.22417,
7.21609,7.20801,7.19995,7.19191,7.18388,7.17586,7.16785,7.15986,7.15188,
7.14392,7.13596,7.12802,7.1201,7.11219,7.10429,7.0964,7.08853,7.08067,
7.07282,7.06499,7.05716,7.04936,7.04156,7.03378,7.02601,7.01825,7.01051,
7.00278,6.99506,6.98735,6.97966,6.97198,6.96431,6.95666,6.94902,6.94139,
6.93377,6.92616,6.91857,6.91099,6.90343,6.89587,6.88833,6.8808,6.87328,
6.86577,6.85828,6.8508,6.84333,6.83587,6.82843,6.821,6.81358,6.80617,
6.79877,6.79139,6.78401,6.77665,6.76931,6.76197,6.75464,6.74733,6.74003,
6.73274,6.72546,6.7182,6.71095,6.7037,6.69647,6.68925,6.68205,6.67485,
6.66767,6.6605,6.65334,6.64619,6.63905,6.63192,6.62481,6.6177,6.61061,
6.60353,6.59646,6.58941,6.58236,6.57532,6.5683,6.56129,6.55428,6.54729,
6.54032,6.53335,6.52639,6.51944,6.51251,6.50559,6.49867,6.49177,6.48488,
6.478,6.47113,6.46427,6.45742,6.45059,6.44376,6.43695,6.43014,6.42335,
6.41657,6.4098,6.40304,6.39629,6.38955,6.38282,6.3761,6.36939,6.36269,
6.35601,6.34933,6.34266,6.33601,6.32936,6.32273,6.3161,6.30949,6.30289,
6.29629,6.28971,6.28314,6.27658,6.27002,6.26348,6.25695,6.25043,6.24392,
6.23742,6.23093,6.22445,6.21798,6.21152,6.20507,6.19862,6.19219,6.18577,
6.17936,6.17296,6.16657,6.16019,6.15382,6.14746,6.14111,6.13477,6.12844,
6.12211,6.1158,6.1095,6.10321,6.09692,6.09065,6.08439,6.07813,6.07189,
6.06565,6.05943,6.05321,6.04701,6.04081,6.03462,6.02845,6.02228,6.01612,
6.00997,6.00383,5.9977,5.99158,5.98547,5.97937,5.97327,5.96719,5.96111,
5.95505,5.94899,5.94295,5.93691,5.93088,5.92486,5.91885,5.91285,5.90686,
5.90087,5.8949,5.88894,5.88298,5.87703,5.8711,5.86517,5.85925,5.85334,
5.84744,5.84154,5.83566,5.82978,5.82392,5.81806,5.81221,5.80637,5.80054,
5.79472,5.7889,5.7831,5.7773,5.77152,5.76574,5.75997,5.75421,5.74845,
5.74271,5.73697,5.73125,5.72553,5.71982,5.71412,5.70842,5.70274,5.69706,
5.69139,5.68574,5.68008,5.67444,5.66881,5.66318,5.65757,5.65196,5.64636,
5.64076,5.63518,5.6296,5.62404,5.61848,5.61293,5.60738,5.60185,5.59632,
5.59081,5.5853,5.57979,5.5743,5.56881,5.56334,5.55787,5.55241,5.54695,
5.54151,5.53607,5.53064,5.52522,5.5198,5.5144,5.509,5.50361,5.49823,
5.49286,5.48749,5.48213,5.47678,5.47144,5.4661,5.46078,5.45546,5.45014,
5.44484,5.43954,5.43426,5.42898,5.4237,5.41844,5.41318,5.40793,5.40269,
5.39745,5.39223,5.38701,5.38179,5.37659,5.37139,5.3662,5.36102,5.35585,
5.35068,5.34552,5.34037,5.33522,5.33008,5.32496,5.31983,5.31472,5.30961,
5.30451,5.29942,5.29433,5.28925,5.28418,5.27912,5.27406,5.26901,5.26397,
5.25893,5.25391,5.24889,5.24387,5.23887,5.23387,5.22888,5.22389,5.21891,
5.21394,5.20898,5.20402,5.19907,5.19413,5.1892,5.18427,5.17935,5.17443,
5.16952,5.16462,5.15973,5.15484,5.14997,5.14509,5.14023,5.13537,5.13052,
5.12567,5.12083,5.116,5.11118,5.10636,5.10155,5.09674,5.09195,5.08716,
5.08237,5.0776,5.07283,5.06806,5.0633,5.05855,5.05381,5.04907,5.04434,
5.03962,5.0349,5.03019,5.02549,5.02079,5.0161,5.01142,5.00674,5.00207,
4.9974,4.99274,4.98809,4.98345,4.97881,4.97418,4.96955,4.96493,4.96032,
4.95571,4.95111,4.94652,4.94193,4.93735,4.93278,4.92821,4.92365,4.91909,
4.91454,4.91,4.90546,4.90093,4.89641,4.89189,4.88738,4.88287,4.87837,
4.87388,4.8694,4.86491,4.86044,4.85597,4.85151,4.84705,4.8426,4.83816,
4.83372,4.82929,4.82487,4.82045,4.81603,4.81163,4.80723,4.80283,4.79844,
4.79406,4.78968,4.78531,4.78094,4.77658,4.77223,4.76788,4.76354,4.75921,
4.75488,4.75055,4.74624,4.74192,4.73762,4.73332,4.72902,4.72474,4.72045,
4.71618,4.7119,4.70764,4.70338,4.69913,4.69488,4.69064,4.6864,4.68217,
4.67794,4.67372,4.66951,4.6653,4.6611,4.6569,4.65271,4.64853,4.64435,
4.64017,4.636,4.63184,4.62768,4.62353,4.61939,4.61525,4.61111,4.60698,
4.60286,4.59874,4.59463,4.59052,4.58642,4.58232,4.57823,4.57414,4.57006,
4.56599,4.56192,4.55786,4.5538,4.54975,4.5457,4.54166,4.53762,4.53359,
4.52956,4.52554,4.52153,4.51752,4.51351,4.50951,4.50552,4.50153,4.49755,
4.49357,4.4896,4.48563,4.48167,4.47771,4.47376,4.46981,4.46587,4.46193,
4.458,4.45408,4.45016,4.44624,4.44233,4.43843,4.43453,4.43063,4.42674,
4.42286,4.41898,4.4151,4.41123,4.40737,4.40351,4.39965,4.39581,4.39196,
4.38812,4.38429,4.38046,4.37664,4.37282,4.369,4.36519,4.36139,4.35759,
4.3538,4.35001,4.34622,4.34244,4.33867,4.3349,4.33113,4.32738,4.32362,
4.31987,4.31613,4.31238,4.30865,4.30492,4.30119,4.29747,4.29376,4.29005,
4.28634,4.28264,4.27894,4.27525,4.27156,4.26788,4.2642,4.26053,4.25686,
4.2532,4.24954,4.24588,4.24223,4.23859,4.23495,4.23131,4.22768,4.22406,
4.22044,4.21682,4.21321,4.2096,4.206,4.2024,4.1988,4.19522,4.19163,
4.18805,4.18448,4.18091,4.17734,4.17378,4.17022,4.16667,4.16312,4.15958,
4.15604,4.1525,4.14897,4.14545,4.14193,4.13841,4.1349,4.13139,4.12789,
4.12439,4.1209,4.11741,4.11392,4.11044,4.10696,4.10349,4.10002,4.09656,
4.0931,4.08965,4.0862,4.08275,4.07931,4.07587,4.07244,4.06901,4.06559,
4.06217,4.05875,4.05534,4.05193,4.04853,4.04513,4.04174,4.03835,4.03496,
4.03158,4.0282,4.02483,4.02146,4.0181,4.01474,4.01138,4.00803,4.00468,
4.00134,3.998,3.99467,3.99133,3.98801,3.98469,3.98137,3.97805,3.97474,
3.97144,3.96813,3.96484,3.96154,3.95825,3.95497,3.95169,3.94841,3.94514,
3.94187,3.9386,3.93534,3.93208,3.92883,3.92558,3.92234,3.9191,3.91586,
3.91263,3.9094,3.90617,3.90295,3.89973,3.89652,3.89331,3.89011,3.88691,
3.88371,3.88051,3.87733,3.87414,3.87096,3.86778,3.86461,3.86144,3.85827,
3.85511,3.85195,3.8488,3.84565,3.8425,3.83936,3.83622,3.83308,3.82995,
3.82683,3.8237,3.82058,3.81747,3.81435,3.81125,3.80814,3.80504,3.80194,
3.79885,3.79576,3.79268,3.78959,3.78652,3.78344,3.78037,3.7773,3.77424,
3.77118,3.76813,3.76507,3.76203,3.75898,3.75594,3.7529,3.74987,3.74684,
3.74381,3.74079,3.73777,3.73476,3.73175,3.72874,3.72573,3.72273,3.71974,
3.71674,3.71375,3.71077,3.70778,3.7048,3.70183,3.69886,3.69589,3.69292,
3.68996,3.68701,3.68405,3.6811,3.67815,3.67521,3.67227,3.66933,3.6664,
3.66347,3.66055,3.65762,3.6547,3.65179,3.64888,3.64597,3.64306,3.64016,
3.63726,3.63437,3.63148,3.62859,3.62571,3.62282,3.61995,3.61707,3.6142,
3.61134,3.60847,3.60561,3.60275,3.5999,3.59705,3.5942,3.59136,3.58852,
3.58568,3.58285,3.58002,3.57719,3.57437,3.57155,3.56873,3.56592,3.56311,
3.5603,3.5575,3.5547,3.5519,3.54911,3.54632,3.54353,3.54075,3.53797,
3.53519,3.53242,3.52965,3.52688,3.52412,3.52136,3.5186,3.51584,3.51309,
3.51035,3.5076,3.50486,3.50212,3.49939,3.49665,3.49393,3.4912,3.48848,
3.48576,3.48304,3.48033,3.47762,3.47491,3.47221,3.46951,3.46681,3.46412,
3.46143,3.45874,3.45606,3.45338,3.4507,3.44802,3.44535,3.44268,3.44002,
3.43735,3.43469,3.43204,3.42938,3.42673,3.42409,3.42144,3.4188,3.41616,
3.41353,3.4109,3.40827,3.40564,3.40302,3.4004,3.39778,3.39517,3.39256,
3.38995,3.38734,3.38474,3.38214,3.37955,3.37695,3.37436,3.37178,3.36919,
3.36661,3.36403,3.36146,3.35889,3.35632,3.35375,3.35119,3.34863,3.34607,
3.34352,3.34096,3.33842,3.33587,3.33333,3.33079,3.32825,3.32572,3.32319,
3.32066,3.31813,3.31561,3.31309,3.31057,3.30806,3.30555,3.30304,3.30053,
3.29803,3.29553,3.29303,3.29054,3.28805,3.28556,3.28307,3.28059,3.27811,
3.27563,3.27316,3.27069,3.26822,3.26575,3.26329,3.26083,3.25837,3.25592,
3.25347,3.25102,3.24857,3.24613,3.24368,3.24125,3.23881,3.23638,3.23395,
3.23152,3.2291,3.22667,3.22426,3.22184,3.21943,3.21701,3.21461,3.2122,
3.2098,3.2074,3.205,3.2026,3.20021,3.19782,3.19544,3.19305,3.19067,
3.18829,3.18592,3.18354,3.18117,3.1788,3.17644,3.17407,3.17171,3.16936,
3.167,3.16465,3.1623,3.15995,3.15761,3.15526,3.15293,3.15059,3.14825,
3.14592,3.14359,3.14127,3.13894,3.13662,3.1343,3.13199,3.12967,3.12736,
3.12505,3.12275,3.12044,3.11814,3.11585,3.11355,3.11126,3.10897,3.10668,
3.10439,3.10211,3.09983,3.09755,3.09527,3.093,3.09073,3.08846,3.0862,
3.08393,3.08167,3.07942,3.07716,3.07491,3.07266,3.07041,3.06816,3.06592,
3.06368,3.06144,3.0592,3.05697,3.05474,3.05251,3.05028,3.04806,3.04584,
3.04362,3.0414,3.03919,3.03698,3.03477,3.03256,3.03036,3.02815,3.02595,
3.02376,3.02156,3.01937,3.01718,3.01499,3.01281,3.01062,3.00844,3.00627,
3.00409,3.00192,2.99974,2.99758,2.99541,2.99325,2.99108,2.98892,2.98677,
2.98461,2.98246,2.98031,2.97816,2.97602,2.97387,2.97173,2.96959,2.96746,
2.96532,2.96319,2.96106,2.95894,2.95681,2.95469,2.95257,2.95045,2.94834,
2.94622,2.94411,2.942,2.9399,2.93779,2.93569,2.93359,2.93149,2.9294,
2.9273,2.92521,2.92312,2.92104,2.91895,2.91687,2.91479,2.91271,2.91064,
2.90857,2.9065,2.90443,2.90236,2.9003,2.89823,2.89617,2.89412,2.89206,
2.89001,2.88796,2.88591,2.88386,2.88182,2.87978,2.87773,2.8757,2.87366,
2.87163,2.8696,2.86757,2.86554,2.86351,2.86149,2.85947,2.85745,2.85544,
2.85342,2.85141,2.8494,2.84739,2.84538,2.84338,2.84138,2.83938,2.83738,
2.83539,2.83339,2.8314,2.82941,2.82743,2.82544,2.82346,2.82148,2.8195,
2.81752,2.81555,2.81358,2.81161,2.80964,2.80767,2.80571,2.80375,2.80179,
2.79983,2.79787,2.79592,2.79397,2.79202,2.79007,2.78812,2.78618,2.78424,
2.7823,2.78036,2.77843,2.77649,2.77456,2.77263,2.7707,2.76878,2.76685,
2.76493,2.76301,2.7611,2.75918,2.75727,2.75536,2.75345,2.75154,2.74963,
2.74773,2.74583,2.74393,2.74203,2.74013,2.73824,2.73635,2.73446,2.73257,
2.73069,2.7288,2.72692,2.72504,2.72316,2.72129,2.71941,2.71754,2.71567,
2.7138,2.71193,2.71007,2.70821,2.70634,2.70449,2.70263,2.70077,2.69892,
2.69707,2.69522,2.69337,2.69153,2.68968,2.68784,2.686,2.68416,2.68233,
2.68049,2.67866,2.67683,2.675,2.67318,2.67135,2.66953,2.66771,2.66589,
2.66407,2.66226,2.66044,2.65863,2.65682,2.65501,2.65321,2.6514,2.6496,
2.6478,2.646,2.6442,2.64241,2.64061,2.63882,2.63703,2.63524,2.63346,
2.63167,2.62989,2.62811,2.62633,2.62455,2.62278,2.621,2.61923,2.61746,
2.61569,2.61393,2.61216,2.6104,2.60864,2.60688,2.60512,2.60337,2.60161,
2.59986,2.59811,2.59636,2.59462,2.59287,2.59113,2.58939,2.58765,2.58591,
2.58417,2.58244,2.5807,2.57897,2.57724,2.57552,2.57379,2.57207,2.57034,
2.56862,2.5669,2.56519,2.56347,2.56176,2.56005,2.55834,2.55663,2.55492,
2.55322,2.55151,2.54981,2.54811,2.54641,2.54471,2.54302,2.54133,2.53963,
2.53794,2.53626,2.53457
};
int i = int(kf);
double x = kf-i;
if(i>2999)
return 2;//or maybe tablica_Mef[2999];
else
return MEF[i]*(1-x) + MEF[i+1]*x;
}
| cjusz/nuwro | src/nucleus_data.cc | C++ | gpl-3.0 | 68,022 |
package org.gnubridge.presentation.gui;
import java.awt.Point;
import org.gnubridge.core.Card;
import org.gnubridge.core.Direction;
import org.gnubridge.core.East;
import org.gnubridge.core.Deal;
import org.gnubridge.core.Hand;
import org.gnubridge.core.North;
import org.gnubridge.core.South;
import org.gnubridge.core.West;
import org.gnubridge.core.deck.Suit;
public class OneColumnPerColor extends HandDisplay {
public OneColumnPerColor(Direction human, Direction player, Deal game, CardPanelHost owner) {
super(human, player, game, owner);
}
final static int CARD_OFFSET = 30;
@Override
public void display() {
dispose(cards);
Hand hand = new Hand(game.getPlayer(player).getHand());
Point upperLeft = calculateUpperLeft(human, player);
for (Suit color : Suit.list) {
int j = 0;
for (Card card : hand.getSuitHi2Low(color)) {
CardPanel cardPanel = new CardPanel(card);
cards.add(cardPanel);
if (human.equals(South.i())) {
cardPanel.setPlayable(true);
}
owner.addCard(cardPanel);
cardPanel.setLocation((int) upperLeft.getX(), (int) upperLeft.getY() + CARD_OFFSET * j);
j++;
}
upperLeft.setLocation(upperLeft.getX() + CardPanel.IMAGE_WIDTH + 2, upperLeft.getY());
}
}
private Point calculateUpperLeft(Direction human, Direction player) {
Direction slot = new HumanAlwaysOnBottom(human).mapRelativeTo(player);
if (North.i().equals(slot)) {
return new Point(235, 5);
} else if (West.i().equals(slot)) {
return new Point(3, owner.getTotalHeight() - 500);
} else if (East.i().equals(slot)) {
return new Point(512, owner.getTotalHeight() - 500);
} else if (South.i().equals(slot)) {
return new Point(235, owner.getTableBottom() + 1);
}
throw new RuntimeException("unknown direction");
}
}
| pslusarz/gnubridge | src/main/java/org/gnubridge/presentation/gui/OneColumnPerColor.java | Java | gpl-3.0 | 1,786 |
<b>Users Currently Logged In</b>
<ul>
<?php if (!empty($currentUsers)):foreach($currentUsers as $u):?>
<li>
<?php echo $u->getFullName();?>
</li>
<?php endforeach;endif;?>
</ul>
| 2pisoftware/cmfive | system/modules/admin/templates/index.tpl.php | PHP | gpl-3.0 | 214 |
<?php
/*******
Biblioteka implementująca BotAPI GG http://boty.gg.pl/
Copyright (C) 2013 GG Network S.A. Marcin Bagiński <marcin.baginski@firma.gg.pl>
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see<http://www.gnu.org/licenses/>.
*******/
require_once(dirname(__FILE__).'/PushConnection.php');
define ('FORMAT_NONE', 0x00);
define ('FORMAT_BOLD_TEXT', 0x01);
define ('FORMAT_ITALIC_TEXT', 0x02);
define ('FORMAT_UNDERLINE_TEXT', 0x04);
define ('FORMAT_NEW_LINE', 0x08);
define ('IMG_FILE', true);
define ('IMG_RAW', false);
define('BOTAPI_VERSION', 'GGBotApi-2.4-PHP');
require_once(dirname(__FILE__).'/PushConnection.php');
/**
* @brief Reprezentacja wiadomości
*/
class MessageBuilder
{
/**
* Tablica numerów GG do których ma trafić wiadomość
*/
public $recipientNumbers=array();
/**
* Określa czy wiadomość zostanie wysłana do numerów będących offline, domyślnie true
*/
public $sendToOffline=true;
public $html='';
public $text='';
public $format='';
public $R=0;
public $G=0;
public $B=0;
/**
* Konstruktor MessageBuilder
*/
public function __construct()
{
}
/**
* Czyści całą wiadomość
*/
public function clear()
{
$this->recipientNumbers=array();
$this->sendToOffline=true;
$this->html='';
$this->text='';
$this->format='';
$this->R=0;
$this->G=0;
$this->B=0;
}
/**
* Dodaje tekst do wiadomości
*
* @param string $text tekst do wysłania
* @param int $formatBits styl wiadomości (FORMAT_BOLD_TEXT, FORMAT_ITALIC_TEXT, FORMAT_UNDERLINE_TEXT), domyślnie brak
* @param int $R, $G, $B składowe koloru tekstu w formacie RGB
*
* @return MessageBuilder this
*/
public function addText($text, $formatBits=FORMAT_NONE, $R=0, $G=0, $B=0)
{
if ($formatBits & FORMAT_NEW_LINE)
$text.="\r\n";
$text=str_replace("\r\r", "\r", str_replace("\n", "\r\n", $text));
$html=str_replace("\r\n", '<br>', htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8'));
if ($this->format!==NULL) {
$this->format.=pack(
'vC',
mb_strlen($this->text, 'UTF-8'),
(($formatBits & FORMAT_BOLD_TEXT)) |
(($formatBits & FORMAT_ITALIC_TEXT)) |
(($formatBits & FORMAT_UNDERLINE_TEXT)) |
((1 || $R!=$this->R || $G!=$this->G || $B!=$this->B) * 0x08)
);
$this->format.=pack('CCC', $R, $G, $B);
$this->R=$R;
$this->G=$G;
$this->B=$B;
$this->text.=$text;
}
if ($R || $G || $B) $html='<span style="color:#'.str_pad(dechex($R), 2, '0', STR_PAD_LEFT).str_pad(dechex($G), 2, '0', STR_PAD_LEFT).str_pad(dechex($B), 2, '0', STR_PAD_LEFT).';">'.$html.'</span>';
if ($formatBits & FORMAT_BOLD_TEXT) $html='<b>'.$html.'</b>';
if ($formatBits & FORMAT_ITALIC_TEXT) $html='<i>'.$html.'</i>';
if ($formatBits & FORMAT_UNDERLINE_TEXT) $html='<u>'.$html.'</u>';
$this->html.=$html;
return $this;
}
/**
* Dodaje tekst do wiadomości
*
* @param string $text tekst do wysłania w formacie BBCode
*
* @return MessageBuilder this
*/
public function addBBcode($bbcode)
{
$tagsLength=0;
$heap=array();
$start=0;
$bbcode=str_replace('[br]', "\n", $bbcode);
while (preg_match('/\[(\/)?(b|i|u|color)(=#?[0-9a-fA-F]{6})?\]/', $bbcode, $out, PREG_OFFSET_CAPTURE, $start)) {
$s=substr($bbcode, $start, $out[0][1]-$start);
$c=array(0, 0, 0);
if (strlen($s)) {
$flags=0;
$c=array(0, 0, 0);
foreach ($heap as $h) {
switch ($h[0]) {
case 'b': { $flags|=0x01; break; }
case 'i': { $flags|=0x02; break; }
case 'u': { $flags|=0x04; break; }
case 'color': { $c=$h[1]; break; }
}
}
$this->addText($s, $flags, $c[0], $c[1], $c[2]);
}
$start=$out[0][1]+strlen($out[0][0]);
if ($out[1][0]=='') {
switch ($out[2][0]) {
case 'b':
case 'i':
case 'u': {
array_push($heap, array($out[2][0]));
break;
}
case 'color': {
$c=hexdec(substr($out[3][0], -6, 6));
$c=array(
($c >> 16) & 0xFF,
($c >> 8) & 0xFF,
($c >> 0) & 0xFF
);
array_push($heap, array('color', $c));
break;
}
}
$tagsLength+=strlen($out[0][0]);
} else {
array_pop($heap);
$tagsLength+=strlen($out[0][0]);
}
}
$s=substr($bbcode, $start);
if (strlen($s))
$this->addText($s);
return $this;
}
/**
* Dodaje tekst do wiadomości
*
* @param string $text tekst do wysłania w HTMLu
*
* @return MessageBuilder this
*/
public function addRawHtml($html)
{
$this->html.=$html;
return $this;
}
/**
* Ustawia tekst do wiadomości
*
* @param string $html tekst do wysłania w HTMLu
*
* @return MessageBuilder this
*/
public function setRawHtml($html)
{
$this->html=$html;
return $this;
}
/**
* Ustawia tekst wiadomości alternatywnej
*
* @param string $text tekst do wysłania dla GG7.7 i starszych
*
* @return MessageBuilder this
*/
public function setAlternativeText($message)
{
$this->format=NULL;
$this->text=$message;
return $this;
}
/**
* Dodaje obraz do wiadomości
*
* @param string $fileName nazwa pliku w formacie JPEG
*
* @return MessageBuilder this
*/
public function addImage($fileName, $isFile=IMG_FILE)
{
if ($isFile==IMG_FILE)
$fileName=file_get_contents($fileName);
$crc=crc32($fileName);
$hash=sprintf('%08x%08x', $crc, strlen($fileName));
if (empty(PushConnection::$lastAuthorization))
throw new Exception('Użyj klasy PushConnection');
$P=new PushConnection();
if (!$P->existsImage($hash))
if (!$P->putImage($fileName))
throw new Exception('Nie udało się wysłać obrazka');
$this->format.=pack('vCCCVV', strlen($this->text), 0x80, 0x09, 0x01, strlen($fileName), $crc);
$this->addRawHtml('<img name="'.$hash.'">');
return $this;
}
/**
* Ustawia odbiorców wiadomości
*
* @param int|string|array recipientNumbers numer GG adresata (lub tablica)
*
* @return MessageBuilder this
*/
public function setRecipients($recipientNumbers)
{
$this->recipientNumbers=(array) $recipientNumbers;
return $this;
}
/**
* Zawsze dostarcza wiadomość
*
* @return MessageBuilder this
*/
public function setSendToOffline($sendToOffline)
{
$this->sendToOffline=$sendToOffline;
return $this;
}
/**
* Tworzy sformatowaną wiadomość do wysłania do BotMastera
*/
public function getProtocolMessage()
{
if (preg_match('/^<span[^>]*>.+<\/span>$/s', $this->html, $o)) {
if ($o[0]!=$this->html)
$this->html='<span style="color:#000000; font-family:\'MS Shell Dlg 2\'; font-size:9pt; ">'.$this->html.'</span>';
} else
$this->html='<span style="color:#000000; font-family:\'MS Shell Dlg 2\'; font-size:9pt; ">'.$this->html.'</span>';
$s=pack('VVVV', strlen($this->html)+1, strlen($this->text)+1, 0, ((empty($this->format)) ? 0 : strlen($this->format)+3)).$this->html."\0".$this->text."\0".((empty($this->format)) ? '' : pack('Cv', 0x02, strlen($this->format)).$this->format);
return $s;
}
/**
* Zwraca na wyjście sformatowaną wiadomość do wysłania do BotMastera
*/
public function reply()
{
if (sizeof($this->recipientNumbers))
header('To: '.join(',', $this->recipientNumbers));
if (!$this->sendToOffline)
header('Send-to-offline: 0');
header('BotApi-Version: '.BOTAPI_VERSION);
echo $this->getProtocolMessage();
}
}
| michibo112/czacik.pl | MessageBuilder.php | PHP | gpl-3.0 | 7,896 |
<?php
/*
Gibbon, Flexible & Open School System
Copyright (C) 2010, Ross Parker
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/>.
*/
@session_start() ;
$proceed=FALSE ;
$public=FALSE ;
if (isset($_SESSION[$guid]["username"])==FALSE) {
$public=TRUE ;
//Get public access
$publicApplications=getSettingByScope($connection2, 'Application Form', 'publicApplications') ;
if ($publicApplications=="Y") {
$proceed=TRUE ;
}
}
else {
if (isActionAccessible($guid, $connection2, "/modules/Application Form/applicationForm.php")!=FALSE) {
$proceed=TRUE ;
}
}
//Set gibbonPersonID of the person completing the application
$gibbonPersonID=NULL ;
if (isset($_SESSION[$guid]["gibbonPersonID"])) {
$gibbonPersonID=$_SESSION[$guid]["gibbonPersonID"] ;
}
if ($proceed==FALSE) {
//Acess denied
print "<div class='error'>" ;
print _("You do not have access to this action.") ;
print "</div>" ;
}
else {
//Proceed!
print "<div class='trail'>" ;
if (isset($_SESSION[$guid]["username"])) {
print "<div class='trailHead'><a href='" . $_SESSION[$guid]["absoluteURL"] . "'>" . _("Home") . "</a> > <a href='" . $_SESSION[$guid]["absoluteURL"] . "/index.php?q=/modules/" . getModuleName($_GET["q"]) . "/" . getModuleEntry($_GET["q"], $connection2, $guid) . "'>" . _(getModuleName($_GET["q"])) . "</a> > </div><div class='trailEnd'>" . $_SESSION[$guid]["organisationNameShort"] . " " . _('Application Form') . "</div>" ;
}
else {
print "<div class='trailHead'><a href='" . $_SESSION[$guid]["absoluteURL"] . "'>" . _("Home") . "</a> > </div><div class='trailEnd'>" . $_SESSION[$guid]["organisationNameShort"] . " " . _('Application Form') . "</div>" ;
}
print "</div>" ;
//Get intro
$intro=getSettingByScope($connection2, 'Application Form', 'introduction') ;
if ($intro!="") {
print "<p>" ;
print $intro ;
print "</p>" ;
}
if (isset($_SESSION[$guid]["username"])==false) {
if ($intro!="") {
print "<br/><br/>" ;
}
print "<p style='font-weight: bold; text-decoration: none; color: #c00'><i><u>" . sprintf(_('If you have an %1$s %2$s account, please log in now to prevent creation of duplicate data about you! Once logged in, you can find the form under People > Data in the main menu.'), $_SESSION[$guid]["organisationNameShort"], $_SESSION[$guid]["systemName"]) . "</u></i> " . sprintf(_('If you do not have an %1$s %2$s account, please use the form below.'), $_SESSION[$guid]["organisationNameShort"], $_SESSION[$guid]["systemName"]) . "</p>" ;
}
if (isset($_GET["addReturn"])) { $addReturn=$_GET["addReturn"] ; } else { $addReturn="" ; }
$addReturnMessage="" ;
$class="error" ;
if (!($addReturn=="")) {
if ($addReturn=="fail0") {
$addReturnMessage=_("Your request failed because you do not have access to this action.") ;
}
else if ($addReturn=="fail2") {
$addReturnMessage=_("Your request failed due to a database error.") ;
}
else if ($addReturn=="fail3") {
$addReturnMessage=_("Your request failed because your inputs were invalid.") ;
}
else if ($addReturn=="fail4") {
$addReturnMessage=_("Your request failed because your inputs were invalid.") ;
}
else if ($addReturn=="success0" OR $addReturn=="success1" OR $addReturn=="success2" OR $addReturn=="success4") {
if ($addReturn=="success0") {
$addReturnMessage=_("Your application was successfully submitted. Our admissions team will review your application and be in touch in due course.") ;
}
else if ($addReturn=="success1") {
$addReturnMessage=_("Your application was successfully submitted and payment has been made to your credit card. Our admissions team will review your application and be in touch in due course.") ;
}
else if ($addReturn=="success2") {
$addReturnMessage=_("Your application was successfully submitted, but payment could not be made to your credit card. Our admissions team will review your application and be in touch in due course.") ;
}
else if ($addReturn=="success3") {
$addReturnMessage=_("Your application was successfully submitted, payment has been made to your credit card, but there has been an error recording your payment. Please print this screen and contact the school ASAP. Our admissions team will review your application and be in touch in due course.") ;
}
else if ($addReturn=="success4") {
$addReturnMessage=_("Your application was successfully submitted, but payment could not be made as the payment gateway does not support the system's currency. Our admissions team will review your application and be in touch in due course.") ;
}
if (isset($_GET["id"])) {
if ($_GET["id"]!="") {
$addReturnMessage=$addReturnMessage . "<br/><br/>" . _('If you need to contact the school in reference to this application, please quote the following number:') . " <b><u>" . $_GET["id"] . "</b></u>." ;
}
}
if ($_SESSION[$guid]["organisationAdmissionsName"]!="" AND $_SESSION[$guid]["organisationAdmissionsEmail"]!="") {
$addReturnMessage=$addReturnMessage . "<br/><br/>Please contact <a href='mailto:" . $_SESSION[$guid]["organisationAdmissionsEmail"] . "'>" . $_SESSION[$guid]["organisationAdmissionsName"] . "</a> if you have any questions, comments or complaints." ;
}
$class="success" ;
}
print "<div class='$class'>" ;
print $addReturnMessage;
print "</div>" ;
}
$currency=getSettingByScope($connection2, "System", "currency") ;
$applicationFee=getSettingByScope($connection2, "Application Form", "applicationFee") ;
$enablePayments=getSettingByScope($connection2, "System", "enablePayments") ;
$paypalAPIUsername=getSettingByScope($connection2, "System", "paypalAPIUsername") ;
$paypalAPIPassword=getSettingByScope($connection2, "System", "paypalAPIPassword") ;
$paypalAPISignature=getSettingByScope($connection2, "System", "paypalAPISignature") ;
if ($applicationFee>0 AND is_numeric($applicationFee)) {
print "<div class='warning'>" ;
print _("Please note that there is an application fee of:") . " <b><u>" . $currency . $applicationFee . "</u></b>." ;
if ($enablePayments=="Y" AND $paypalAPIUsername!="" AND $paypalAPIPassword!="" AND $paypalAPISignature!="") {
print " " . _('Payment must be made by credit card, using our secure PayPal payment gateway. When you press Submit at the end of this form, you will be directed to PayPal in order to make payment. During this process we do not see or store your credit card details.') ;
}
print "</div>" ;
}
?>
<form method="post" action="<?php print $_SESSION[$guid]["absoluteURL"] . "/modules/" . $_SESSION[$guid]["module"] . "/applicationFormProcess.php" ?>" enctype="multipart/form-data">
<table class='smallIntBorder' cellspacing='0' style="width: 100%">
<tr class='break'>
<td colspan=2>
<h3><?php print _('Student') ?></h3>
</td>
</tr>
<tr>
<td colspan=2>
<h4><?php print _('Student Personal Data') ?></h4>
</td>
</tr>
<tr>
<td style='width: 275px'>
<b><?php print _('Surname') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Family name as shown in ID documents.') ?></i></span>
</td>
<td class="right">
<input name="surname" id="surname" maxlength=30 value="" type="text" style="width: 300px">
<script type="text/javascript">
var surname=new LiveValidation('surname');
surname.add(Validate.Presence);
</script>
</td>
</tr>
<tr>
<td>
<b><?php print _('First Name') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('First name as shown in ID documents.') ?></i></span>
</td>
<td class="right">
<input name="firstName" id="firstName" maxlength=30 value="" type="text" style="width: 300px">
<script type="text/javascript">
var firstName=new LiveValidation('firstName');
firstName.add(Validate.Presence);
</script>
</td>
</tr>
<tr>
<td>
<b><?php print _('Preferred Name') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Most common name, alias, nickname, etc.') ?></i></span>
</td>
<td class="right">
<input name="preferredName" id="preferredName" maxlength=30 value="" type="text" style="width: 300px">
<script type="text/javascript">
var preferredName=new LiveValidation('preferredName');
preferredName.add(Validate.Presence);
</script>
</td>
</tr>
<tr>
<td>
<b><?php print _('Official Name') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Full name as shown in ID documents.') ?></i></span>
</td>
<td class="right">
<input title='Please enter full name as shown in ID documents' name="officialName" id="officialName" maxlength=150 value="" type="text" style="width: 300px">
<script type="text/javascript">
var officialName=new LiveValidation('officialName');
officialName.add(Validate.Presence);
</script>
</td>
</tr>
<tr>
<td>
<b><?php print _('Name In Characters') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Chinese or other character-based name.') ?></i></span>
</td>
<td class="right">
<input name="nameInCharacters" id="nameInCharacters" maxlength=20 value="" type="text" style="width: 300px">
</td>
</tr>
<tr>
<td>
<b><?php print _('Gender') ?> *</b><br/>
</td>
<td class="right">
<select name="gender" id="gender" style="width: 302px">
<option value="Please select..."><?php print _('Please select...') ?></option>
<option value="F"><?php print _('Female') ?></option>
<option value="M"><?php print _('Male') ?></option>
</select>
<script type="text/javascript">
var gender=new LiveValidation('gender');
gender.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<tr>
<td>
<b><?php print _('Date of Birth') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Format:') . " " . $_SESSION[$guid]["i18n"]["dateFormat"] ?></i></span>
</td>
<td class="right">
<input name="dob" id="dob" maxlength=10 value="" type="text" style="width: 300px">
<script type="text/javascript">
var dob=new LiveValidation('dob');
dob.add( Validate.Format, {pattern: <?php if ($_SESSION[$guid]["i18n"]["dateFormatRegEx"]=="") { print "/^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/i" ; } else { print $_SESSION[$guid]["i18n"]["dateFormatRegEx"] ; } ?>, failureMessage: "Use <?php if ($_SESSION[$guid]["i18n"]["dateFormat"]=="") { print "dd/mm/yyyy" ; } else { print $_SESSION[$guid]["i18n"]["dateFormat"] ; }?>." } );
dob.add(Validate.Presence);
</script>
<script type="text/javascript">
$(function() {
$( "#dob" ).datepicker();
});
</script>
</td>
</tr>
<tr>
<td colspan=2>
<h4><?php print _('Student Background') ?></h4>
</td>
</tr>
<tr>
<td>
<b><?php print _('Home Language') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('The primary language used in the student\'s home.') ?></i></span>
</td>
<td class="right">
<input name="languageHome" id="languageHome" maxlength=30 value="" type="text" style="width: 300px">
</td>
<script type="text/javascript">
$(function() {
var availableTags=[
<?php
try {
$dataAuto=array();
$sqlAuto="SELECT DISTINCT languageHome FROM gibbonApplicationForm ORDER BY languageHome" ;
$resultAuto=$connection2->prepare($sqlAuto);
$resultAuto->execute($dataAuto);
}
catch(PDOException $e) { }
while ($rowAuto=$resultAuto->fetch()) {
print "\"" . $rowAuto["languageHome"] . "\", " ;
}
?>
];
$( "#languageHome" ).autocomplete({source: availableTags});
});
</script>
<script type="text/javascript">
var languageHome=new LiveValidation('languageHome');
languageHome.add(Validate.Presence);
</script>
</tr>
<tr>
<td>
<b><?php print _('First Language') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Student\'s native/first/mother language.') ?></i></span>
</td>
<td class="right">
<input name="languageFirst" id="languageFirst" maxlength=30 value="" type="text" style="width: 300px">
</td>
<script type="text/javascript">
$(function() {
var availableTags=[
<?php
try {
$dataAuto=array();
$sqlAuto="SELECT DISTINCT languageFirst FROM gibbonApplicationForm ORDER BY languageFirst" ;
$resultAuto=$connection2->prepare($sqlAuto);
$resultAuto->execute($dataAuto);
}
catch(PDOException $e) { }
while ($rowAuto=$resultAuto->fetch()) {
print "\"" . $rowAuto["languageFirst"] . "\", " ;
}
?>
];
$( "#languageFirst" ).autocomplete({source: availableTags});
});
</script>
<script type="text/javascript">
var languageFirst=new LiveValidation('languageFirst');
languageFirst.add(Validate.Presence);
</script>
</tr>
<tr>
<td>
<b><?php print _('Second Language') ?></b><br/>
</td>
<td class="right">
<input name="languageSecond" id="languageSecond" maxlength=30 value="" type="text" style="width: 300px">
</td>
<script type="text/javascript">
$(function() {
var availableTags=[
<?php
try {
$dataAuto=array();
$sqlAuto="SELECT DISTINCT languageSecond FROM gibbonApplicationForm ORDER BY languageSecond" ;
$resultAuto=$connection2->prepare($sqlAuto);
$resultAuto->execute($dataAuto);
}
catch(PDOException $e) { }
while ($rowAuto=$resultAuto->fetch()) {
print "\"" . $rowAuto["languageSecond"] . "\", " ;
}
?>
];
$( "#languageSecond" ).autocomplete({source: availableTags});
});
</script>
</tr>
<tr>
<td>
<b><?php print _('Third Language') ?></b><br/>
</td>
<td class="right">
<input name="languageThird" id="languageThird" maxlength=30 value="" type="text" style="width: 300px">
</td>
<script type="text/javascript">
$(function() {
var availableTags=[
<?php
try {
$dataAuto=array();
$sqlAuto="SELECT DISTINCT languageThird FROM gibbonApplicationForm ORDER BY languageThird" ;
$resultAuto=$connection2->prepare($sqlAuto);
$resultAuto->execute($dataAuto);
}
catch(PDOException $e) { }
while ($rowAuto=$resultAuto->fetch()) {
print "\"" . $rowAuto["languageThird"] . "\", " ;
}
?>
];
$( "#languageThird" ).autocomplete({source: availableTags});
});
</script>
</tr>
<tr>
<td>
<b><?php print _('Country of Birth') ?></b><br/>
</td>
<td class="right">
<select name="countryOfBirth" id="countryOfBirth" style="width: 302px">
<?php
try {
$dataSelect=array();
$sqlSelect="SELECT printable_name FROM gibbonCountry ORDER BY printable_name" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) { }
print "<option value=''></option>" ;
while ($rowSelect=$resultSelect->fetch()) {
print "<option value='" . $rowSelect["printable_name"] . "'>" . htmlPrep(_($rowSelect["printable_name"])) . "</option>" ;
}
?>
</select>
</td>
</tr>
<tr>
<td>
<b><?php print _('Citizenship') ?></b><br/>
</td>
<td class="right">
<select name="citizenship1" id="citizenship1" style="width: 302px">
<?php
print "<option value=''></option>" ;
$nationalityList=getSettingByScope($connection2, "User Admin", "nationality") ;
if ($nationalityList=="") {
try {
$dataSelect=array();
$sqlSelect="SELECT printable_name FROM gibbonCountry ORDER BY printable_name" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) { }
while ($rowSelect=$resultSelect->fetch()) {
print "<option value='" . $rowSelect["printable_name"] . "'>" . htmlPrep(_($rowSelect["printable_name"])) . "</option>" ;
}
}
else {
$nationalities=explode(",", $nationalityList) ;
foreach ($nationalities as $nationality) {
print "<option value='" . trim($nationality) . "'>" . trim($nationality) . "</option>" ;
}
}
?>
</select>
</td>
</tr>
<tr>
<td>
<b><?php print _('Citizenship Passport Number') ?></b><br/>
</td>
<td class="right">
<input name="citizenship1Passport" id="citizenship1Passport" maxlength=30 value="" type="text" style="width: 300px">
</td>
</tr>
<tr>
<td>
<?php
if ($_SESSION[$guid]["country"]=="") {
print "<b>" . _('National ID Card Number') . "</b><br/>" ;
}
else {
print "<b>" . $_SESSION[$guid]["country"] . " " . _('ID Card Number') . "</b><br/>" ;
}
?>
</td>
<td class="right">
<input name="nationalIDCardNumber" id="nationalIDCardNumber" maxlength=30 value="" type="text" style="width: 300px">
</td>
</tr>
<tr>
<td>
<?php
if ($_SESSION[$guid]["country"]=="") {
print "<b>" . _('Residency/Visa Type') . "</b><br/>" ;
}
else {
print "<b>" . $_SESSION[$guid]["country"] . " " . _('Residency/Visa Type') . "</b><br/>" ;
}
?>
</td>
<td class="right">
<?php
$residencyStatusList=getSettingByScope($connection2, "User Admin", "residencyStatus") ;
if ($residencyStatusList=="") {
print "<input name='residencyStatus' id='residencyStatus' maxlength=30 value='' type='text' style='width: 300px'>" ;
}
else {
print "<select name='residencyStatus' id='residencyStatus' style='width: 302px'>" ;
print "<option value=''></option>" ;
$residencyStatuses=explode(",", $residencyStatusList) ;
foreach ($residencyStatuses as $residencyStatus) {
$selected="" ;
if (trim($residencyStatus)==$row["residencyStatus"]) {
$selected="selected" ;
}
print "<option $selected value='" . trim($residencyStatus) . "'>" . trim($residencyStatus) . "</option>" ;
}
print "</select>" ;
}
?>
</td>
</tr>
<tr>
<td>
<?php
if ($_SESSION[$guid]["country"]=="") {
print "<b>" . _('Visa Expiry Date') . "</b><br/>" ;
}
else {
print "<b>" . $_SESSION[$guid]["country"] . " " . _('Visa Expiry Date') . "</b><br/>" ;
}
print "<span style='font-size: 90%'><i>Format: " ; if ($_SESSION[$guid]["i18n"]["dateFormat"]=="") { print "dd/mm/yyyy" ; } else { print $_SESSION[$guid]["i18n"]["dateFormat"] ; } print ". " . _('If relevant.') . "</i></span>" ;
?>
</td>
<td class="right">
<input name="visaExpiryDate" id="visaExpiryDate" maxlength=10 value="" type="text" style="width: 300px">
<script type="text/javascript">
var visaExpiryDate=new LiveValidation('visaExpiryDate');
visaExpiryDate.add( Validate.Format, {pattern: <?php if ($_SESSION[$guid]["i18n"]["dateFormatRegEx"]=="") { print "/^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/i" ; } else { print $_SESSION[$guid]["i18n"]["dateFormatRegEx"] ; } ?>, failureMessage: "Use <?php if ($_SESSION[$guid]["i18n"]["dateFormat"]=="") { print "dd/mm/yyyy" ; } else { print $_SESSION[$guid]["i18n"]["dateFormat"] ; }?>." } );
</script>
<script type="text/javascript">
$(function() {
$( "#visaExpiryDate" ).datepicker();
});
</script>
</td>
</tr>
<tr>
<td colspan=2>
<h4><?php print _('Student Contact') ?></h4>
</td>
</tr>
<tr>
<td>
<b><?php print _('Email') ?></b><br/>
</td>
<td class="right">
<input name="email" id="email" maxlength=50 value="" type="text" style="width: 300px">
<script type="text/javascript">
var email=new LiveValidation('email');
email.add(Validate.Email);
</script>
</td>
</tr>
<?php
for ($i=1; $i<3; $i++) {
?>
<tr>
<td>
<b><?php print _('Phone') ?> <?php print $i ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Type, country code, number.') ?></i></span>
</td>
<td class="right">
<input name="phone<?php print $i ?>" id="phone<?php print $i ?>" maxlength=20 value="" type="text" style="width: 160px">
<select name="phone<?php print $i ?>CountryCode" id="phone<?php print $i ?>CountryCode" style="width: 60px">
<?php
print "<option value=''></option>" ;
try {
$dataSelect=array();
$sqlSelect="SELECT * FROM gibbonCountry ORDER BY printable_name" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) { }
while ($rowSelect=$resultSelect->fetch()) {
print "<option value='" . $rowSelect["iddCountryCode"] . "'>" . htmlPrep($rowSelect["iddCountryCode"]) . " - " . htmlPrep(_($rowSelect["printable_name"])) . "</option>" ;
}
?>
</select>
<select style="width: 70px" name="phone<?php print $i ?>Type">
<option value=""></option>
<option value="Mobile"><?php print _('Mobile') ?></option>
<option value="Home"><?php print _('Home') ?></option>
<option value="Work"><?php print _('Work') ?></option>
<option value="Fax"><?php print _('Fax') ?></option>
<option value="Pager"><?php print _('Pager') ?></option>
<option value="Other"><?php print _('Other') ?></option>
</select>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan=2>
<h4><?php print _('Student Medical & Development') ?></h4>
</td>
</tr>
<tr>
<td colspan=2 style='padding-top: 15px'>
<b><?php print _('Medical Information') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Please indicate any medical conditions.') ?></i></span><br/>
<textarea name="medicalInformation" id="medicalInformation" rows=5 style="width:738px; margin: 5px 0px 0px 0px"></textarea>
</td>
</tr>
<tr>
<td colspan=2 style='padding-top: 15px'>
<b><?php print _('Development Information') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Provide any comments or information concerning your child\'s development that may be relevant to your child\’s performance in the classroom or elsewhere? (Incorrect or withheld information may affect continued enrolment).') ?></i></span><br/>
<textarea name="developmentInformation" id="developmentInformation" rows=5 style="width:738px; margin: 5px 0px 0px 0px"></textarea>
</td>
</tr>
<tr>
<td colspan=2>
<h4><?php print _('Student Education') ?></h4>
</td>
</tr>
<tr>
<td>
<b><?php print _('Anticipated Year of Entry') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('What school year will the student join in?') ?></i></span>
</td>
<td class="right">
<select name="gibbonSchoolYearIDEntry" id="gibbonSchoolYearIDEntry" style="width: 302px">
<?php
print "<option value='Please select...'>" . _('Please select...') . "</option>" ;
try {
$dataSelect=array();
$sqlSelect="SELECT * FROM gibbonSchoolYear WHERE (status='Current' OR status='Upcoming') ORDER BY sequenceNumber" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) {
print "<div class='error'>" . $e->getMessage() . "</div>" ;
}
while ($rowSelect=$resultSelect->fetch()) {
print "<option value='" . $rowSelect["gibbonSchoolYearID"] . "'>" . htmlPrep($rowSelect["name"]) . "</option>" ;
}
?>
</select>
<script type="text/javascript">
var gibbonSchoolYearIDEntry=new LiveValidation('gibbonSchoolYearIDEntry');
gibbonSchoolYearIDEntry.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<tr>
<td>
<b><?php print _('Intended Start Date') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Student\'s intended first day at school.') ?><br/><?php print _('Format:') ?> <?php if ($_SESSION[$guid]["i18n"]["dateFormat"]=="") { print "dd/mm/yyyy" ; } else { print $_SESSION[$guid]["i18n"]["dateFormat"] ; }?></i></span>
</td>
<td class="right">
<input name="dateStart" id="dateStart" maxlength=10 value="" type="text" style="width: 300px">
<script type="text/javascript">
var dateStart=new LiveValidation('dateStart');
dateStart.add( Validate.Format, {pattern: <?php if ($_SESSION[$guid]["i18n"]["dateFormatRegEx"]=="") { print "/^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/i" ; } else { print $_SESSION[$guid]["i18n"]["dateFormatRegEx"] ; } ?>, failureMessage: "Use <?php if ($_SESSION[$guid]["i18n"]["dateFormat"]=="") { print "dd/mm/yyyy" ; } else { print $_SESSION[$guid]["i18n"]["dateFormat"] ; }?>." } );
dateStart.add(Validate.Presence);
</script>
<script type="text/javascript">
$(function() {
$( "#dateStart" ).datepicker();
});
</script>
</td>
</tr>
<tr>
<td>
<b><?php print _('Year Group at Entry') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Which year level will student enter.') ?></i></span>
</td>
<td class="right">
<select name="gibbonYearGroupIDEntry" id="gibbonYearGroupIDEntry" style="width: 302px">
<?php
print "<option value='Please select...'>" . _('Please select...') . "</option>" ;
try {
$dataSelect=array();
$sqlSelect="SELECT * FROM gibbonYearGroup ORDER BY sequenceNumber" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) {
print "<div class='error'>" . $e->getMessage() . "</div>" ;
}
while ($rowSelect=$resultSelect->fetch()) {
print "<option value='" . $rowSelect["gibbonYearGroupID"] . "'>" . htmlPrep(_($rowSelect["name"])) . "</option>" ;
}
?>
</select>
<script type="text/javascript">
var gibbonYearGroupIDEntry=new LiveValidation('gibbonYearGroupIDEntry');
gibbonYearGroupIDEntry.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<?php
$dayTypeOptions=getSettingByScope($connection2, 'User Admin', 'dayTypeOptions') ;
if ($dayTypeOptions!="") {
?>
<tr>
<td>
<b><?php print _('Day Type') ?></b><br/>
<span style="font-size: 90%"><i><?php print getSettingByScope($connection2, 'User Admin', 'dayTypeText') ; ?></i></span>
</td>
<td class="right">
<select name="dayType" id="dayType" style="width: 302px">
<?php
$dayTypes=explode(",", $dayTypeOptions) ;
foreach ($dayTypes as $dayType) {
print "<option value='" . trim($dayType) . "'>" . trim($dayType) . "</option>" ;
}
?>
</select>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan=2 style='padding-top: 15px'>
<b><?php print _('Previous Schools') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Please give information on the last two schools attended by the applicant.') ?></i></span>
</td>
</tr>
<tr>
<td colspan=2>
<?php
print "<table cellspacing='0' style='width: 100%'>" ;
print "<tr class='head'>" ;
print "<th>" ;
print _("School Name") ;
print "</th>" ;
print "<th>" ;
print _("Address") ;
print "</th>" ;
print "<th>" ;
print sprintf(_('Grades%1$sAttended'), "<br/>") ;
print "</th>" ;
print "<th>" ;
print sprintf(_('Language of%1$sInstruction'), "<br/>") ;
print "</th>" ;
print "<th>" ;
print _("Joining Date") . "<br/><span style='font-size: 80%'>" ; if ($_SESSION[$guid]["i18n"]["dateFormat"]=="") { print "dd/mm/yyyy" ; } else { print $_SESSION[$guid]["i18n"]["dateFormat"] ; } print "</span>" ;
print "</th>" ;
print "</tr>" ;
for ($i=1; $i<3; $i++) {
if ((($i%2)-1)==0) {
$rowNum="even" ;
}
else {
$rowNum="odd" ;
}
print "<tr class=$rowNum>" ;
print "<td>" ;
print "<input name='schoolName$i' id='schoolName$i' maxlength=50 value='' type='text' style='width:120px; float: left'>" ;
print "</td>" ;
print "<td>" ;
print "<input name='schoolAddress$i' id='schoolAddress$i' maxlength=255 value='' type='text' style='width:120px; float: left'>" ;
print "</td>" ;
print "<td>" ;
print "<input name='schoolGrades$i' id='schoolGrades$i' maxlength=20 value='' type='text' style='width:70px; float: left'>" ;
print "</td>" ;
print "<td>" ;
print "<input name='schoolLanguage$i' id='schoolLanguage$i' maxlength=50 value='' type='text' style='width:100px; float: left'>" ;
?>
<script type="text/javascript">
$(function() {
var availableTags=[
<?php
try {
$dataAuto=array();
$sqlAuto="SELECT DISTINCT schoolLanguage" . $i . " FROM gibbonApplicationForm ORDER BY schoolLanguage" . $i ;
$resultAuto=$connection2->prepare($sqlAuto);
$resultAuto->execute($dataAuto);
}
catch(PDOException $e) { }
while ($rowAuto=$resultAuto->fetch()) {
print "\"" . $rowAuto["schoolLanguage" . $i] . "\", " ;
}
?>
];
$( "#schoolLanguage<?php print $i ?>" ).autocomplete({source: availableTags});
});
</script>
<?php
print "</td>" ;
print "<td>" ;
?>
<input name="<?php print "schoolDate$i" ?>" id="<?php print "schoolDate$i" ?>" maxlength=10 value="" type="text" style="width:90px; float: left">
<script type="text/javascript">
$(function() {
$( "#<?php print "schoolDate$i" ?>" ).datepicker();
});
</script>
<?php
print "</td>" ;
print "</tr>" ;
}
print "</table>" ;
?>
</td>
</tr>
<?php
//FAMILY
try {
$dataSelect=array("gibbonPersonID"=>$gibbonPersonID);
$sqlSelect="SELECT * FROM gibbonFamily JOIN gibbonFamilyAdult ON (gibbonFamily.gibbonFamilyID=gibbonFamilyAdult.gibbonFamilyID) WHERE gibbonFamilyAdult.gibbonPersonID=:gibbonPersonID ORDER BY name" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) { }
if ($public==TRUE OR $resultSelect->rowCount()<1) {
?>
<input type="hidden" name="gibbonFamily" value="FALSE">
<tr class='break'>
<td colspan=2>
<h3>
<?php print _('Home Address') ?>
</h3>
<p>
<?php print _('This address will be used for all members of the family. If an individual within the family needs a different address, this can be set through Data Updater after admission.') ?>
</p>
</td>
</tr>
<tr>
<td>
<b><?php print _('Home Address') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Unit, Building, Street') ?></i></span>
</td>
<td class="right">
<input name="homeAddress" id="homeAddress" maxlength=255 value="" type="text" style="width: 300px">
<script type="text/javascript">
var homeAddress=new LiveValidation('homeAddress');
homeAddress.add(Validate.Presence);
</script>
</td>
</tr>
<tr>
<td>
<b><?php print _('Home Address (District)') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('County, State, District') ?></i></span>
</td>
<td class="right">
<input name="homeAddressDistrict" id="homeAddressDistrict" maxlength=30 value="" type="text" style="width: 300px">
</td>
<script type="text/javascript">
$(function() {
var availableTags=[
<?php
try {
$dataAuto=array();
$sqlAuto="SELECT DISTINCT name FROM gibbonDistrict ORDER BY name" ;
$resultAuto=$connection2->prepare($sqlAuto);
$resultAuto->execute($dataAuto);
}
catch(PDOException $e) { }
while ($rowAuto=$resultAuto->fetch()) {
print "\"" . $rowAuto["name"] . "\", " ;
}
?>
];
$( "#homeAddressDistrict" ).autocomplete({source: availableTags});
});
</script>
<script type="text/javascript">
var homeAddressDistrict=new LiveValidation('homeAddressDistrict');
homeAddressDistrict.add(Validate.Presence);
</script>
</tr>
<tr>
<td>
<b><?php print _('Home Address (Country)') ?> *</b><br/>
</td>
<td class="right">
<select name="homeAddressCountry" id="homeAddressCountry" style="width: 302px">
<?php
try {
$dataSelect=array();
$sqlSelect="SELECT printable_name FROM gibbonCountry ORDER BY printable_name" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) { }
print "<option value='Please select...'>" . _('Please select...') . "</option>" ;
while ($rowSelect=$resultSelect->fetch()) {
print "<option value='" . $rowSelect["printable_name"] . "'>" . htmlPrep(_($rowSelect["printable_name"])) . "</option>" ;
}
?>
</select>
<script type="text/javascript">
var homeAddressCountry=new LiveValidation('homeAddressCountry');
homeAddressCountry.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<?php
if (isset($_SESSION[$guid]["username"])) {
$start=2 ;
?>
<tr class='break'>
<td colspan=2>
<h3>
<?php print _('Parent/Guardian 1') ?>
<?php
if ($i==1) {
print "<span style='font-size: 75%'></span>" ;
}
?>
</h3>
</td>
</tr>
<tr>
<td>
<b><?php print _('Username') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('System login ID.') ?></i></span>
</td>
<td class="right">
<input readonly name='parent1username' maxlength=30 value="<?php print $_SESSION[$guid]["username"] ?>" type="text" style="width: 300px">
</td>
</tr>
<tr>
<td>
<b><?php print _('Surname') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Family name as shown in ID documents.') ?></i></span>
</td>
<td class="right">
<input readonly name='parent1surname' maxlength=30 value="<?php print $_SESSION[$guid]["surname"] ?>" type="text" style="width: 300px">
</td>
</tr>
<tr>
<td>
<b><?php print _('Preferred Name') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Most common name, alias, nickname, etc.') ?></i></span>
</td>
<td class="right">
<input readonly name='parent1preferredName' maxlength=30 value="<?php print $_SESSION[$guid]["preferredName"] ?>" type="text" style="width: 300px">
</td>
</tr>
<tr>
<td>
<b><?php print _('Relationship') ?> *</b><br/>
</td>
<td class="right">
<select name="parent1relationship" id="parent1relationship" style="width: 302px">
<option value="Please select..."><?php print _('Please select...') ?></option>
<option value="Mother"><?php print _('Mother') ?></option>
<option value="Father"><?php print _('Father') ?></option>
<option value="Step-Mother"><?php print _('Step-Mother') ?></option>
<option value="Step-Father"><?php print _('Step-Father') ?></option>
<option value="Adoptive Parent"><?php print _('Adoptive Parent') ?></option>
<option value="Guardian"><?php print _('Guardian') ?></option>
<option value="Grandmother"><?php print _('Grandmother') ?></option>
<option value="Grandfather"><?php print _('Grandfather') ?></option>
<option value="Aunt"><?php print _('Aunt') ?></option>
<option value="Uncle"><?php print _('Uncle') ?></option>
<option value="Nanny/Helper"><?php print _('Nanny/Helper') ?></option>
<option value="Other"><?php print _('Other') ?></option>
</select>
<script type="text/javascript">
var parent1relationship=new LiveValidation('parent1relationship');
parent1relationship.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<input name='parent1gibbonPersonID' value="<?php print $gibbonPersonID ?>" type="hidden">
<?php
}
else {
$start=1 ;
}
for ($i=$start;$i<3;$i++) {
?>
<tr class='break'>
<td colspan=2>
<h3>
<?php print _('Parent/Guardian') ?> <?php print $i ?>
<?php
if ($i==1) {
print "<span style='font-size: 75%'> (e.g. mother)</span>" ;
}
else if ($i==2 AND $gibbonPersonID=="") {
print "<span style='font-size: 75%'> (e.g. father)</span>" ;
}
?>
</h3>
</td>
</tr>
<?php
if ($i==2) {
?>
<tr>
<td class='right' colspan=2>
<script type="text/javascript">
/* Advanced Options Control */
$(document).ready(function(){
$("#secondParent").click(function(){
if ($('input[name=secondParent]:checked').val()=="No" ) {
$(".secondParent").slideUp("fast");
$("#parent2title").attr("disabled", "disabled");
$("#parent2surname").attr("disabled", "disabled");
$("#parent2firstName").attr("disabled", "disabled");
$("#parent2preferredName").attr("disabled", "disabled");
$("#parent2officialName").attr("disabled", "disabled");
$("#parent2nameInCharacters").attr("disabled", "disabled");
$("#parent2gender").attr("disabled", "disabled");
$("#parent2relationship").attr("disabled", "disabled");
$("#parent2languageFirst").attr("disabled", "disabled");
$("#parent2languageSecond").attr("disabled", "disabled");
$("#parent2citizenship1").attr("disabled", "disabled");
$("#parent2nationalIDCardNumber").attr("disabled", "disabled");
$("#parent2residencyStatus").attr("disabled", "disabled");
$("#parent2visaExpiryDate").attr("disabled", "disabled");
$("#parent2email").attr("disabled", "disabled");
$("#parent2phone1Type").attr("disabled", "disabled");
$("#parent2phone1CountryCode").attr("disabled", "disabled");
$("#parent2phone1").attr("disabled", "disabled");
$("#parent2phone2Type").attr("disabled", "disabled");
$("#parent2phone2CountryCode").attr("disabled", "disabled");
$("#parent2phone2").attr("disabled", "disabled");
$("#parent2profession").attr("disabled", "disabled");
$("#parent2employer").attr("disabled", "disabled");
}
else {
$(".secondParent").slideDown("fast", $(".secondParent").css("display","table-row"));
$("#parent2title").removeAttr("disabled");
$("#parent2surname").removeAttr("disabled");
$("#parent2firstName").removeAttr("disabled");
$("#parent2preferredName").removeAttr("disabled");
$("#parent2officialName").removeAttr("disabled");
$("#parent2nameInCharacters").removeAttr("disabled");
$("#parent2gender").removeAttr("disabled");
$("#parent2relationship").removeAttr("disabled");
$("#parent2languageFirst").removeAttr("disabled");
$("#parent2languageSecond").removeAttr("disabled");
$("#parent2citizenship1").removeAttr("disabled");
$("#parent2nationalIDCardNumber").removeAttr("disabled");
$("#parent2residencyStatus").removeAttr("disabled");
$("#parent2visaExpiryDate").removeAttr("disabled");
$("#parent2email").removeAttr("disabled");
$("#parent2phone1Type").removeAttr("disabled");
$("#parent2phone1CountryCode").removeAttr("disabled");
$("#parent2phone1").removeAttr("disabled");
$("#parent2phone2Type").removeAttr("disabled");
$("#parent2phone2CountryCode").removeAttr("disabled");
$("#parent2phone2").removeAttr("disabled");
$("#parent2profession").removeAttr("disabled");
$("#parent2employer").removeAttr("disabled");
}
});
});
</script>
<span style='font-weight: bold; font-style: italic'>Do not include a second parent/gaurdian <input id='secondParent' name='secondParent' type='checkbox' value='No'/></span>
</td>
</tr>
<?php
}
?>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td colspan=2>
<h4><?php print _('Parent/Guardian') ?> <?php print $i ?> <?php print _('Personal Data') ?></h4>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Title') ?> *</b><br/>
<span style="font-size: 90%"><i></i></span>
</td>
<td class="right">
<select style="width: 302px" id="<?php print "parent$i" ?>title" name="<?php print "parent$i" ?>title">
<option value="Please select..."><?php print _('Please select...') ?></option>
<option value="Ms.">Ms.</option>
<option value="Miss">Miss</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Dr.">Dr.</option>
</select>
<script type="text/javascript">
var <?php print "parent$i" ?>title=new LiveValidation('<?php print "parent$i" ?>title');
<?php print "parent$i" ?>title.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Surname') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Family name as shown in ID documents.') ?></i></span>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>surname" id="<?php print "parent$i" ?>surname" maxlength=30 value="" type="text" style="width: 300px">
<script type="text/javascript">
var <?php print "parent$i" ?>surname=new LiveValidation('<?php print "parent$i" ?>surname');
<?php print "parent$i" ?>surname.add(Validate.Presence);
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('First Name') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('First name as shown in ID documents.') ?></i></span>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>firstName" id="<?php print "parent$i" ?>firstName" maxlength=30 value="" type="text" style="width: 300px">
<script type="text/javascript">
var <?php print "parent$i" ?>firstName=new LiveValidation('<?php print "parent$i" ?>firstName');
<?php print "parent$i" ?>firstName.add(Validate.Presence);
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Preferred Name') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Most common name, alias, nickname, etc.') ?></i></span>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>preferredName" id="<?php print "parent$i" ?>preferredName" maxlength=30 value="" type="text" style="width: 300px">
<script type="text/javascript">
var <?php print "parent$i" ?>preferredName=new LiveValidation('<?php print "parent$i" ?>preferredName');
<?php print "parent$i" ?>preferredName.add(Validate.Presence);
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Official Name') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Full name as shown in ID documents.') ?></i></span>
</td>
<td class="right">
<input title='Please enter full name as shown in ID documents' name="<?php print "parent$i" ?>officialName" id="<?php print "parent$i" ?>officialName" maxlength=150 value="" type="text" style="width: 300px">
<script type="text/javascript">
var <?php print "parent$i" ?>officialName=new LiveValidation('<?php print "parent$i" ?>officialName');
<?php print "parent$i" ?>officialName.add(Validate.Presence);
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Name In Characters') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Chinese or other character-based name.') ?></i></span>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>nameInCharacters" id="<?php print "parent$i" ?>nameInCharacters" maxlength=20 value="" type="text" style="width: 300px">
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Gender') ?> *</b><br/>
</td>
<td class="right">
<select name="<?php print "parent$i" ?>gender" id="<?php print "parent$i" ?>gender" style="width: 302px">
<option value="Please select..."><?php print _('Please select...') ?></option>
<option value="F"><?php print _('Female') ?></option>
<option value="M"><?php print _('Male') ?></option>
</select>
<script type="text/javascript">
var <?php print "parent$i" ?>gender=new LiveValidation('<?php print "parent$i" ?>gender');
<?php print "parent$i" ?>gender.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Relationship') ?> *</b><br/>
</td>
<td class="right">
<select name="<?php print "parent$i" ?>relationship" id="<?php print "parent$i" ?>relationship" style="width: 302px">
<option value="Please select..."><?php print _('Please select...') ?></option>
<option value="Mother"><?php print _('Mother') ?></option>
<option value="Father"><?php print _('Father') ?></option>
<option value="Step-Mother"><?php print _('Step-Mother') ?></option>
<option value="Step-Father"><?php print _('Step-Father') ?></option>
<option value="Adoptive Parent"><?php print _('Adoptive Parent') ?></option>
<option value="Guardian"><?php print _('Guardian') ?></option>
<option value="Grandmother"><?php print _('Grandmother') ?></option>
<option value="Grandfather"><?php print _('Grandfather') ?></option>
<option value="Aunt"><?php print _('Aunt') ?></option>
<option value="Uncle"><?php print _('Uncle') ?></option>
<option value="Nanny/Helper"><?php print _('Nanny/Helper') ?></option>
<option value="Other"><?php print _('Other') ?></option>
</select>
<script type="text/javascript">
var <?php print "parent$i" ?>relationship=new LiveValidation('<?php print "parent$i" ?>relationship');
<?php print "parent$i" ?>relationship.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td colspan=2>
<h4><?php print _('Parent/Guardian') ?> <?php print $i ?> <?php print _('Personal Background') ?></h4>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('First Language') ?></b><br/>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>languageFirst" id="<?php print "parent$i" ?>languageFirst" maxlength=30 value="" type="text" style="width: 300px">
</td>
<script type="text/javascript">
$(function() {
var availableTags=[
<?php
try {
$dataAuto=array();
$sqlAuto="SELECT DISTINCT languageFirst FROM gibbonApplicationForm ORDER BY languageFirst" ;
$resultAuto=$connection2->prepare($sqlAuto);
$resultAuto->execute($dataAuto);
}
catch(PDOException $e) { }
while ($rowAuto=$resultAuto->fetch()) {
print "\"" . $rowAuto["languageFirst"] . "\", " ;
}
?>
];
$( "#<?php print 'parent' . $i ?>languageFirst" ).autocomplete({source: availableTags});
});
</script>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Second Language') ?></b><br/>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>languageSecond" id="<?php print "parent$i" ?>languageSecond" maxlength=30 value="" type="text" style="width: 300px">
</td>
<script type="text/javascript">
$(function() {
var availableTags=[
<?php
try {
$dataAuto=array();
$sqlAuto="SELECT DISTINCT languageSecond FROM gibbonApplicationForm ORDER BY languageSecond" ;
$resultAuto=$connection2->prepare($sqlAuto);
$resultAuto->execute($dataAuto);
}
catch(PDOException $e) { }
while ($rowAuto=$resultAuto->fetch()) {
print "\"" . $rowAuto["languageSecond"] . "\", " ;
}
?>
];
$( "#<?php print 'parent' . $i ?>languageSecond" ).autocomplete({source: availableTags});
});
</script>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Citizenship') ?></b><br/>
</td>
<td class="right">
<select name="<?php print "parent$i" ?>citizenship1" id="<?php print "parent$i" ?>citizenship1" style="width: 302px">
<?php
print "<option value=''></option>" ;
$nationalityList=getSettingByScope($connection2, "User Admin", "nationality") ;
if ($nationalityList=="") {
try {
$dataSelect=array();
$sqlSelect="SELECT printable_name FROM gibbonCountry ORDER BY printable_name" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) { }
while ($rowSelect=$resultSelect->fetch()) {
print "<option value='" . $rowSelect["printable_name"] . "'>" . htmlPrep(_($rowSelect["printable_name"])) . "</option>" ;
}
}
else {
$nationalities=explode(",", $nationalityList) ;
foreach ($nationalities as $nationality) {
print "<option value='" . trim($nationality) . "'>" . trim($nationality) . "</option>" ;
}
}
?>
</select>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<?php
if ($_SESSION[$guid]["country"]=="") {
print "<b>" . _('National ID Card Number') . "</b><br/>" ;
}
else {
print "<b>" . $_SESSION[$guid]["country"] . " " . _('ID Card Number') . "</b><br/>" ;
}
?>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>nationalIDCardNumber" id="<?php print "parent$i" ?>nationalIDCardNumber" maxlength=30 value="" type="text" style="width: 300px">
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<?php
if ($_SESSION[$guid]["country"]=="") {
print "<b>" . _('Residency/Visa Type') . "</b><br/>" ;
}
else {
print "<b>" . $_SESSION[$guid]["country"] . " " . _('Residency/Visa Type') . "</b><br/>" ;
}
?>
</td>
<td class="right">
<?php
$residencyStatusList=getSettingByScope($connection2, "User Admin", "residencyStatus") ;
if ($residencyStatusList=="") {
print "<input name='parent" . $i . "residencyStatus' id='parent" . $i . "residencyStatus' maxlength=30 type='text' style='width: 300px'>" ;
}
else {
print "<select name='parent" . $i . "residencyStatus' id='parent" . $i . "residencyStatus' style='width: 302px'>" ;
print "<option value=''></option>" ;
$residencyStatuses=explode(",", $residencyStatusList) ;
foreach ($residencyStatuses as $residencyStatus) {
$selected="" ;
if (trim($residencyStatus)==$row["parent" . $i . "residencyStatus"]) {
$selected="selected" ;
}
print "<option $selected value='" . trim($residencyStatus) . "'>" . trim($residencyStatus) . "</option>" ;
}
print "</select>" ;
}
?>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<?php
if ($_SESSION[$guid]["country"]=="") {
print "<b>" . _('Visa Expiry Date') . "</b><br/>" ;
}
else {
print "<b>" . $_SESSION[$guid]["country"] . " " . _('Visa Expiry Date') . "</b><br/>" ;
}
print "<span style='font-size: 90%'><i>" . _('Format:') . " " ; if ($_SESSION[$guid]["i18n"]["dateFormat"]=="") { print "dd/mm/yyyy" ; } else { print $_SESSION[$guid]["i18n"]["dateFormat"] ; } print ". " . _('If relevant.') . "</i></span>" ;
?>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>visaExpiryDate" id="<?php print "parent$i" ?>visaExpiryDate" maxlength=10 value="" type="text" style="width: 300px">
<script type="text/javascript">
var <?php print "parent$i" ?>visaExpiryDate=new LiveValidation('<?php print "parent$i" ?>visaExpiryDate');
<?php print "parent$i" ?>visaExpiryDate.add( Validate.Format, {pattern: <?php if ($_SESSION[$guid]["i18n"]["dateFormatRegEx"]=="") { print "/^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/i" ; } else { print $_SESSION[$guid]["i18n"]["dateFormatRegEx"] ; } ?>, failureMessage: "Use <?php if ($_SESSION[$guid]["i18n"]["dateFormat"]=="") { print "dd/mm/yyyy" ; } else { print $_SESSION[$guid]["i18n"]["dateFormat"] ; }?>." } );
</script>
<script type="text/javascript">
$(function() {
$( "#<?php print "parent$i" ?>visaExpiryDate" ).datepicker();
});
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td colspan=2>
<h4><?php print _('Parent/Guardian') ?> <?php print $i ?> <?php print _('Contact') ?></h4>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Email') ?> *</b><br/>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>email" id="<?php print "parent$i" ?>email" maxlength=50 value="" type="text" style="width: 300px">
<script type="text/javascript">
var <?php print "parent$i" ?>email=new LiveValidation('<?php print "parent$i" ?>email');
<?php
print "parent$i" . "email.add(Validate.Email);";
print "parent$i" . "email.add(Validate.Presence);" ;
?>
</script>
</td>
</tr>
<?php
for ($y=1; $y<3; $y++) {
?>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Phone') ?> <?php print $y ; if ($y==1) { print " *" ;}?></b><br/>
<span style="font-size: 90%"><i><?php print _('Type, country code, number.') ?></i></span>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>phone<?php print $y ?>" id="<?php print "parent$i" ?>phone<?php print $y ?>" maxlength=20 value="" type="text" style="width: 160px">
<?php
if ($y==1) {
?>
<script type="text/javascript">
var <?php print "parent$i" ?>phone<?php print $y ?>=new LiveValidation('<?php print "parent$i" ?>phone<?php print $y ?>');
<?php print "parent$i" ?>phone<?php print $y ?>.add(Validate.Presence);
</script>
<?php
}
?>
<select name="<?php print "parent$i" ?>phone<?php print $y ?>CountryCode" id="<?php print "parent$i" ?>phone<?php print $y ?>CountryCode" style="width: 60px">
<?php
print "<option value=''></option>" ;
try {
$dataSelect=array();
$sqlSelect="SELECT * FROM gibbonCountry ORDER BY printable_name" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) { }
while ($rowSelect=$resultSelect->fetch()) {
print "<option value='" . $rowSelect["iddCountryCode"] . "'>" . htmlPrep($rowSelect["iddCountryCode"]) . " - " . htmlPrep(_($rowSelect["printable_name"])) . "</option>" ;
}
?>
</select>
<select style="width: 70px" name="<?php print "parent$i" ?>phone<?php print $y ?>Type">
<option value=""></option>
<option value="Mobile"><?php print _('Mobile') ?></option>
<option value="Home"><?php print _('Home') ?></option>
<option value="Work"><?php print _('Work') ?></option>
<option value="Fax"><?php print _('Fax') ?></option>
<option value="Pager"><?php print _('Pager') ?></option>
<option value="Other"><?php print _('Other') ?></option>
</select>
</td>
</tr>
<?php
}
?>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td colspan=2>
<h4><?php print _('Parent/Guardian') ?> <?php print $i ?> <?php print _('Employment') ?></h4>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Profession') ?> *</b><br/>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>profession" id="<?php print "parent$i" ?>profession" maxlength=30 value="" type="text" style="width: 300px">
<script type="text/javascript">
var <?php print "parent$i" ?>profession=new LiveValidation('<?php print "parent$i" ?>profession');
<?php print "parent$i" ?>profession.add(Validate.Presence);
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Employer') ?></b><br/>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>employer" id="<?php print "parent$i" ?>employer" maxlength=30 value="" type="text" style="width: 300px">
</td>
</tr>
<?php
}
}
else {
?>
<input type="hidden" name="gibbonFamily" value="TRUE">
<tr class='break'>
<td colspan=2>
<h3><?php print _('Family') ?></h3>
<p><?php print _('Choose the family you wish to associate this application with.') ?></p>
<?php
print "<table cellspacing='0' style='width: 100%'>" ;
print "<tr class='head'>" ;
print "<th>" ;
print _("Family Name") ;
print "</th>" ;
print "<th>" ;
print _("Selected") ;
print "</th>" ;
print "<th>" ;
print _("Relationships") ;
print "</th>" ;
print "</tr>" ;
$rowCount=1 ;
while ($rowSelect=$resultSelect->fetch()) {
if (($rowCount%2)==0) {
$rowNum="odd" ;
}
else {
$rowNum="even" ;
}
print "<tr class=$rowNum>" ;
print "<td>" ;
print "<b>" . $rowSelect["name"] . "</b><br/>" ;
print "</td>" ;
print "<td>" ;
$checked="" ;
if ($rowCount==1) {
$checked="checked" ;
}
print "<input $checked value='" . $rowSelect["gibbonFamilyID"] . "' name='gibbonFamilyID' type='radio'/>" ;
print "</td>" ;
print "<td>" ;
try {
$dataRelationships=array("gibbonFamilyID"=>$rowSelect["gibbonFamilyID"]);
$sqlRelationships="SELECT surname, preferredName, title, gender, gibbonFamilyAdult.gibbonPersonID FROM gibbonFamilyAdult JOIN gibbonPerson ON (gibbonFamilyAdult.gibbonPersonID=gibbonPerson.gibbonPersonID) WHERE gibbonFamilyID=:gibbonFamilyID" ;
$resultRelationships=$connection2->prepare($sqlRelationships);
$resultRelationships->execute($dataRelationships);
}
catch(PDOException $e) {
print "<div class='error'>" . $e->getMessage() . "</div>" ;
}
while ($rowRelationships=$resultRelationships->fetch()) {
print "<div style='width: 100%'>" ;
print formatName($rowRelationships["title"], $rowRelationships["preferredName"], $rowRelationships["surname"], "Parent") ;
?>
<select name="<?php print $rowSelect["gibbonFamilyID"] ?>-relationships[]" id="relationships[]" style="width: 200px">
<option <?php if ($rowRelationships["gender"]=="F") { print "selected" ; } ?> value="Mother"><?php print _('Mother') ?></option>
<option <?php if ($rowRelationships["gender"]=="M") { print "selected" ; } ?> value="Father"><?php print _('Father') ?></option>
<option value="Step-Mother"><?php print _('Step-Mother') ?></option>
<option value="Step-Father"><?php print _('Step-Father') ?></option>
<option value="Adoptive Parent"><?php print _('Adoptive Parent') ?></option>
<option value="Guardian"><?php print _('Guardian') ?></option>
<option value="Grandmother"><?php print _('Grandmother') ?></option>
<option value="Grandfather"><?php print _('Grandfather') ?></option>
<option value="Aunt"><?php print _('Aunt') ?></option>
<option value="Uncle"><?php print _('Uncle') ?></option>
<option value="Nanny/Helper"><?php print _('Nanny/Helper') ?></option>
<option value="Other"><?php print _('Other') ?></option>
</select>
<input type="hidden" name="<?php print $rowSelect["gibbonFamilyID"] ?>-relationshipsGibbonPersonID[]" value="<?php print $rowRelationships["gibbonPersonID"] ?>">
<?php
print "</div>" ;
print "<br/>" ;
}
print "</td>" ;
print "</tr>" ;
$rowCount++ ;
}
print "</table>" ;
?>
</td>
</tr>
<?php
}
?>
<tr class='break'>
<td colspan=2>
<h3><?php print _('Siblings') ?></h3>
</td>
</tr>
<tr>
<td colspan=2 style='padding-top: 0px'>
<p><?php print _('Please give information on the applicants\'s siblings.') ?></p>
</td>
</tr>
<tr>
<td colspan=2>
<?php
print "<table cellspacing='0' style='width: 100%'>" ;
print "<tr class='head'>" ;
print "<th>" ;
print _("Sibling Name") ;
print "</th>" ;
print "<th>" ;
print _("Date of Birth") . "<br/><span style='font-size: 80%'>" . $_SESSION[$guid]["i18n"]["dateFormat"] . "</span>" ;
print "</th>" ;
print "<th>" ;
print _("School Attending") ;
print "</th>" ;
print "<th>" ;
print _("Joining Date") . "<br/><span style='font-size: 80%'>" . $_SESSION[$guid]["i18n"]["dateFormat"] . "</span>" ;
print "</th>" ;
print "</tr>" ;
$rowCount=1 ;
//List siblings who have been to or are at the school
if (isset($gibbonFamilyID)) {
try {
$dataSibling=array("gibbonFamilyID"=>$gibbonFamilyID);
$sqlSibling="SELECT surname, preferredName, dob, dateStart FROM gibbonFamilyChild JOIN gibbonPerson ON (gibbonFamilyChild.gibbonPersonID=gibbonPerson.gibbonPersonID) WHERE gibbonFamilyID=:gibbonFamilyID ORDER BY dob ASC, surname, preferredName" ;
$resultSibling=$connection2->prepare($sqlSibling);
$resultSibling->execute($dataSibling);
}
catch(PDOException $e) {
print "<div class='error'>" . $e->getMessage() . "</div>" ;
}
while ($rowSibling=$resultSibling->fetch()) {
if (($rowCount%2)==0) {
$rowNum="odd" ;
}
else {
$rowNum="even" ;
}
print "<tr class=$rowNum>" ;
print "<td>" ;
print "<input name='siblingName$rowCount' id='siblingName$rowCount' maxlength=50 value='" . formatName("", $rowSibling["preferredName"], $rowSibling["surname"], "Student") . "' type='text' style='width:120px; float: left'>" ;
print "</td>" ;
print "<td>" ;
?>
<input name="<?php print "siblingDOB$rowCount" ?>" id="<?php print "siblingDOB$rowCount" ?>" maxlength=10 value="<?php print dateConvertBack($guid, $rowSibling["dob"]) ?>" type="text" style="width:90px; float: left"><br/>
<script type="text/javascript">
$(function() {
$( "#<?php print "siblingDOB$rowCount" ?>" ).datepicker();
});
</script>
<?php
print "</td>" ;
print "<td>" ;
print "<input name='siblingSchool$rowCount' id='siblingSchool$rowCount' maxlength=50 value='" . $_SESSION[$guid]["organisationName"] . "' type='text' style='width:200px; float: left'>" ;
print "</td>" ;
print "<td>" ;
?>
<input name="<?php print "siblingSchoolJoiningDate$rowCount" ?>" id="<?php print "siblingSchoolJoiningDate$rowCount" ?>" maxlength=10 value="<?php print dateConvertBack($guid, $rowSibling["dateStart"]) ?>" type="text" style="width:90px; float: left">
<script type="text/javascript">
$(function() {
$( "#<?php print "siblingSchoolJoiningDate$rowCount" ?>" ).datepicker();
});
</script>
<?php
print "</td>" ;
print "</tr>" ;
$rowCount++ ;
}
}
//Space for other siblings
for ($i=$rowCount; $i<4; $i++) {
if (($i%2)==0) {
$rowNum="even" ;
}
else {
$rowNum="odd" ;
}
print "<tr class=$rowNum>" ;
print "<td>" ;
print "<input name='siblingName$i' id='siblingName$i' maxlength=50 value='' type='text' style='width:120px; float: left'>" ;
print "</td>" ;
print "<td>" ;
?>
<input name="<?php print "siblingDOB$i" ?>" id="<?php print "siblingDOB$i" ?>" maxlength=10 value="" type="text" style="width:90px; float: left"><br/>
<script type="text/javascript">
$(function() {
$( "#<?php print "siblingDOB$i" ?>" ).datepicker();
});
</script>
<?php
print "</td>" ;
print "<td>" ;
print "<input name='siblingSchool$i' id='siblingSchool$i' maxlength=50 value='' type='text' style='width:200px; float: left'>" ;
print "</td>" ;
print "<td>" ;
?>
<input name="<?php print "siblingSchoolJoiningDate$i" ?>" id="<?php print "siblingSchoolJoiningDate$i" ?>" maxlength=10 value="" type="text" style="width:120px; float: left">
<script type="text/javascript">
$(function() {
$( "#<?php print "siblingSchoolJoiningDate$i" ?>" ).datepicker();
});
</script>
<?php
print "</td>" ;
print "</tr>" ;
}
print "</table>" ;
?>
</td>
</tr>
<?php
$languageOptionsActive=getSettingByScope($connection2, 'Application Form', 'languageOptionsActive') ;
if ($languageOptionsActive=="On") {
?>
<tr class='break'>
<td colspan=2>
<h3><?php print _('Language Selection') ?></h3>
<?php
$languageOptionsBlurb=getSettingByScope($connection2, 'Application Form', 'languageOptionsBlurb') ;
if ($languageOptionsBlurb!="") {
print "<p>" ;
print $languageOptionsBlurb ;
print "</p>" ;
}
?>
</td>
</tr>
<tr>
<td>
<b><?php print _('Language Choice') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Please choose preferred additional language to study.') ?></i></span>
</td>
<td class="right">
<select name="languageChoice" id="languageChoice" style="width: 302px">
<?php
print "<option value='Please select...'>" . _('Please select...') . "</option>" ;
$languageOptionsLanguageList=getSettingByScope($connection2, "Application Form", "languageOptionsLanguageList") ;
$languages=explode(",", $languageOptionsLanguageList) ;
foreach ($languages as $language) {
print "<option value='" . trim($language) . "'>" . trim($language) . "</option>" ;
}
?>
</select>
<script type="text/javascript">
var languageChoice=new LiveValidation('languageChoice');
languageChoice.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<tr>
<td colspan=2 style='padding-top: 15px'>
<b><?php print _('Language Choice Experience') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Has the applicant studied the selected language before? If so, please describe the level and type of experience.') ?></i></span><br/>
<textarea name="languageChoiceExperience" id="languageChoiceExperience" rows=5 style="width:738px; margin: 5px 0px 0px 0px"></textarea>
<script type="text/javascript">
var languageChoiceExperience=new LiveValidation('languageChoiceExperience');
languageChoiceExperience.add(Validate.Presence);
</script>
</td>
</tr>
<?php
}
?>
<tr class='break'>
<td colspan=2>
<h3><?php print _('Scholarships') ?></h3>
<?php
//Get scholarships info
$scholarship=getSettingByScope($connection2, 'Application Form', 'scholarships') ;
if ($scholarship!="") {
print "<p>" ;
print $scholarship ;
print "</p>" ;
}
?>
</td>
</tr>
<tr>
<td>
<b><?php print _('Interest') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Indicate if you are interested in a scholarship.') ?></i></span><br/>
</td>
<td class="right">
<input type="radio" id="scholarshipInterest" name="scholarshipInterest" class="type" value="Y" /> Yes
<input checked type="radio" id="scholarshipInterest" name="scholarshipInterest" class="type" value="N" /> No
</td>
</tr>
<tr>
<td>
<b><?php print _('Required?') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Is a scholarship required for you to take up a place at the school?') ?></i></span><br/>
</td>
<td class="right">
<input type="radio" id="scholarshipRequired" name="scholarshipRequired" class="type" value="Y" /> Yes
<input checked type="radio" id="scholarshipRequired" name="scholarshipRequired" class="type" value="N" /> No
</td>
</tr>
<tr class='break'>
<td colspan=2>
<h3><?php print _('Payment') ?></h3>
</td>
</tr>
<script type="text/javascript">
/* Resource 1 Option Control */
$(document).ready(function(){
$("#companyNameRow").css("display","none");
$("#companyContactRow").css("display","none");
$("#companyAddressRow").css("display","none");
$("#companyEmailRow").css("display","none");
$("#companyCCFamilyRow").css("display","none");
$("#companyPhoneRow").css("display","none");
$("#companyAllRow").css("display","none");
$("#companyCategoriesRow").css("display","none");
$(".payment").click(function(){
if ($('input[name=payment]:checked').val()=="Family" ) {
$("#companyNameRow").css("display","none");
$("#companyContactRow").css("display","none");
$("#companyAddressRow").css("display","none");
$("#companyEmailRow").css("display","none");
$("#companyCCFamilyRow").css("display","none");
$("#companyPhoneRow").css("display","none");
$("#companyAllRow").css("display","none");
$("#companyCategoriesRow").css("display","none");
} else {
$("#companyNameRow").slideDown("fast", $("#companyNameRow").css("display","table-row"));
$("#companyContactRow").slideDown("fast", $("#companyContactRow").css("display","table-row"));
$("#companyAddressRow").slideDown("fast", $("#companyAddressRow").css("display","table-row"));
$("#companyEmailRow").slideDown("fast", $("#companyEmailRow").css("display","table-row"));
$("#companyCCFamilyRow").slideDown("fast", $("#companyCCFamilyRow").css("display","table-row"));
$("#companyPhoneRow").slideDown("fast", $("#companyPhoneRow").css("display","table-row"));
$("#companyAllRow").slideDown("fast", $("#companyAllRow").css("display","table-row"));
if ($('input[name=companyAll]:checked').val()=="N" ) {
$("#companyCategoriesRow").slideDown("fast", $("#companyCategoriesRow").css("display","table-row"));
}
}
});
$(".companyAll").click(function(){
if ($('input[name=companyAll]:checked').val()=="Y" ) {
$("#companyCategoriesRow").css("display","none");
} else {
$("#companyCategoriesRow").slideDown("fast", $("#companyCategoriesRow").css("display","table-row"));
}
});
});
</script>
<tr id="familyRow">
<td colspan=2>
<p><?php print _('If you choose family, future invoices will be sent according to your family\'s contact preferences, which can be changed at a later date by contacting the school. For example you may wish both parents to receive the invoice, or only one. Alternatively, if you choose Company, you can choose for all or only some fees to be covered by the specified company.') ?></p>
</td>
</tr>
<tr>
<td>
<b><?php print _('Send Future Invoices To') ?></b><br/>
</td>
<td class="right">
<input type="radio" name="payment" value="Family" class="payment" checked /> Family
<input type="radio" name="payment" value="Company" class="payment" /> Company
</td>
</tr>
<tr id="companyNameRow">
<td>
<b><?php print _('Company Name') ?></b><br/>
</td>
<td class="right">
<input name="companyName" id="companyName" maxlength=100 value="" type="text" style="width: 300px">
</td>
</tr>
<tr id="companyContactRow">
<td>
<b><?php print _('Company Contact Person') ?></b><br/>
</td>
<td class="right">
<input name="companyContact" id="companyContact" maxlength=100 value="" type="text" style="width: 300px">
</td>
</tr>
<tr id="companyAddressRow">
<td>
<b><?php print _('Company Address') ?></b><br/>
</td>
<td class="right">
<input name="companyAddress" id="companyAddress" maxlength=255 value="" type="text" style="width: 300px">
</td>
</tr>
<tr id="companyEmailRow">
<td>
<b><?php print _('Company Email') ?></b><br/>
</td>
<td class="right">
<input name="companyEmail" id="companyEmail" maxlength=255 value="" type="text" style="width: 300px">
<script type="text/javascript">
var companyEmail=new LiveValidation('companyEmail');
companyEmail.add(Validate.Email);
</script>
</td>
</tr>
<tr id="companyCCFamilyRow">
<td>
<b><?php print _('CC Family?') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Should the family be sent a copy of billing emails?') ?></i></span>
</td>
<td class="right">
<select name="companyCCFamily" id="companyCCFamily" style="width: 302px">
<option value="N" /> <?php print _('No') ?>
<option value="Y" /> <?php print _('Yes') ?>
</select>
</td>
</tr>
<tr id="companyPhoneRow">
<td>
<b><?php print _('Company Phone') ?></b><br/>
</td>
<td class="right">
<input name="companyPhone" id="companyPhone" maxlength=20 value="" type="text" style="width: 300px">
</td>
</tr>
<?php
try {
$dataCat=array();
$sqlCat="SELECT * FROM gibbonFinanceFeeCategory WHERE active='Y' AND NOT gibbonFinanceFeeCategoryID=1 ORDER BY name" ;
$resultCat=$connection2->prepare($sqlCat);
$resultCat->execute($dataCat);
}
catch(PDOException $e) { }
if ($resultCat->rowCount()<1) {
print "<input type=\"hidden\" name=\"companyAll\" value=\"Y\" class=\"companyAll\"/>" ;
}
else {
?>
<tr id="companyAllRow">
<td>
<b><?php print _('Company All?') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Should all items be billed to the specified company, or just some?') ?></i></span>
</td>
<td class="right">
<input type="radio" name="companyAll" value="Y" class="companyAll" checked /> <?php print _('All') ?>
<input type="radio" name="companyAll" value="N" class="companyAll" /> <?php print _('Selected') ?>
</td>
</tr>
<tr id="companyCategoriesRow">
<td>
<b><?php print _('Company Fee Categories') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('If the specified company is not paying all fees, which categories are they paying?') ?></i></span>
</td>
<td class="right">
<?php
while ($rowCat=$resultCat->fetch()) {
print $rowCat["name"] . " <input type='checkbox' name='gibbonFinanceFeeCategoryIDList[]' value='" . $rowCat["gibbonFinanceFeeCategoryID"] . "'/><br/>" ;
}
print _("Other") . " <input type='checkbox' name='gibbonFinanceFeeCategoryIDList[]' value='0001'/><br/>" ;
?>
</td>
</tr>
<?php
}
$requiredDocuments=getSettingByScope($connection2, "Application Form", "requiredDocuments") ;
$requiredDocumentsText=getSettingByScope($connection2, "Application Form", "requiredDocumentsText") ;
$requiredDocumentsCompulsory=getSettingByScope($connection2, "Application Form", "requiredDocumentsCompulsory") ;
if ($requiredDocuments!="" AND $requiredDocuments!=FALSE) {
?>
<tr class='break'>
<td colspan=2>
<h3><?php print _('Supporting Documents') ?></h3>
<?php
if ($requiredDocumentsText!="" OR $requiredDocumentsCompulsory!="") {
print "<p>" ;
print $requiredDocumentsText . " " ;
if ($requiredDocumentsCompulsory=="Y") {
print _("These documents must all be included before the application can be submitted.") ;
}
else {
print _("These documents are all required, but can be submitted separately to this form if preferred. Please note, however, that your application will be processed faster if the documents are included here.") ;
}
print "</p>" ;
}
?>
</td>
</tr>
<?php
//Get list of acceptable file extensions
try {
$dataExt=array();
$sqlExt="SELECT * FROM gibbonFileExtension" ;
$resultExt=$connection2->prepare($sqlExt);
$resultExt->execute($dataExt);
}
catch(PDOException $e) { }
$ext="" ;
while ($rowExt=$resultExt->fetch()) {
$ext=$ext . "'." . $rowExt["extension"] . "'," ;
}
$requiredDocumentsList=explode(",", $requiredDocuments) ;
$count=0 ;
foreach ($requiredDocumentsList AS $document) {
?>
<tr>
<td>
<b><?php print $document ; if ($requiredDocumentsCompulsory=="Y") { print " *" ; } ?></b><br/>
</td>
<td class="right">
<?php
print "<input type='file' name='file$count' id='file$count'><br/>" ;
print "<input type='hidden' name='fileName$count' id='filefileName$count' value='$document'>" ;
if ($requiredDocumentsCompulsory=="Y") {
print "<script type='text/javascript'>" ;
print "var file$count=new LiveValidation('file$count');" ;
print "file$count.add( Validate.Inclusion, { within: [" . $ext . "], failureMessage: 'Illegal file type!', partialMatch: true, caseSensitive: false } );" ;
print "file$count.add(Validate.Presence);" ;
print "</script>" ;
}
$count++ ;
?>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan=2>
<?php print getMaxUpload() ; ?>
<input type="hidden" name="fileCount" value="<?php print $count ?>">
</td>
</tr>
<?php
}
?>
<tr class='break'>
<td colspan=2>
<h3><?php print _('Miscellaneous') ?></h3>
</td>
</tr>
<tr>
<td>
<b><?php print _('How Did You Hear About Us?') ?> *</b><br/>
</td>
<td class="right">
<?php
$howDidYouHearList=getSettingByScope($connection2, "Application Form", "howDidYouHear") ;
if ($howDidYouHearList=="") {
print "<input name='howDidYouHear' id='howDidYouHear' maxlength=30 value='" . $row["howDidYouHear"] . "' type='text' style='width: 300px'>" ;
}
else {
print "<select name='howDidYouHear' id='howDidYouHear' style='width: 302px'>" ;
print "<option value='Please select...'>" . _('Please select...') . "</option>" ;
$howDidYouHears=explode(",", $howDidYouHearList) ;
foreach ($howDidYouHears as $howDidYouHear) {
print "<option value='" . trim($howDidYouHear) . "'>" . trim($howDidYouHear) . "</option>" ;
}
print "</select>" ;
?>
<script type="text/javascript">
var howDidYouHear=new LiveValidation('howDidYouHear');
howDidYouHear.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
<?php
}
?>
</td>
</tr>
<script type="text/javascript">
$(document).ready(function(){
$("#howDidYouHear").change(function(){
if ($('#howDidYouHear option:selected').val()=="Please select..." ) {
$("#tellUsMoreRow").css("display","none");
}
else {
$("#tellUsMoreRow").slideDown("fast", $("#tellUsMoreRow").css("display","table-row"));
}
});
});
</script>
<tr id="tellUsMoreRow" style='display: none'>
<td>
<b><?php print _('Tell Us More') ?> </b><br/>
<span style="font-size: 90%"><i><?php print _('The name of a person or link to a website, etc.') ?></i></span>
</td>
<td class="right">
<input name="howDidYouHearMore" id="howDidYouHearMore" maxlength=255 value="" type="text" style="width: 300px">
</td>
</tr>
<?php
$privacySetting=getSettingByScope( $connection2, "User Admin", "privacy" ) ;
$privacyBlurb=getSettingByScope( $connection2, "User Admin", "privacyBlurb" ) ;
$privacyOptions=getSettingByScope( $connection2, "User Admin", "privacyOptions" ) ;
if ($privacySetting=="Y" AND $privacyBlurb!="" AND $privacyOptions!="") {
?>
<tr>
<td>
<b><?php print _('Privacy') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print htmlPrep($privacyBlurb) ?><br/>
</i></span>
</td>
<td class="right">
<?php
$options=explode(",",$privacyOptions) ;
foreach ($options AS $option) {
print $option . " <input type='checkbox' name='privacyOptions[]' value='" . htmlPrep($option) . "'/><br/>" ;
}
?>
</td>
</tr>
<?php
}
//Get agreement
$agreement=getSettingByScope($connection2, 'Application Form', 'agreement') ;
if ($agreement!="") {
print "<tr class='break'>" ;
print "<td colspan=2>" ;
print "<h3>" ;
print _("Agreement") ;
print "</h3>" ;
print "<p>" ;
print $agreement ;
print "</p>" ;
print "</td>" ;
print "</tr>" ;
print "<tr>" ;
print "<td>" ;
print "<b>" . _('Do you agree to the above?') . "</b><br/>" ;
print "</td>" ;
print "<td class='right'>" ;
print "Yes <input type='checkbox' name='agreement' id='agreement'>" ;
?>
<script type="text/javascript">
var agreement=new LiveValidation('agreement');
agreement.add( Validate.Acceptance );
</script>
<?php
print "</td>" ;
print "</tr>" ;
}
?>
<tr>
<td>
<span style="font-size: 90%"><i>* <?php print _("denotes a required field") ; ?></i></span>
</td>
<td class="right">
<input type="hidden" name="address" value="<?php print $_SESSION[$guid]["address"] ?>">
<input type="submit" value="<?php print _("Submit") ; ?>">
</td>
</tr>
</table>
</form>
<?php
//Get postscrript
$postscript=getSettingByScope($connection2, 'Application Form', 'postscript') ;
if ($postscript!="") {
print "<h2>" ;
print _("Further Information") ;
print "</h2>" ;
print "<p style='padding-bottom: 15px'>" ;
print $postscript ;
print "</p>" ;
}
}
?> | dimas-latief/core | modules/Application Form/applicationForm.php | PHP | gpl-3.0 | 86,438 |
// uScript Action Node
// (C) 2011 Detox Studios LLC
using UnityEngine;
using System.Collections;
[NodePath("Actions/Assets")]
[NodeCopyright("Copyright 2011 by Detox Studios LLC")]
[NodeToolTip("Loads a PhysicMaterial")]
[NodeAuthor("Detox Studios LLC", "http://www.detoxstudios.com")]
[NodeHelp("http://docs.uscript.net/#3-Working_With_uScript/3.4-Nodes.htm")]
[FriendlyName("Load PhysicMaterial", "Loads a PhysicMaterial file from your Resources directory.")]
public class uScriptAct_LoadPhysicMaterial : uScriptLogic
{
public bool Out { get { return true; } }
public void In(
[FriendlyName("Asset Path", "The PhysicMaterial file to load. The supported file format is: \"physicMaterial\".")]
[AssetPathField(AssetType.PhysicMaterial)]
string name,
[FriendlyName("Loaded Asset", "The PhysicMaterial loaded from the specified file path.")]
out PhysicMaterial asset
)
{
asset = Resources.Load(name) as PhysicMaterial;
if ( null == asset )
{
uScriptDebug.Log( "Asset " + name + " couldn't be loaded, are you sure it's in a Resources folder?", uScriptDebug.Type.Warning );
}
}
#if UNITY_EDITOR
public override Hashtable EditorDragDrop( object o )
{
if ( typeof(PhysicMaterial).IsAssignableFrom( o.GetType() ) )
{
PhysicMaterial ac = (PhysicMaterial)o;
string path = UnityEditor.AssetDatabase.GetAssetPath( ac.GetInstanceID( ) );
int index = path.IndexOf( "Resources/" );
if ( index > 0 )
{
path = path.Substring( index + "Resources/".Length );
int dot = path.LastIndexOf( '.' );
if ( dot >= 0 ) path = path.Substring( 0, dot );
Hashtable hashtable = new Hashtable( );
hashtable[ "name" ] = path;
return hashtable;
}
}
return null;
}
#endif
} | neroziros/GameJam2017 | Assets/uScript/uScriptRuntime/Nodes/Actions/Assets/uScriptAct_LoadPhysicMaterial.cs | C# | gpl-3.0 | 1,905 |
/*global define*/
/*global test*/
/*global equal*/
define(['models/config'], function (Model) {
'use strict';
module('Config model');
test('Can be created with default values', function() {
var note = new Model();
equal(note.get('name'), '', 'For default config name is empty');
equal(note.get('value'), '', 'For default config value is empty');
});
test('Update attributes', function(){
var note = new Model();
note.set('name', 'new-config');
equal(note.get('name'), 'new-config');
equal(note.get('value'), '', 'For default config value is empty');
});
});
| elopio/laverna | test/spec/Models/config.js | JavaScript | gpl-3.0 | 641 |
<?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/>.
/**
* Version details
*
* @package block_tag_flickr
* @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2020110900; // The current plugin version (Date: YYYYMMDDXX)
$plugin->requires = 2020110300; // Requires this Moodle version
$plugin->component = 'block_tag_flickr'; // Full name of the plugin (used for diagnostics)
| iomad/iomad | blocks/tag_flickr/version.php | PHP | gpl-3.0 | 1,183 |
/*
* Copyright (C) 2013 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 com.android.inputmethod.latin;
import android.content.Context;
import com.android.inputmethod.keyboard.ProximityInfo;
import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
import com.android.inputmethod.latin.makedict.DictEncoder;
import com.android.inputmethod.latin.makedict.FormatSpec;
import com.android.inputmethod.latin.makedict.FusionDictionary;
import com.android.inputmethod.latin.makedict.FusionDictionary.PtNodeArray;
import com.android.inputmethod.latin.makedict.FusionDictionary.WeightedString;
import com.android.inputmethod.latin.makedict.UnsupportedFormatException;
import com.android.inputmethod.latin.utils.CollectionUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* An in memory dictionary for memorizing entries and writing a binary dictionary.
*/
public class DictionaryWriter extends AbstractDictionaryWriter {
private static final int BINARY_DICT_VERSION = 3;
private static final FormatSpec.FormatOptions FORMAT_OPTIONS =
new FormatSpec.FormatOptions(BINARY_DICT_VERSION, true /* supportsDynamicUpdate */);
private FusionDictionary mFusionDictionary;
public DictionaryWriter(final Context context, final String dictType) {
super(context, dictType);
clear();
}
@Override
public void clear() {
final HashMap<String, String> attributes = CollectionUtils.newHashMap();
mFusionDictionary = new FusionDictionary(new PtNodeArray(),
new FusionDictionary.DictionaryOptions(attributes, false, false));
}
/**
* Adds a word unigram to the fusion dictionary.
*/
// TODO: Create "cache dictionary" to cache fresh words for frequently updated dictionaries,
// considering performance regression.
@Override
public void addUnigramWord(final String word, final String shortcutTarget, final int frequency,
final int shortcutFreq, final boolean isNotAWord) {
if (shortcutTarget == null) {
mFusionDictionary.add(word, frequency, null, isNotAWord);
} else {
// TODO: Do this in the subclass, with this class taking an arraylist.
final ArrayList<WeightedString> shortcutTargets = CollectionUtils.newArrayList();
shortcutTargets.add(new WeightedString(shortcutTarget, shortcutFreq));
mFusionDictionary.add(word, frequency, shortcutTargets, isNotAWord);
}
}
@Override
public void addBigramWords(final String word0, final String word1, final int frequency,
final boolean isValid, final long lastModifiedTime) {
mFusionDictionary.setBigram(word0, word1, frequency);
}
@Override
public void removeBigramWords(final String word0, final String word1) {
// This class don't support removing bigram words.
}
@Override
protected void writeDictionary(final DictEncoder dictEncoder,
final Map<String, String> attributeMap) throws IOException, UnsupportedFormatException {
for (final Map.Entry<String, String> entry : attributeMap.entrySet()) {
mFusionDictionary.addOptionAttribute(entry.getKey(), entry.getValue());
}
dictEncoder.writeDictionary(mFusionDictionary, FORMAT_OPTIONS);
}
@Override
public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer,
final String prevWord, final ProximityInfo proximityInfo,
boolean blockOffensiveWords, final int[] additionalFeaturesOptions) {
// This class doesn't support suggestion.
return null;
}
@Override
public boolean isValidWord(String word) {
// This class doesn't support dictionary retrieval.
return false;
}
}
| s20121035/rk3288_android5.1_repo | packages/inputmethods/LatinIME/java/src/com/android/inputmethod/latin/DictionaryWriter.java | Java | gpl-3.0 | 4,412 |
var searchData=
[
['operator_2a',['operator*',['../class_complex.html#a789de21d72aa21414c26e0dd0966313a',1,'Complex']]],
['operator_2b',['operator+',['../class_complex.html#a5a7bc077499ace978055b0e6b9072ee9',1,'Complex']]],
['operator_5e',['operator^',['../class_complex.html#a952d42791b6b729c16406e21f9615f9f',1,'Complex']]]
];
| philippeganz/mandelbrot | docs/search/functions_6.js | JavaScript | gpl-3.0 | 335 |
<?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/>.
/**
* Atto text editor recordrtc version file.
*
* @package atto_recordrtc
* @author Jesus Federico (jesus [at] blindsidenetworks [dt] com)
* @author Jacob Prud'homme (jacob [dt] prudhomme [at] blindsidenetworks [dt] com)
* @copyright 2017 Blindside Networks Inc.
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2020061500;
$plugin->requires = 2020060900;
$plugin->component = 'atto_recordrtc';
$plugin->maturity = MATURITY_STABLE;
| stopfstedt/moodle | lib/editor/atto/plugins/recordrtc/version.php | PHP | gpl-3.0 | 1,229 |
# import re, os
# from jandy.profiler import Profiler
#
#
# class Base:
# def __init__(self):
# print('init call')
#
# def compile(self, str):
# re.compile(str)
#
# #
# p = Profiler("12K", "localhost:3000", 1)
# try:
# p.start()
# b = Base()
# b.compile("foo|bar")
# print("Hello World!!\n")
# finally:
# p.done()
#
#
# #try:
# # b.print_usage()
# #except e.MyException as e:
# # raise ValueError('failed')
| jcooky/jandy | jandy-python/tests/a.py | Python | gpl-3.0 | 457 |
# Copyright (C) 1998-2014 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman 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.
#
# GNU Mailman 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
# GNU Mailman. If not, see <http://www.gnu.org/licenses/>.
import sys
import time
import optparse
from email.Charset import Charset
from mailman import MailList
from mailman import Utils
from mailman.app.requests import handle_request
from mailman.configuration import config
from mailman.core.i18n import _
from mailman.email.message import UserNotification
from mailman.initialize import initialize
from mailman.interfaces.requests import IListRequests, RequestType
from mailman.version import MAILMAN_VERSION
# Work around known problems with some RedHat cron daemons
import signal
signal.signal(signal.SIGCHLD, signal.SIG_DFL)
NL = u'\n'
now = time.time()
def parseargs():
parser = optparse.OptionParser(version=MAILMAN_VERSION,
usage=_("""\
%prog [options]
Check for pending admin requests and mail the list owners if necessary."""))
parser.add_option('-C', '--config',
help=_('Alternative configuration file to use'))
opts, args = parser.parse_args()
if args:
parser.print_help()
print(_('Unexpected arguments'), file=sys.stderr)
sys.exit(1)
return opts, args, parser
def pending_requests(mlist):
# Must return a byte string
lcset = mlist.preferred_language.charset
pending = []
first = True
requestsdb = IListRequests(mlist)
for request in requestsdb.of_type(RequestType.subscription):
if first:
pending.append(_('Pending subscriptions:'))
first = False
key, data = requestsdb.get_request(request.id)
when = data['when']
addr = data['addr']
fullname = data['fullname']
passwd = data['passwd']
digest = data['digest']
lang = data['lang']
if fullname:
if isinstance(fullname, unicode):
fullname = fullname.encode(lcset, 'replace')
fullname = ' (%s)' % fullname
pending.append(' %s%s %s' % (addr, fullname, time.ctime(when)))
first = True
for request in requestsdb.of_type(RequestType.held_message):
if first:
pending.append(_('\nPending posts:'))
first = False
key, data = requestsdb.get_request(request.id)
when = data['when']
sender = data['sender']
subject = data['subject']
reason = data['reason']
text = data['text']
msgdata = data['msgdata']
subject = Utils.oneline(subject, lcset)
date = time.ctime(when)
reason = _(reason)
pending.append(_("""\
From: $sender on $date
Subject: $subject
Cause: $reason"""))
pending.append('')
# Coerce all items in pending to a Unicode so we can join them
upending = []
charset = mlist.preferred_language.charset
for s in pending:
if isinstance(s, unicode):
upending.append(s)
else:
upending.append(unicode(s, charset, 'replace'))
# Make sure that the text we return from here can be encoded to a byte
# string in the charset of the list's language. This could fail if for
# example, the request was pended while the list's language was French,
# but then it was changed to English before checkdbs ran.
text = NL.join(upending)
charset = Charset(mlist.preferred_language.charset)
incodec = charset.input_codec or 'ascii'
outcodec = charset.output_codec or 'ascii'
if isinstance(text, unicode):
return text.encode(outcodec, 'replace')
# Be sure this is a byte string encodeable in the list's charset
utext = unicode(text, incodec, 'replace')
return utext.encode(outcodec, 'replace')
def auto_discard(mlist):
# Discard old held messages
discard_count = 0
expire = config.days(mlist.max_days_to_hold)
requestsdb = IListRequests(mlist)
heldmsgs = list(requestsdb.of_type(RequestType.held_message))
if expire and heldmsgs:
for request in heldmsgs:
key, data = requestsdb.get_request(request.id)
if now - data['date'] > expire:
handle_request(mlist, request.id, config.DISCARD)
discard_count += 1
mlist.Save()
return discard_count
# Figure out epoch seconds of midnight at the start of today (or the given
# 3-tuple date of (year, month, day).
def midnight(date=None):
if date is None:
date = time.localtime()[:3]
# -1 for dst flag tells the library to figure it out
return time.mktime(date + (0,)*5 + (-1,))
def main():
opts, args, parser = parseargs()
initialize(opts.config)
for name in config.list_manager.names:
# The list must be locked in order to open the requests database
mlist = MailList.MailList(name)
try:
count = IListRequests(mlist).count
# While we're at it, let's evict yesterday's autoresponse data
midnight_today = midnight()
evictions = []
for sender in mlist.hold_and_cmd_autoresponses.keys():
date, respcount = mlist.hold_and_cmd_autoresponses[sender]
if midnight(date) < midnight_today:
evictions.append(sender)
if evictions:
for sender in evictions:
del mlist.hold_and_cmd_autoresponses[sender]
# This is the only place we've changed the list's database
mlist.Save()
if count:
# Set the default language the the list's preferred language.
_.default = mlist.preferred_language
realname = mlist.real_name
discarded = auto_discard(mlist)
if discarded:
count = count - discarded
text = _('Notice: $discarded old request(s) '
'automatically expired.\n\n')
else:
text = ''
if count:
text += Utils.maketext(
'checkdbs.txt',
{'count' : count,
'mail_host': mlist.mail_host,
'adminDB' : mlist.GetScriptURL('admindb',
absolute=1),
'real_name': realname,
}, mlist=mlist)
text += '\n' + pending_requests(mlist)
subject = _('$count $realname moderator '
'request(s) waiting')
else:
subject = _('$realname moderator request check result')
msg = UserNotification(mlist.GetOwnerEmail(),
mlist.GetBouncesEmail(),
subject, text,
mlist.preferred_language)
msg.send(mlist, **{'tomoderators': True})
finally:
mlist.Unlock()
if __name__ == '__main__':
main()
| adam-iris/mailman | src/mailman/bin/checkdbs.py | Python | gpl-3.0 | 7,696 |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'InstanceApplication.network'
db.add_column('apply_instanceapplication', 'network', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['ganeti.Network'], null=True, blank=True), keep_default=False)
def backwards(self, orm):
# Deleting field 'InstanceApplication.network'
db.delete_column('apply_instanceapplication', 'network_id')
models = {
'apply.instanceapplication': {
'Meta': {'object_name': 'InstanceApplication'},
'admin_contact_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
'admin_contact_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'admin_contact_phone': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}),
'applicant': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'backend_message': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'cluster': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['ganeti.Cluster']", 'null': 'True', 'blank': 'True'}),
'comments': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'cookie': ('django.db.models.fields.CharField', [], {'default': "'AYkWSa4Fr2'", 'max_length': '255'}),
'disk_size': ('django.db.models.fields.IntegerField', [], {}),
'filed': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'hostname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hosts_mail_server': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'job_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'memory': ('django.db.models.fields.IntegerField', [], {}),
'network': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['ganeti.Network']", 'null': 'True', 'blank': 'True'}),
'operating_system': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'organization': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['apply.Organization']"}),
'status': ('django.db.models.fields.IntegerField', [], {}),
'vcpus': ('django.db.models.fields.IntegerField', [], {})
},
'apply.organization': {
'Meta': {'object_name': 'Organization'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'phone': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'users': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
'website': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'})
},
'apply.sshpublickey': {
'Meta': {'object_name': 'SshPublicKey'},
'comment': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'fingerprint': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.TextField', [], {}),
'key_type': ('django.db.models.fields.CharField', [], {'max_length': '12'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'ganeti.cluster': {
'Meta': {'object_name': 'Cluster'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
'fast_create': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'hostname': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}),
'port': ('django.db.models.fields.PositiveIntegerField', [], {'default': '5080'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'})
},
'ganeti.network': {
'Meta': {'object_name': 'Network'},
'cluster': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['ganeti.Cluster']"}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'link': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'mode': ('django.db.models.fields.CharField', [], {'max_length': '64'})
}
}
complete_apps = ['apply']
| sunweaver/ganetimgr | apply/migrations/0005_add_application_network_field.py | Python | gpl-3.0 | 8,911 |
require 'uuid'
class CompassAeInstance < ActiveRecord::Base
attr_protected :created_at, :updated_at
has_tracked_status
has_many :parties, :through => :compass_ae_instance_party_roles
has_many :compass_ae_instance_party_roles, :dependent => :destroy do
def owners
where('role_type_id = ?', RoleType.compass_ae_instance_owner.id)
end
end
validates :guid, :uniqueness => true
validates :internal_identifier, :presence => {:message => 'internal_identifier cannot be blank'}, :uniqueness => {:case_sensitive => false}
def installed_engines
Rails.application.config.erp_base_erp_svcs.compass_ae_engines.map do |compass_ae_engine|
klass_name = compass_ae_engine.railtie_name.camelize
{:name => klass_name, :version => ("#{klass_name}::VERSION::STRING".constantize rescue 'N/A')}
end
end
#helpers for guid
def set_guid(guid)
self.guid = guid
self.save
end
def get_guid
self.guid
end
def setup_guid
guid = Digest::SHA1.hexdigest(Time.now.to_s + rand(10000).to_s)
set_guid(guid)
guid
end
end | xuewenfei/compass_agile_enterprise | erp_base_erp_svcs/app/models/compass_ae_instance.rb | Ruby | gpl-3.0 | 1,077 |
<?php
/**
* LnmsCommand.php
*
* Convenience class for common command code
*
* 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 LibreNMS
* @link http://librenms.org
* @copyright 2019 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
namespace App\Console;
use Illuminate\Console\Command;
use Illuminate\Validation\ValidationException;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Validator;
abstract class LnmsCommand extends Command
{
protected $developer = false;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
$this->setDescription(__('commands.' . $this->getName() . '.description'));
}
public function isHidden()
{
$env = $this->getLaravel() ? $this->getLaravel()->environment() : getenv('APP_ENV');
return $this->hidden || ($this->developer && $env !== 'production');
}
/**
* Adds an argument. If $description is null, translate commands.command-name.arguments.name
* If you want the description to be empty, just set an empty string
*
* @param string $name The argument name
* @param int|null $mode The argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL
* @param string $description A description text
* @param string|string[]|null $default The default value (for InputArgument::OPTIONAL mode only)
*
* @throws InvalidArgumentException When argument mode is not valid
*
* @return $this
*/
public function addArgument($name, $mode = null, $description = null, $default = null)
{
// use a generated translation location by default
if (is_null($description)) {
$description = __('commands.' . $this->getName() . '.arguments.' . $name);
}
parent::addArgument($name, $mode, $description, $default);
return $this;
}
/**
* Adds an option. If $description is null, translate commands.command-name.arguments.name
* If you want the description to be empty, just set an empty string
*
* @param string $name The option name
* @param string|array|null $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts
* @param int|null $mode The option mode: One of the InputOption::VALUE_* constants
* @param string $description A description text
* @param string|string[]|int|bool|null $default The default value (must be null for InputOption::VALUE_NONE)
*
* @throws InvalidArgumentException If option mode is invalid or incompatible
*
* @return $this
*/
public function addOption($name, $shortcut = null, $mode = null, $description = null, $default = null)
{
// use a generated translation location by default
if (is_null($description)) {
$description = __('commands.' . $this->getName() . '.options.' . $name);
}
parent::addOption($name, $shortcut, $mode, $description, $default);
return $this;
}
/**
* Validate the input of this command. Uses Laravel input validation
* merging the arguments and options together to check.
*
* @param array $rules
* @param array $messages
*/
protected function validate($rules, $messages = [])
{
$validator = Validator::make($this->arguments() + $this->options(), $rules, $messages);
try {
$validator->validate();
} catch (ValidationException $e) {
collect($validator->getMessageBag()->all())->each(function ($message) {
$this->error($message);
});
exit(1);
}
}
}
| justmedude/librenms | app/Console/LnmsCommand.php | PHP | gpl-3.0 | 4,534 |
package com.example.mathsolver;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class AreaFragmentRight extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.area_right, container, false);
}
}
| RahulDadoriya/MathSolverApp | src/com/example/mathsolver/AreaFragmentRight.java | Java | gpl-3.0 | 580 |
# coding=utf-8
# This file is part of SickChill.
#
# URL: https://sickchill.github.io
# Git: https://github.com/SickChill/SickChill.git
#
# SickChill 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.
#
# SickChill 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 SickChill. If not, see <http://www.gnu.org/licenses/>.
"""
Test shows
"""
# pylint: disable=line-too-long
from __future__ import print_function, unicode_literals
import os
import sys
import unittest
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../lib')))
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))
import sickbeard
import six
from sickbeard.common import Quality
from sickbeard.tv import TVShow
from sickchill.helper.exceptions import MultipleShowObjectsException
from sickchill.show.Show import Show
class ShowTests(unittest.TestCase):
"""
Test shows
"""
def test_find(self):
"""
Test find tv shows by indexer_id
"""
sickbeard.QUALITY_DEFAULT = Quality.FULLHDTV
sickbeard.showList = []
show123 = TestTVShow(0, 123)
show456 = TestTVShow(0, 456)
show789 = TestTVShow(0, 789)
shows = [show123, show456, show789]
shows_duplicate = shows + shows
test_cases = {
(False, None): None,
(False, ''): None,
(False, '123'): None,
(False, 123): None,
(False, 12.3): None,
(True, None): None,
(True, ''): None,
(True, '123'): None,
(True, 123): show123,
(True, 12.3): None,
(True, 456): show456,
(True, 789): show789,
}
unicode_test_cases = {
(False, ''): None,
(False, '123'): None,
(True, ''): None,
(True, '123'): None,
}
for tests in test_cases, unicode_test_cases:
for ((use_shows, indexer_id), result) in six.iteritems(tests):
if use_shows:
self.assertEqual(Show.find(shows, indexer_id), result)
else:
self.assertEqual(Show.find(None, indexer_id), result)
with self.assertRaises(MultipleShowObjectsException):
Show.find(shows_duplicate, 456)
def test_validate_indexer_id(self):
"""
Tests if the indexer_id is valid and if so if it returns the right show
"""
sickbeard.QUALITY_DEFAULT = Quality.FULLHDTV
sickbeard.showList = []
show123 = TestTVShow(0, 123)
show456 = TestTVShow(0, 456)
show789 = TestTVShow(0, 789)
sickbeard.showList = [
show123,
show456,
show789,
]
invalid_show_id = ('Invalid show ID', None)
indexer_id_list = [
None, '', '', '123', '123', '456', '456', '789', '789', 123, 456, 789, ['123', '456'], ['123', '456'],
[123, 456]
]
results_list = [
invalid_show_id, invalid_show_id, invalid_show_id, (None, show123), (None, show123), (None, show456),
(None, show456), (None, show789), (None, show789), (None, show123), (None, show456), (None, show789),
invalid_show_id, invalid_show_id, invalid_show_id
]
self.assertEqual(
len(indexer_id_list), len(results_list),
'Number of parameters ({0:d}) and results ({1:d}) does not match'.format(len(indexer_id_list), len(results_list))
)
for (index, indexer_id) in enumerate(indexer_id_list):
self.assertEqual(Show._validate_indexer_id(indexer_id), results_list[index]) # pylint: disable=protected-access
class TestTVShow(TVShow):
"""
A test `TVShow` object that does not need DB access.
"""
def __init__(self, indexer, indexer_id):
super(TestTVShow, self).__init__(indexer, indexer_id)
def loadFromDB(self):
"""
Override TVShow.loadFromDB to avoid DB access during testing
"""
pass
if __name__ == '__main__':
print('=====> Testing {0}'.format(__file__))
SUITE = unittest.TestLoader().loadTestsFromTestCase(ShowTests)
unittest.TextTestRunner(verbosity=2).run(SUITE)
| dfalt974/SickRage | tests/sickchill_tests/show/show_tests.py | Python | gpl-3.0 | 4,719 |
/*
* ============================================================================
* GNU General Public License
* ============================================================================
*
* Copyright (C) 2015 Infinite Automation Software. All rights reserved.
*
* 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/>.
*
* When signing a commercial license with Infinite Automation Software,
* the following extension to GPL is made. A special exception to the GPL is
* included to allow you to distribute a combined work that includes BAcnet4J
* without being obliged to provide the source code for any proprietary components.
*
* See www.infiniteautomation.com for commercial license options.
*
* @author Matthew Lohbihler
*/
package com.serotonin.bacnet4j.type.notificationParameters;
import com.serotonin.bacnet4j.exception.BACnetException;
import com.serotonin.bacnet4j.type.AmbiguousValue;
import com.serotonin.bacnet4j.type.Encodable;
import com.serotonin.bacnet4j.type.constructed.StatusFlags;
import com.serotonin.bacnet4j.util.sero.ByteQueue;
public class CommandFailure extends NotificationParameters {
private static final long serialVersionUID = 5727410398456093753L;
public static final byte TYPE_ID = 3;
private final Encodable commandValue;
private final StatusFlags statusFlags;
private final Encodable feedbackValue;
public CommandFailure(Encodable commandValue, StatusFlags statusFlags, Encodable feedbackValue) {
this.commandValue = commandValue;
this.statusFlags = statusFlags;
this.feedbackValue = feedbackValue;
}
@Override
protected void writeImpl(ByteQueue queue) {
writeEncodable(queue, commandValue, 0);
write(queue, statusFlags, 1);
writeEncodable(queue, feedbackValue, 2);
}
public CommandFailure(ByteQueue queue) throws BACnetException {
commandValue = new AmbiguousValue(queue, 0);
statusFlags = read(queue, StatusFlags.class, 1);
feedbackValue = new AmbiguousValue(queue, 2);
}
@Override
protected int getTypeId() {
return TYPE_ID;
}
public Encodable getCommandValue() {
return commandValue;
}
public StatusFlags getStatusFlags() {
return statusFlags;
}
public Encodable getFeedbackValue() {
return feedbackValue;
}
@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((commandValue == null) ? 0 : commandValue.hashCode());
result = PRIME * result + ((feedbackValue == null) ? 0 : feedbackValue.hashCode());
result = PRIME * result + ((statusFlags == null) ? 0 : statusFlags.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final CommandFailure other = (CommandFailure) obj;
if (commandValue == null) {
if (other.commandValue != null)
return false;
}
else if (!commandValue.equals(other.commandValue))
return false;
if (feedbackValue == null) {
if (other.feedbackValue != null)
return false;
}
else if (!feedbackValue.equals(other.feedbackValue))
return false;
if (statusFlags == null) {
if (other.statusFlags != null)
return false;
}
else if (!statusFlags.equals(other.statusFlags))
return false;
return true;
}
}
| mlohbihler/BACnet4J | src/main/java/com/serotonin/bacnet4j/type/notificationParameters/CommandFailure.java | Java | gpl-3.0 | 4,277 |
<?php
/**
* Kodekit - http://timble.net/kodekit
*
* @copyright Copyright (C) 2007 - 2016 Johan Janssens and Timble CVBA. (http://www.timble.net)
* @license MPL v2.0 <https://www.mozilla.org/en-US/MPL/2.0>
* @link https://github.com/timble/kodekit for the canonical source repository
*/
namespace Kodekit\Library;
/**
* Controller Permission Interface
*
* @author Johan Janssens <https://github.com/johanjanssens>
* @package Kodekit\Library\Controller\Permission
*/
interface ControllerPermissionInterface
{
/**
* Permission handler for render actions
*
* @return boolean Return TRUE if action is permitted. FALSE otherwise.
*/
public function canRender();
/**
* Permission handler for read actions
*
* Method should return FALSE if the controller does not implements the ControllerModellable interface.
*
* @return boolean Return TRUE if action is permitted. FALSE otherwise.
*/
public function canRead();
/**
* Permission handler for browse actions
*
* Method should return FALSE if the controller does not implements the ControllerModellable interface.
*
* @return boolean Return TRUE if action is permitted. FALSE otherwise.
*/
public function canBrowse();
/**
* Permission handler for add actions
*
* Method should return FALSE if the controller does not implements the ControllerModellable interface.
*
* @return boolean Return TRUE if action is permitted. FALSE otherwise.
*/
public function canAdd();
/**
* Permission handler for edit actions
*
* Method should return FALSE if the controller does not implements the ControllerModellable interface.
*
* @return boolean Return TRUE if action is permitted. FALSE otherwise.
*/
public function canEdit();
/**
* Permission handler for delete actions
*
* Method should return FALSE if the controller does not implements the ControllerModellable interface.
*
* @return boolean Returns TRUE if action is permitted. FALSE otherwise.
*/
public function canDelete();
} | nooku/nooku-framework | code/controller/permission/interface.php | PHP | gpl-3.0 | 2,175 |
// Font.cpp: ActionScript Font handling, for Gnash.
//
// Copyright (C) 2006, 2007, 2008, 2009, 2010 Free Software
// Foundation, Inc
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// Based on the public domain work of Thatcher Ulrich <tu@tulrich.com> 2003
#include "smart_ptr.h" // GNASH_USE_GC
#include "Font.h"
#include "log.h"
#include "ShapeRecord.h"
#include "DefineFontTag.h"
#include "FreetypeGlyphsProvider.h"
#include <utility> // for std::make_pair
#include <memory>
namespace gnash {
namespace {
/// Reverse lookup of Glyph in CodeTable.
//
/// Inefficient, which is probably why TextSnapshot was designed like it
/// is.
class CodeLookup
{
public:
CodeLookup(const int glyph) : _glyph(glyph) {}
bool operator()(const std::pair<const boost::uint16_t, int>& p) {
return p.second == _glyph;
}
private:
int _glyph;
};
}
Font::GlyphInfo::GlyphInfo()
:
advance(0)
{}
Font::GlyphInfo::GlyphInfo(std::auto_ptr<SWF::ShapeRecord> glyph,
float advance)
:
glyph(glyph.release()),
advance(advance)
{}
Font::GlyphInfo::GlyphInfo(const GlyphInfo& o)
:
glyph(o.glyph),
advance(o.advance)
{}
Font::Font(std::auto_ptr<SWF::DefineFontTag> ft)
:
_fontTag(ft.release()),
_name(_fontTag->name()),
_unicodeChars(_fontTag->unicodeChars()),
_shiftJISChars(_fontTag->shiftJISChars()),
_ansiChars(_fontTag->ansiChars()),
_italic(_fontTag->italic()),
_bold(_fontTag->bold())
{
if (_fontTag->hasCodeTable()) _embeddedCodeTable = _fontTag->getCodeTable();
}
Font::Font(const std::string& name, bool bold, bool italic)
:
_fontTag(0),
_name(name),
_unicodeChars(false),
_shiftJISChars(false),
_ansiChars(true),
_italic(italic),
_bold(bold)
{
assert(!_name.empty());
}
Font::~Font()
{
}
SWF::ShapeRecord*
Font::get_glyph(int index, bool embedded) const
{
// What to do if embedded is true and this is a
// device-only font?
const GlyphInfoRecords& lookup = (embedded && _fontTag) ?
_fontTag->glyphTable() : _deviceGlyphTable;
if (index >= 0 && (size_t)index < lookup.size()) {
return lookup[index].glyph.get();
}
// TODO: should we log an error here ?
return 0;
}
void
Font::addFontNameInfo(const FontNameInfo& fontName)
{
if (!_displayName.empty() || !_copyrightName.empty())
{
IF_VERBOSE_MALFORMED_SWF(
log_swferror(_("Attempt to set font display or copyright name "
"again. This should mean there is more than one "
"DefineFontName tag referring to the same Font. Don't "
"know what to do in this case, so ignoring."));
);
return;
}
_displayName = fontName.displayName;
_copyrightName = fontName.copyrightName;
}
Font::GlyphInfoRecords::size_type
Font::glyphCount() const
{
assert(_fontTag);
return _fontTag->glyphTable().size();
}
void
Font::setFlags(boost::uint8_t flags)
{
_shiftJISChars = flags & (1 << 6);
_unicodeChars = flags & (1 << 5);
_ansiChars = flags & (1 << 4);
_italic = flags & (1 << 1);
_bold = flags & (1 << 0);
}
void
Font::setCodeTable(std::auto_ptr<CodeTable> table)
{
if (_embeddedCodeTable)
{
IF_VERBOSE_MALFORMED_SWF(
log_swferror(_("Attempt to add an embedded glyph CodeTable to "
"a font that already has one. This should mean there "
"are several DefineFontInfo tags, or a DefineFontInfo "
"tag refers to a font created by DefineFone2 or "
"DefineFont3. Don't know what should happen in this "
"case, so ignoring."));
);
return;
}
_embeddedCodeTable.reset(table.release());
}
void
Font::setName(const std::string& name)
{
_name = name;
}
boost::uint16_t
Font::codeTableLookup(int glyph, bool embedded) const
{
const CodeTable& ctable = (embedded && _embeddedCodeTable) ?
*_embeddedCodeTable : _deviceCodeTable;
CodeTable::const_iterator it = std::find_if(ctable.begin(), ctable.end(),
CodeLookup(glyph));
assert (it != ctable.end());
return it->first;
}
int
Font::get_glyph_index(boost::uint16_t code, bool embedded) const
{
const CodeTable& ctable = (embedded && _embeddedCodeTable) ?
*_embeddedCodeTable : _deviceCodeTable;
int glyph_index = -1;
CodeTable::const_iterator it = ctable.find(code);
if (it != ctable.end()) {
glyph_index = it->second;
return glyph_index;
}
// Try adding an os font, if possible
if (!embedded) {
glyph_index = const_cast<Font*>(this)->add_os_glyph(code);
}
return glyph_index;
}
float
Font::get_advance(int glyph_index, bool embedded) const
{
// What to do if embedded is true and this is a
// device-only font?
const GlyphInfoRecords& lookup = (embedded && _fontTag) ?
_fontTag->glyphTable() : _deviceGlyphTable;
if (glyph_index < 0) {
// Default advance.
return 512.0f;
}
assert(static_cast<size_t>(glyph_index) < lookup.size());
assert(glyph_index >= 0);
return lookup[glyph_index].advance;
}
// Return the adjustment in advance between the given two
// DisplayObjects. Normally this will be 0; i.e. the
float
Font::get_kerning_adjustment(int last_code, int code) const
{
kerning_pair k;
k.m_char0 = last_code;
k.m_char1 = code;
kernings_table::const_iterator it = m_kerning_pairs.find(k);
if (it != m_kerning_pairs.end()) {
float adjustment = it->second;
return adjustment;
}
return 0;
}
size_t
Font::unitsPerEM(bool embed) const
{
// the EM square is 1024 x 1024 for DefineFont up to 2
// and 20 as much for DefineFont3 up
if (embed) {
if ( _fontTag && _fontTag->subpixelFont() ) return 1024 * 20.0;
else return 1024;
}
FreetypeGlyphsProvider* ft = ftProvider();
if (!ft) {
log_error("Device font provider was not initialized, "
"can't get unitsPerEM");
return 0;
}
return ft->unitsPerEM();
}
int
Font::add_os_glyph(boost::uint16_t code)
{
FreetypeGlyphsProvider* ft = ftProvider();
if (!ft) return -1;
assert(_deviceCodeTable.find(code) == _deviceCodeTable.end());
float advance;
// Get the vectorial glyph
std::auto_ptr<SWF::ShapeRecord> sh = ft->getGlyph(code, advance);
if (!sh.get()) {
log_error("Could not create shape "
"glyph for DisplayObject code %u (%c) with "
"device font %s (%p)", code, code, _name, ft);
return -1;
}
// Find new glyph offset
int newOffset = _deviceGlyphTable.size();
// Add the new glyph id
_deviceCodeTable[code] = newOffset;
_deviceGlyphTable.push_back(GlyphInfo(sh, advance));
return newOffset;
}
bool
Font::matches(const std::string& name, bool bold, bool italic) const
{
return (_bold == bold && _italic == italic && name ==_name);
}
float
Font::leading() const {
return _fontTag ? _fontTag->leading() : 0.0f;
}
FreetypeGlyphsProvider*
Font::ftProvider() const
{
if (_ftProvider.get()) return _ftProvider.get();
if (_name.empty()) {
log_error("No name associated with this font, can't use device "
"fonts (should I use a default one?)");
return 0;
}
_ftProvider = FreetypeGlyphsProvider::createFace(_name, _bold, _italic);
if (!_ftProvider.get()) {
log_error("Could not create a freetype face %s", _name);
return 0;
}
return _ftProvider.get();
}
float
Font::ascent(bool embedded) const
{
if (embedded && _fontTag) return _fontTag->ascent();
FreetypeGlyphsProvider* ft = ftProvider();
if (ft) return ft->ascent();
return 0;
}
float
Font::descent(bool embedded) const
{
if (embedded && _fontTag) return _fontTag->descent();
FreetypeGlyphsProvider* ft = ftProvider();
if (ft) return ft->descent();
return 0;
}
bool
Font::is_subpixel_font() const {
return _fontTag ? _fontTag->subpixelFont() : false;
}
} // namespace gnash
// Local Variables:
// mode: C++
// indent-tabs-mode: t
// End:
| atheerabed/gnash-fork | libcore/Font.cpp | C++ | gpl-3.0 | 8,960 |
<?php
/*
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Free Content / Management System #
# / #
# #
# #
# Copyright 2005-2015 by webspell.org #
# #
# visit webSPELL.org, webspell.info to get webSPELL for free #
# - Script runs under the GNU GENERAL PUBLIC LICENSE #
# - It's NOT allowed to remove this copyright-tag #
# -- http://www.fsf.org/licensing/licenses/gpl.html #
# #
# Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), #
# Far Development by Development Team - webspell.org #
# #
# visit webspell.org #
# #
##########################################################################
*/
$language_array = Array(
/* do not edit above this line */
'access_denied'=>'Приступ одбијен',
'activated'=>'активиран',
'additional_options'=>'Додатне опције',
'admin_email'=>'Администратор Е-маил',
'admin_name'=>'Админ име',
'allow_usergalleries'=>'дозволи кориснику галерије',
'archive'=>'Архива',
'articles'=>'Чланци',
'autoresize'=>'Функција за промену величине слике',
'autoresize_js'=>'на основу Јавасцрипт',
'autoresize_off'=>'деактивиран',
'autoresize_php'=>'по ПХП',
'awards'=>'Награде',
'captcha'=>'Цаптцха',
'captcha_autodetect'=>'Аутоматско',
'captcha_bgcol'=>'Боја позадине',
'captcha_both'=>'оба',
'captcha_fontcol'=>'Боја фонта',
'captcha_image'=>'слика',
'captcha_linenoise'=>'сметње на линији',
'captcha_noise'=>'бука',
'captcha_only_math'=>'само математика',
'captcha_only_text'=>'само текст',
'captcha_text'=>'текст',
'captcha_type'=>'Тип Цаптцха',
'captcha_style'=>'Цаптцха стил',
'clan_name'=>'Име клана',
'clan_tag'=>'Клан ознака',
'clanwars'=>'РатКланова',
'comments'=>'Коментари',
'content_size'=>'Величина садржаја',
'deactivated'=>'деактивиран',
'default_language'=>'подразумевани језик',
'demos'=>'Демои',
'demos_top'=>'Топ 5 Демоа',
'demos_latest'=>'Последњих 5 Демоа',
'detect_visitor_language'=>'Одредити језик посетиоца',
'forum'=>'Форум',
'forum_posts'=>'Форум постови',
'forum_topics'=>'Форум Теме',
'format_date'=>'Формат датума',
'format_time'=>'Формат времена',
'files'=>'Фајлови',
'files_top'=>'Топ 5 Преузимања',
'files_latest'=>'Последњих 5 Преузимања',
'gallery'=>'Галерија',
'guestbook'=>'Књига гостију',
'headlines'=>'Наслови',
'insert_links'=>'убаците линкове чланова',
'latest_articles'=>'Најновији чланци',
'latest_results'=>'Последњи резултати',
'latest_topics'=>'најновије теме',
'login_duration'=>'Трајање пријаве',
'max_length_headlines'=>'макс. дужина наслова',
'max_length_latest_articles'=>'Макс. дужина последњих чланака',
'max_length_latest_topics'=>'Макс. дужина најновије теме',
'max_length_topnews'=>'Макс. дужина topnews',
'max_wrong_pw'=>'Макс. погрешних лозинки',
'messenger'=>'Гласник',
'msg_on_gb_entry'=>'Msg на GB унос',
'news'=>'Новости',
'other'=>'Други',
'page_title'=>'Почетна страница име',
'page_url'=>'УРЛ почетне странице',
'pagelock'=>'Закључај страницу',
'pictures'=>'Слике',
'profile_last_posts'=>'Профил последње поруке',
'public_admin'=>'Админ јавне зоне',
'registered_users'=>'Регистровани корисници',
'search_min_length'=>'Претрага мин. дужина',
'settings'=>'Подешавања',
'shoutbox'=>'Shoutbox',
'shoutbox_all_messages'=>'Shoutbox све поруке',
'shoutbox_refresh'=>'Shoutbox освежи',
'space_user'=>'Простор по кориснику (МБајт)',
'spam_check'=>'Потврди постове?',
'spamapiblockerror'=>'Блокирај Поруке?',
'spamapihost'=>'АПИ УРЛ адреса',
'spamapikey'=>'АПИ кључ',
'spamfilter'=>'Спам филтер',
'spammaxposts'=>'макс. Порука',
'sc_modules'=>'СЦ Модули',
'thumb_width'=>'Ширина палца',
'tooltip_1'=>'Ово је УРЛ ваше странице ЕГ (иоурдомаин.цом/патх/вебспелл). <br> Без хттп: // на почетку и не завршава са косом цртом! <br> Требало би да буде као',
'tooltip_2'=>'Ово је наслов ваше странице, приказан као прозор наслов',
'tooltip_3'=>'Назив ваше организације',
'tooltip_4'=>'Скраћени назив / ознака ваше организације',
'tooltip_5'=>'Име вебмастера = Ваше име',
'tooltip_6'=>'Е-маил адреса вебмастера',
'tooltip_7'=>'Максималне вести које су у потпуности приказане',
'tooltip_8'=>'Форум тема по страници',
'tooltip_9'=>'Слике по страници',
'tooltip_10'=>'Наведене Вести у архиви за страницу',
'tooltip_11'=>'Форум порука по страници',
'tooltip_12'=>'Величина (ширина) за Галерију тхумбс',
'tooltip_13'=>'Наслови наведени у sc_headlines',
'tooltip_14'=>'Теме наведене у latesttopics',
'tooltip_15'=>'Веб-простор за корисничке галерије по кориснику у Мбите',
'tooltip_16'=>'Максимална дужина заглавља у sc_headlines',
'tooltip_17'=>'Минимална дужина термина за претрагу',
'tooltip_18'=>'Да ли желите да дозволите корисничке галерије за сваког корисника?',
'tooltip_19'=>'Да ли желите да управљате галеријом слика директно на Вашој страници? (Боље бити изабран)',
'tooltip_20'=>'Чланака по страници',
'tooltip_21'=>'Награда по страници',
'tooltip_22'=>'Чланци наведени од sc_articles',
'tooltip_23'=>'Демоа по страници',
'tooltip_24'=>'Максимална дужина наслова чланака у sc_articles',
'tooltip_25'=>'Уноси у књигу гостију по страници',
'tooltip_26'=>'Коментара по страници',
'tooltip_27'=>'Порука по страници',
'tooltip_28'=>'РатКланова по страници',
'tooltip_29'=>'Регистрованих корисника по страници',
'tooltip_30'=>'Резултати наведени у sc_results',
'tooltip_31'=>'Најновије поруке које су наведене у профилу',
'tooltip_32'=>'Уноси наведени у sc_upcoming',
'tooltip_33'=>'Трајање да остану пријављени [у сатима] (0 = 20 минута)',
'tooltip_34'=>'Максимална величина (ширина) садржаја (слике, текст ,итд.) (0 = искључи)',
'tooltip_35'=>'Максимална величина (висина) садржаја (слика) (0 = искључи)',
'tooltip_36'=>'Треба ли Админима повратних информација порука о новим уносима у књигу гостију?',
'tooltip_37'=>'Shoutbox коментари који су приказани у shoutbox',
'tooltip_38'=>'Максимално сачуваних коментара у shoutbox',
'tooltip_39'=>'Период (у секундама) за shoutbox освежење',
'tooltip_40'=>'Подразумевани језик за сајт',
'tooltip_41'=>'Убаците линкове ка профилу члана аутоматски?',
'tooltip_42'=>'Максимална дужина теме у latesttopics',
'tooltip_43'=>'Максималан број погрешних уноса лозинке пре ИП бан-а',
'tooltip_44'=>'Приказ типа captcha',
'tooltip_45'=>'Боја позадине од captcha',
'tooltip_46'=>'Боја фонта од captcha',
'tooltip_47'=>'Садржај тип / стил captcha',
'tooltip_48'=>'Број буке-пиксела',
'tooltip_49'=>'Број буке-линија',
'tooltip_50'=>'Избор аутоматске функције за промену величине слике',
'tooltip_51'=>'Максимална дужина topnews у sc_topnews',
'tooltip_52'=>'Одредити језик посетиоца аутоматски',
'tooltip_53'=>'Потврдите поруке са екстерном базом података',
'tooltip_54'=>'Унесите свој Spam API кључ овде ако је доступан',
'tooltip_55'=>'Унесите УРЛ у АПИ хост сервера. <br> Уобичајено: хттпс://апи.вебспелл.орг',
'tooltip_56'=>'Број порука од када више неће бити потврђени од спољашње базе података',
'tooltip_57'=>'Блокирај постове, када дође до грешке',
'tooltip_58'=>'Излазни Формат датума',
'tooltip_59'=>'Излазни Формат времена',
'tooltip_60'=>'Омогући корисника књиге гостију на сајту?',
'tooltip_61'=>'Шта би требало да СБ Демо модул показује?',
'tooltip_62'=>'Шта би требало да СБ датотеке модула показују?',
'transaction_invalid'=>'ИД трансакције неважећи',
'upcoming_actions'=>'предстојеће акције',
'update'=>'ажурирање',
'user_guestbook'=>'Корисник Књиге гостију'
);
| nerdiabet/webSPELL | languages/sr/admin/settings.php | PHP | gpl-3.0 | 11,568 |
using System.Linq;
using kino.Core.Framework;
using kino.Messaging;
namespace kino.Cluster
{
public partial class ScaleOutListener
{
private void ReceivedFromOtherNode(Message message)
{
if ((message.TraceOptions & MessageTraceOptions.Routing) == MessageTraceOptions.Routing)
{
var hops = string.Join("|",
message.GetMessageRouting()
.Select(h => $"{nameof(h.Uri)}:{h.Uri}/{h.Identity.GetAnyString()}"));
logger.Trace($"Message: {message} received from other node via hops {hops}");
}
}
}
} | iiwaasnet/kino | src/kino.Cluster/ScaleOutListener.Tracing.cs | C# | gpl-3.0 | 684 |
Bitrix 17.0.9 Business Demo = f37a7cf627b2ec3aa4045ed4678789ad
| gohdan/DFC | known_files/hashes/bitrix/modules/iblock/install/components/bitrix/iblock.vote/templates/stars/script.min.js | JavaScript | gpl-3.0 | 63 |
<?php
/**
* MyBB 1.8 Merge System
* Copyright 2014 MyBB Group, All Rights Reserved
*
* Website: http://www.mybb.com
* License: http://www.mybb.com/download/merge-system/license/
*/
// Disallow direct access to this file for security reasons
if(!defined("IN_MYBB"))
{
die("Direct initialization of this file is not allowed.<br /><br />Please make sure IN_MYBB is defined.");
}
class PHPBB3_Converter_Module_Pollvotes extends Converter_Module_Pollvotes {
var $settings = array(
'friendly_name' => 'poll votes',
'progress_column' => 'topic_id',
'default_per_screen' => 1000,
);
var $cache_poll_details = array();
function import()
{
global $import_session;
$query = $this->old_db->simple_select("poll_votes", "*", "", array('limit_start' => $this->trackers['start_pollvotes'], 'limit' => $import_session['pollvotes_per_screen']));
while($pollvote = $this->old_db->fetch_array($query))
{
$this->insert($pollvote);
}
}
function convert_data($data)
{
$insert_data = array();
// phpBB 3 values
$poll = $this->get_poll_details($data['topic_id']);
$insert_data['uid'] = $this->get_import->uid($data['vote_user_id']);
$insert_data['dateline'] = $poll['dateline'];
$insert_data['voteoption'] = $data['poll_option_id'];
$insert_data['pid'] = $poll['poll'];
return $insert_data;
}
function get_poll_details($tid)
{
global $db;
if(array_key_exists($tid, $this->cache_poll_details))
{
return $this->cache_poll_details[$tid];
}
$query = $db->simple_select("threads", "dateline,poll", "tid = '".$this->get_import->tid($tid)."'");
$poll = $db->fetch_array($query);
$db->free_result($query);
$this->cache_poll_details[$tid] = $poll;
return $poll;
}
function fetch_total()
{
global $import_session;
// Get number of poll votes
if(!isset($import_session['total_pollvotes']))
{
$query = $this->old_db->simple_select("poll_votes", "COUNT(*) as count");
$import_session['total_pollvotes'] = $this->old_db->fetch_field($query, 'count');
$this->old_db->free_result($query);
}
return $import_session['total_pollvotes'];
}
}
| PaulBender/merge-system | boards/phpbb3/pollvotes.php | PHP | gpl-3.0 | 2,116 |
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogSearch\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
/**
* @codeCoverageIgnore
*/
class InstallSchema implements InstallSchemaInterface
{
/**
* {@inheritdoc}
*/
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$installer = $setup;
$installer->startSetup();
$installer->getConnection()->addColumn(
$installer->getTable('catalog_eav_attribute'),
'search_weight',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_FLOAT,
'unsigned' => true,
'nullable' => false,
'default' => '1',
'comment' => 'Search Weight'
]
);
$installer->endSetup();
}
}
| rajmahesh/magento2-master | vendor/magento/module-catalog-search/Setup/InstallSchema.php | PHP | gpl-3.0 | 1,022 |
/*
* Copyright (C) 2012 Krawler Information Systems Pvt Ltd
* All rights reserved.
*
* 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.
*/
package com.krawler.portal.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* <a href="ListUtil.java.html"><b><i>View Source</i></b></a>
*
* @author Brian Wing Shun Chan
*
*/
public class ListUtil {
public static List copy(List master) {
if (master == null) {
return null;
}
return new ArrayList(master);
}
public static void copy(List master, List copy) {
if ((master == null) || (copy == null)) {
return;
}
copy.clear();
Iterator itr = master.iterator();
while (itr.hasNext()) {
Object obj = itr.next();
copy.add(obj);
}
}
public static void distinct(List list) {
distinct(list, null);
}
public static void distinct(List list, Comparator comparator) {
if ((list == null) || (list.size() == 0)) {
return;
}
Set<Object> set = null;
if (comparator == null) {
set = new TreeSet<Object>();
}
else {
set = new TreeSet<Object>(comparator);
}
Iterator<Object> itr = list.iterator();
while (itr.hasNext()) {
Object obj = itr.next();
if (set.contains(obj)) {
itr.remove();
}
else {
set.add(obj);
}
}
}
public static List fromArray(Object[] array) {
if ((array == null) || (array.length == 0)) {
return new ArrayList();
}
List list = new ArrayList(array.length);
for (int i = 0; i < array.length; i++) {
list.add(array[i]);
}
return list;
}
public static List fromCollection(Collection c) {
if ((c != null) && (c instanceof List)) {
return (List)c;
}
if ((c == null) || (c.size() == 0)) {
return new ArrayList();
}
List list = new ArrayList(c.size());
Iterator itr = c.iterator();
while (itr.hasNext()) {
list.add(itr.next());
}
return list;
}
public static List fromEnumeration(Enumeration enu) {
List list = new ArrayList();
while (enu.hasMoreElements()) {
Object obj = enu.nextElement();
list.add(obj);
}
return list;
}
public static List fromFile(String fileName) throws IOException {
return fromFile(new File(fileName));
}
public static List fromFile(File file) throws IOException {
List list = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(file));
String s = StringPool.BLANK;
while ((s = br.readLine()) != null) {
list.add(s);
}
br.close();
return list;
}
public static List fromString(String s) {
return fromArray(StringUtil.split(s, StringPool.NEW_LINE));
}
public static List sort(List list) {
return sort(list, null);
}
public static List sort(List list, Comparator comparator) {
// if (list instanceof UnmodifiableList) {
// list = copy(list);
// }
//
// Collections.sort(list, comparator);
return list;
}
public static List subList(List list, int start, int end) {
List newList = new ArrayList();
int normalizedSize = list.size() - 1;
if ((start < 0) || (start > normalizedSize) || (end < 0) ||
(start > end)) {
return newList;
}
for (int i = start; i < end && i <= normalizedSize; i++) {
newList.add(list.get(i));
}
return newList;
}
public static List<Boolean> toList(boolean[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Boolean> list = new ArrayList<Boolean>(array.length);
for (boolean value : array) {
list.add(value);
}
return list;
}
public static List<Double> toList(double[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Double> list = new ArrayList<Double>(array.length);
for (double value : array) {
list.add(value);
}
return list;
}
public static List<Float> toList(float[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Float> list = new ArrayList<Float>(array.length);
for (float value : array) {
list.add(value);
}
return list;
}
public static List<Integer> toList(int[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Integer> list = new ArrayList<Integer>(array.length);
for (int value : array) {
list.add(value);
}
return list;
}
public static List<Long> toList(long[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Long> list = new ArrayList<Long>(array.length);
for (long value : array) {
list.add(value);
}
return list;
}
public static List<Short> toList(short[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Short> list = new ArrayList<Short>(array.length);
for (short value : array) {
list.add(value);
}
return list;
}
public static List<Boolean> toList(Boolean[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Boolean> list = new ArrayList<Boolean>(array.length);
for (Boolean value : array) {
list.add(value);
}
return list;
}
public static List<Double> toList(Double[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Double> list = new ArrayList<Double>(array.length);
for (Double value : array) {
list.add(value);
}
return list;
}
public static List<Float> toList(Float[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Float> list = new ArrayList<Float>(array.length);
for (Float value : array) {
list.add(value);
}
return list;
}
public static List<Integer> toList(Integer[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Integer> list = new ArrayList<Integer>(array.length);
for (Integer value : array) {
list.add(value);
}
return list;
}
public static List<Long> toList(Long[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Long> list = new ArrayList<Long>(array.length);
for (Long value : array) {
list.add(value);
}
return list;
}
public static List<Short> toList(Short[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Short> list = new ArrayList<Short>(array.length);
for (Short value : array) {
list.add(value);
}
return list;
}
public static List<String> toList(String[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<String> list = new ArrayList<String>(array.length);
for (String value : array) {
list.add(value);
}
return list;
}
public static String toString(List list, String param) {
return toString(list, param, StringPool.COMMA);
}
public static String toString(List list, String param, String delimiter) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
Object bean = list.get(i);
// Object value = BeanPropertiesUtil.getObject(bean, param);
//
// if (value == null) {
// value = StringPool.BLANK;
// }
//
// sb.append(value.toString());
if ((i + 1) != list.size()) {
sb.append(delimiter);
}
}
return sb.toString();
}
}
| ufoe/Deskera-CRM | bpm-app/modulebuilder/src/main/java/com/krawler/portal/util/ListUtil.java | Java | gpl-3.0 | 8,286 |
<?php
/**
* Created by PhpStorm.
* User: mkt
* Date: 2015-10-28
* Time: 14:49
*/
namespace view;
require_once("view/ListView.php");
/**
* View that shows a list of unique sessions
* for a specific ip-number
*/
class SessionListView extends ListView
{
private $logSessions = array();
private static $loggedDate = "loggedDate";
private static $pageTitle = "Ip-address: ";
private static $sessionURL = "session";
//get list of unique session for that specific ip-number
public function getSessionList($selectedIP)
{
$logItems = $this->getLogItemsList();
foreach ($logItems as $logItem) {
$latest = $this->getLatestSession($logItem[$this->sessionId], $logItems);
if ($logItem[$this->ip] === $selectedIP) {
if($this->checkIfUnique($logItem[$this->sessionId], $this->sessionId, $this->logSessions)){
array_push($this->logSessions, [$this->sessionId => $logItem[$this->sessionId], Self::$loggedDate => $latest]);
}
}
}
$this->sortBy(Self::$loggedDate, $this->logSessions);
$this->renderHTML(Self::$pageTitle . $selectedIP, $this->renderSessionList());
}
/**
* @param $sessionId
* @param $logItems, array of ip-numbers, sessions, and dates
* @return mixed
* uses temporary array to sort session dates and get the latest logged
*/
private function getLatestSession($sessionId, $logItems)
{
$sessionDateArray = array();
foreach ($logItems as $logItem) {
$dateTime = $this->convertMicroTime($logItem[$this->microTime]);
if ($sessionId == $logItem[$this->sessionId]) {
if (!in_array($dateTime, $sessionDateArray)) {
array_push($sessionDateArray, $dateTime);
}
}
}
return end($sessionDateArray);
}
/**
* @return bool
* checks if user clicked sessionlink
* to view specific logged items in that session
*/
public function sessionLinkIsClicked() {
if (isset($_GET[self::$sessionURL]) ) {
return true;
}
return false;
}
private function getSessionUrl($session) {
return "?".self::$sessionURL."=$session";
}
public function getSession() {
assert($this->sessionLinkIsClicked());
return $_GET[self::$sessionURL];
}
/**
* @return string that represents HTML for that list of sessions
*/
private function renderSessionList()
{
$ret = "<ul>";
foreach ($this->logSessions as $sessions) {
$sessionId = $sessions[$this->sessionId];
$lastLogged = $sessions[Self::$loggedDate];
$sessionUrl = $this->getSessionUrl($sessions[$this->sessionId]);
$ret .= "<li>Session: <a href='$sessionUrl'>$sessionId</a></li>";
$ret .= "<li>Last logged: $lastLogged</li>";
$ret .= "<br>";
}
$ret .= "</ul>";
return $ret;
}
} | js223kz/PHP_LOGGER | view/SessionListView.php | PHP | gpl-3.0 | 3,066 |
/**
* Copyright (c) 2012, Google Inc.
*
* 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.mail.compose;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import com.android.mail.providers.Account;
import com.android.mail.providers.Message;
import com.android.mail.providers.ReplyFromAccount;
import com.android.mail.utils.AccountUtils;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.util.List;
public class FromAddressSpinner extends Spinner implements OnItemSelectedListener {
private List<Account> mAccounts;
private ReplyFromAccount mAccount;
private final List<ReplyFromAccount> mReplyFromAccounts = Lists.newArrayList();
private OnAccountChangedListener mAccountChangedListener;
public FromAddressSpinner(Context context) {
this(context, null);
}
public FromAddressSpinner(Context context, AttributeSet set) {
super(context, set);
}
public void setCurrentAccount(ReplyFromAccount account) {
mAccount = account;
selectCurrentAccount();
}
private void selectCurrentAccount() {
if (mAccount == null) {
return;
}
int currentIndex = 0;
for (ReplyFromAccount acct : mReplyFromAccounts) {
if (TextUtils.equals(mAccount.name, acct.name)
&& TextUtils.equals(mAccount.address, acct.address)) {
setSelection(currentIndex, true);
break;
}
currentIndex++;
}
}
public ReplyFromAccount getMatchingReplyFromAccount(String accountString) {
if (!TextUtils.isEmpty(accountString)) {
for (ReplyFromAccount acct : mReplyFromAccounts) {
if (accountString.equals(acct.address)) {
return acct;
}
}
}
return null;
}
public ReplyFromAccount getCurrentAccount() {
return mAccount;
}
/**
* @param action Action being performed; if this is COMPOSE, show all
* accounts. Otherwise, show just the account this was launched
* with.
* @param currentAccount Account used to launch activity.
* @param syncingAccounts
*/
public void initialize(int action, Account currentAccount, Account[] syncingAccounts,
Message refMessage) {
final List<Account> accounts = AccountUtils.mergeAccountLists(mAccounts,
syncingAccounts, true /* prioritizeAccountList */);
if (action == ComposeActivity.COMPOSE) {
mAccounts = accounts;
} else {
// First assume that we are going to use the current account as the reply account
Account replyAccount = currentAccount;
if (refMessage != null && refMessage.accountUri != null) {
// This is a reply or forward of a message access through the "combined" account.
// We want to make sure that the real account is in the spinner
for (Account account : accounts) {
if (account.uri.equals(refMessage.accountUri)) {
replyAccount = account;
break;
}
}
}
mAccounts = ImmutableList.of(replyAccount);
}
initFromSpinner();
}
@VisibleForTesting
protected void initFromSpinner() {
// If there are not yet any accounts in the cached synced accounts
// because this is the first time mail was opened, and it was opened
// directly to the compose activity, don't bother populating the reply
// from spinner yet.
if (mAccounts == null || mAccounts.size() == 0) {
return;
}
FromAddressSpinnerAdapter adapter =
new FromAddressSpinnerAdapter(getContext());
mReplyFromAccounts.clear();
for (Account account : mAccounts) {
mReplyFromAccounts.addAll(account.getReplyFroms());
}
adapter.addAccounts(mReplyFromAccounts);
setAdapter(adapter);
selectCurrentAccount();
setOnItemSelectedListener(this);
}
public List<ReplyFromAccount> getReplyFromAccounts() {
return mReplyFromAccounts;
}
public void setOnAccountChangedListener(OnAccountChangedListener listener) {
mAccountChangedListener = listener;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ReplyFromAccount selection = (ReplyFromAccount) getItemAtPosition(position);
if (!selection.address.equals(mAccount.address)) {
mAccount = selection;
mAccountChangedListener.onAccountChanged();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
/**
* Classes that want to know when a different account in the
* FromAddressSpinner has been selected should implement this interface.
* Note: if the user chooses the same account as the one that has already
* been selected, this method will not be called.
*/
public static interface OnAccountChangedListener {
public void onAccountChanged();
}
}
| s20121035/rk3288_android5.1_repo | packages/apps/UnifiedEmail/src/com/android/mail/compose/FromAddressSpinner.java | Java | gpl-3.0 | 6,076 |
# coding: utf8
{
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN',
'%Y-%m-%d': '%Y.%m.%d.',
'%Y-%m-%d %H:%M:%S': '%Y.%m.%d. %H:%M:%S',
'%s rows deleted': '%s sorok t\xc3\xb6rl\xc5\x91dtek',
'%s rows updated': '%s sorok friss\xc3\xadt\xc5\x91dtek',
'Available databases and tables': 'El\xc3\xa9rhet\xc5\x91 adatb\xc3\xa1zisok \xc3\xa9s t\xc3\xa1bl\xc3\xa1k',
'Cannot be empty': 'Nem lehet \xc3\xbcres',
'Check to delete': 'T\xc3\xb6rl\xc3\xa9shez v\xc3\xa1laszd ki',
'Client IP': 'Client IP',
'Controller': 'Controller',
'Copyright': 'Copyright',
'Current request': 'Jelenlegi lek\xc3\xa9rdez\xc3\xa9s',
'Current response': 'Jelenlegi v\xc3\xa1lasz',
'Current session': 'Jelenlegi folyamat',
'DB Model': 'DB Model',
'Database': 'Adatb\xc3\xa1zis',
'Delete:': 'T\xc3\xb6r\xc3\xb6l:',
'Description': 'Description',
'E-mail': 'E-mail',
'Edit': 'Szerkeszt',
'Edit This App': 'Alkalmaz\xc3\xa1st szerkeszt',
'Edit current record': 'Aktu\xc3\xa1lis bejegyz\xc3\xa9s szerkeszt\xc3\xa9se',
'First name': 'First name',
'Group ID': 'Group ID',
'Hello World': 'Hello Vil\xc3\xa1g',
'Import/Export': 'Import/Export',
'Index': 'Index',
'Internal State': 'Internal State',
'Invalid Query': 'Hib\xc3\xa1s lek\xc3\xa9rdez\xc3\xa9s',
'Invalid email': 'Invalid email',
'Last name': 'Last name',
'Layout': 'Szerkezet',
'Main Menu': 'F\xc5\x91men\xc3\xbc',
'Menu Model': 'Men\xc3\xbc model',
'Name': 'Name',
'New Record': '\xc3\x9aj bejegyz\xc3\xa9s',
'No databases in this application': 'Nincs adatb\xc3\xa1zis ebben az alkalmaz\xc3\xa1sban',
'Origin': 'Origin',
'Password': 'Password',
'Powered by': 'Powered by',
'Query:': 'Lek\xc3\xa9rdez\xc3\xa9s:',
'Record ID': 'Record ID',
'Registration key': 'Registration key',
'Reset Password key': 'Reset Password key',
'Role': 'Role',
'Rows in table': 'Sorok a t\xc3\xa1bl\xc3\xa1ban',
'Rows selected': 'Kiv\xc3\xa1lasztott sorok',
'Stylesheet': 'Stylesheet',
'Sure you want to delete this object?': 'Biztos t\xc3\xb6rli ezt az objektumot?',
'Table name': 'Table name',
'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.',
'Timestamp': 'Timestamp',
'Update:': 'Friss\xc3\xadt:',
'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.',
'User ID': 'User ID',
'View': 'N\xc3\xa9zet',
'Welcome to web2py': 'Isten hozott a web2py-ban',
'appadmin is disabled because insecure channel': 'az appadmin a biztons\xc3\xa1gtalan csatorna miatt letiltva',
'cache': 'gyors\xc3\xadt\xc3\xb3t\xc3\xa1r',
'change password': 'jelsz\xc3\xb3 megv\xc3\xa1ltoztat\xc3\xa1sa',
'click here for online examples': 'online p\xc3\xa9ld\xc3\xa1k\xc3\xa9rt kattints ide',
'click here for the administrative interface': 'az adminisztr\xc3\xa1ci\xc3\xb3s fel\xc3\xbclet\xc3\xa9rt kattints ide',
'customize me!': 'v\xc3\xa1ltoztass meg!',
'data uploaded': 'adat felt\xc3\xb6ltve',
'database': 'adatb\xc3\xa1zis',
'database %s select': 'adatb\xc3\xa1zis %s kiv\xc3\xa1laszt\xc3\xa1s',
'db': 'db',
'design': 'design',
'done!': 'k\xc3\xa9sz!',
'edit profile': 'profil szerkeszt\xc3\xa9se',
'export as csv file': 'export\xc3\xa1l csv f\xc3\xa1jlba',
'insert new': '\xc3\xbaj beilleszt\xc3\xa9se',
'insert new %s': '\xc3\xbaj beilleszt\xc3\xa9se %s',
'invalid request': 'hib\xc3\xa1s k\xc3\xa9r\xc3\xa9s',
'login': 'bel\xc3\xa9p',
'logout': 'kil\xc3\xa9p',
'lost password': 'elveszett jelsz\xc3\xb3',
'new record inserted': '\xc3\xbaj bejegyz\xc3\xa9s felv\xc3\xa9ve',
'next 100 rows': 'k\xc3\xb6vetkez\xc5\x91 100 sor',
'or import from csv file': 'vagy bet\xc3\xb6lt\xc3\xa9s csv f\xc3\xa1jlb\xc3\xb3l',
'previous 100 rows': 'el\xc5\x91z\xc5\x91 100 sor',
'record': 'bejegyz\xc3\xa9s',
'record does not exist': 'bejegyz\xc3\xa9s nem l\xc3\xa9tezik',
'record id': 'bejegyz\xc3\xa9s id',
'register': 'regisztr\xc3\xa1ci\xc3\xb3',
'selected': 'kiv\xc3\xa1lasztott',
'state': '\xc3\xa1llapot',
'table': 't\xc3\xa1bla',
'unable to parse csv file': 'nem lehet a csv f\xc3\xa1jlt beolvasni',
}
| henkelis/sonospy | web2py/applications/sonospy/languages/hu.py | Python | gpl-3.0 | 4,428 |