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 |
|---|---|---|---|---|---|
/*
html:after {
display: none;
content: '--small: (max-width: 500px) | --medium: (max-width: 1100px) | --large: (min-width: 1100px)';
}
*/
(function(window){
/*jshint eqnull:true */
'use strict';
var docElem = document.documentElement;
var create = function(){
if(!window.lazySizes || window.lazySizes.getCustomMedias){return;}
var lazySizes = window.lazySizes;
lazySizes.getCustomMedias = (function(){
var regCleanPseudos = /['"]/g;
var regSplit = /\s*\|\s*/g;
var regNamedQueries = /^([a-z0-9_-]+)\s*:\s*(.+)$/i;
var getStyle = function(elem, pseudo){
return (getComputedStyle(elem, pseudo).getPropertyValue('content') || 'none').replace(regCleanPseudos, '').trim();
};
var parse = function(string, object){
string.split(regSplit).forEach(function(query){
if(query.match(regNamedQueries)){
object[RegExp.$1] = RegExp.$2;
}
});
};
return function(object, element){
object = object || lazySizes.cfg.customMedia;
element = element || document.querySelector('html');
parse(getStyle(element, ':before'), object);
parse(getStyle(element, ':after'), object);
return object;
};
})();
lazySizes.updateCustomMedia = function(){
var i, len, customMedia;
var elems = docElem.querySelectorAll('source[media][data-media][srcset]');
lazySizes.getCustomMedias();
for(i = 0, len = elems.length; i < len; i++){
if( (customMedia = lazySizes.cfg.customMedia[elems[i].getAttribute('data-media') || elems[i].getAttribute('media')]) ){
elems[i].setAttribute('media', customMedia);
}
}
if(!window.HTMLPictureElement){
elems = docElem.querySelector('source[media][data-media][srcset] ~ img');
for(i = 0, len = elems.length; i < len; i++){
lazySizes.uP(elems[i]);
}
}
lazySizes.autoSizer.checkElems();
};
lazySizes.getCustomMedias();
docElem.removeEventListener('lazybeforeunveil', create);
};
if(window.addEventListener){
docElem.addEventListener('lazybeforeunveil', create);
create();
setTimeout(create);
}
})(window);
| georges5/bcangular | wp-content/plugins/wp-lazysizes-master/js/lazysizes/plugins/custommedia/ls.custommedia.js | JavaScript | gpl-2.0 | 2,072 |
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'list', 'pt-br', {
bulletedlist: 'Lista sem números',
numberedlist: 'Lista numerada'
} );
| SeeyaSia/www | web/libraries/ckeditor/plugins/list/lang/pt-br.js | JavaScript | gpl-2.0 | 262 |
<?php
/**
* @version $Id: default.php 21463 2011-06-06 15:28:10Z dextercowley $
* @package Joomla.Installation
* @copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
?>
<div id="step">
<div class="far-right">
<?php if ($this->document->direction == 'ltr') : ?>
<div class="button1-right"><div class="prev"><a href="index.php?view=preinstall" onclick="return Install.goToPage('preinstall');" rel="prev" title="<?php echo JText::_('JPREVIOUS'); ?>"><?php echo JText::_('JPREVIOUS'); ?></a></div></div>
<div class="button1-left"><div class="next"><a href="index.php?view=database" onclick="return Install.goToPage('database');" rel="next" title="<?php echo JText::_('JNEXT'); ?>"><?php echo JText::_('JNEXT'); ?></a></div></div>
<?php elseif ($this->document->direction == 'rtl') : ?>
<div class="button1-right"><div class="prev"><a href="index.php?view=database" onclick="return Install.goToPage('database');" rel="next" title="<?php echo JText::_('JNEXT'); ?>"><?php echo JText::_('JNEXT'); ?></a></div></div>
<div class="button1-left"><div class="next"><a href="index.php?view=preinstall" onclick="return Install.goToPage('preinstall');" rel="prev" title="<?php echo JText::_('JPREVIOUS'); ?>"><?php echo JText::_('JPREVIOUS'); ?></a></div></div>
<?php endif; ?>
</div>
<span class="steptitle"><?php echo JText::_('INSTL_LICENSE'); ?></span>
</div>
<form action="index.php" method="post" id="adminForm" class="form-validate">
<div id="installer">
<div class="m">
<h2><?php echo JText::_('INSTL_GNU_GPL_LICENSE'); ?></h2>
<iframe src="gpl.html" class="license" marginwidth="25" scrolling="auto"></iframe>
</div>
</div>
<input type="hidden" name="task" value="" />
<?php echo JHtml::_('form.token'); ?>
</form>
| heqiaoliu/Viral-Dark-Matter | tmp/install_4f20924cbb0a1/installation/views/license/tmpl/default.php | PHP | gpl-2.0 | 1,877 |
(function(){
// module factory: start
var moduleFactory = function($) {
// module body: start
var module = this;
$.require()
.script("moment")
.done(function() {
var exports = function() {
$.moment.lang('ar-ma', {
months : "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),
monthsShort : "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),
weekdays : "الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),
weekdaysShort : "احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت".split("_"),
weekdaysMin : "ح_ن_ث_ر_خ_ج_س".split("_"),
longDateFormat : {
LT : "HH:mm",
L : "DD/MM/YYYY",
LL : "D MMMM YYYY",
LLL : "D MMMM YYYY LT",
LLLL : "dddd D MMMM YYYY LT"
},
calendar : {
sameDay: "[اليوم على الساعة] LT",
nextDay: '[غدا على الساعة] LT',
nextWeek: 'dddd [على الساعة] LT',
lastDay: '[أمس على الساعة] LT',
lastWeek: 'dddd [على الساعة] LT',
sameElse: 'L'
},
relativeTime : {
future : "في %s",
past : "منذ %s",
s : "ثوان",
m : "دقيقة",
mm : "%d دقائق",
h : "ساعة",
hh : "%d ساعات",
d : "يوم",
dd : "%d أيام",
M : "شهر",
MM : "%d أشهر",
y : "سنة",
yy : "%d سنوات"
},
week : {
dow : 6, // Saturday is the first day of the week.
doy : 12 // The week that contains Jan 1st is the first week of the year.
}
});
};
exports();
module.resolveWith(exports);
});
// module body: end
};
// module factory: end
FD50.module("moment/ar-ma", moduleFactory);
}()); | BetterBetterBetter/B3App | media/foundry/5.0/scripts/moment/ar-ma.js | JavaScript | gpl-2.0 | 2,156 |
require "test_helper"
module Api
class TracesControllerTest < ActionDispatch::IntegrationTest
##
# test all routes which lead to this controller
def test_routes
assert_routing(
{ :path => "/api/0.6/gpx/create", :method => :post },
{ :controller => "api/traces", :action => "create" }
)
assert_routing(
{ :path => "/api/0.6/gpx/1", :method => :get },
{ :controller => "api/traces", :action => "show", :id => "1" }
)
assert_routing(
{ :path => "/api/0.6/gpx/1", :method => :put },
{ :controller => "api/traces", :action => "update", :id => "1" }
)
assert_routing(
{ :path => "/api/0.6/gpx/1", :method => :delete },
{ :controller => "api/traces", :action => "destroy", :id => "1" }
)
assert_recognizes(
{ :controller => "api/traces", :action => "show", :id => "1" },
{ :path => "/api/0.6/gpx/1/details", :method => :get }
)
assert_routing(
{ :path => "/api/0.6/gpx/1/data", :method => :get },
{ :controller => "api/traces", :action => "data", :id => "1" }
)
assert_routing(
{ :path => "/api/0.6/gpx/1/data.xml", :method => :get },
{ :controller => "api/traces", :action => "data", :id => "1", :format => "xml" }
)
end
# Check getting a specific trace through the api
def test_show
public_trace_file = create(:trace, :visibility => "public")
# First with no auth
get api_trace_path(public_trace_file)
assert_response :unauthorized
# Now with some other user, which should work since the trace is public
auth_header = basic_authorization_header create(:user).display_name, "test"
get api_trace_path(public_trace_file), :headers => auth_header
assert_response :success
# And finally we should be able to do it with the owner of the trace
auth_header = basic_authorization_header public_trace_file.user.display_name, "test"
get api_trace_path(public_trace_file), :headers => auth_header
assert_response :success
end
# Check an anonymous trace can't be specifically fetched by another user
def test_show_anon
anon_trace_file = create(:trace, :visibility => "private")
# First with no auth
get api_trace_path(anon_trace_file)
assert_response :unauthorized
# Now try with another user, which shouldn't work since the trace is anon
auth_header = basic_authorization_header create(:user).display_name, "test"
get api_trace_path(anon_trace_file), :headers => auth_header
assert_response :forbidden
# And finally we should be able to get the trace details with the trace owner
auth_header = basic_authorization_header anon_trace_file.user.display_name, "test"
get api_trace_path(anon_trace_file), :headers => auth_header
assert_response :success
end
# Check the api details for a trace that doesn't exist
def test_show_not_found
deleted_trace_file = create(:trace, :deleted)
# Try first with no auth, as it should require it
get api_trace_path(:id => 0)
assert_response :unauthorized
# Login, and try again
auth_header = basic_authorization_header deleted_trace_file.user.display_name, "test"
get api_trace_path(:id => 0), :headers => auth_header
assert_response :not_found
# Now try a trace which did exist but has been deleted
auth_header = basic_authorization_header deleted_trace_file.user.display_name, "test"
get api_trace_path(deleted_trace_file), :headers => auth_header
assert_response :not_found
end
# Test downloading a trace through the api
def test_data
public_trace_file = create(:trace, :visibility => "public", :fixture => "a")
# First with no auth
get api_trace_data_path(public_trace_file)
assert_response :unauthorized
# Now with some other user, which should work since the trace is public
auth_header = basic_authorization_header create(:user).display_name, "test"
get api_trace_data_path(public_trace_file), :headers => auth_header
follow_redirect!
follow_redirect!
check_trace_data public_trace_file, "848caa72f2f456d1bd6a0fdf228aa1b9"
# And finally we should be able to do it with the owner of the trace
auth_header = basic_authorization_header public_trace_file.user.display_name, "test"
get api_trace_data_path(public_trace_file), :headers => auth_header
follow_redirect!
follow_redirect!
check_trace_data public_trace_file, "848caa72f2f456d1bd6a0fdf228aa1b9"
end
# Test downloading a compressed trace through the api
def test_data_compressed
identifiable_trace_file = create(:trace, :visibility => "identifiable", :fixture => "d")
# Authenticate as the owner of the trace we will be using
auth_header = basic_authorization_header identifiable_trace_file.user.display_name, "test"
# First get the data as is
get api_trace_data_path(identifiable_trace_file), :headers => auth_header
follow_redirect!
follow_redirect!
check_trace_data identifiable_trace_file, "c6422a3d8750faae49ed70e7e8a51b93", "application/gzip", "gpx.gz"
# Now ask explicitly for XML format
get api_trace_data_path(identifiable_trace_file, :format => "xml"), :headers => auth_header
check_trace_data identifiable_trace_file, "abd6675fdf3024a84fc0a1deac147c0d", "application/xml", "xml"
# Now ask explicitly for GPX format
get api_trace_data_path(identifiable_trace_file, :format => "gpx"), :headers => auth_header
check_trace_data identifiable_trace_file, "abd6675fdf3024a84fc0a1deac147c0d"
end
# Check an anonymous trace can't be downloaded by another user through the api
def test_data_anon
anon_trace_file = create(:trace, :visibility => "private", :fixture => "b")
# First with no auth
get api_trace_data_path(anon_trace_file)
assert_response :unauthorized
# Now with some other user, which shouldn't work since the trace is anon
auth_header = basic_authorization_header create(:user).display_name, "test"
get api_trace_data_path(anon_trace_file), :headers => auth_header
assert_response :forbidden
# And finally we should be able to do it with the owner of the trace
auth_header = basic_authorization_header anon_trace_file.user.display_name, "test"
get api_trace_data_path(anon_trace_file), :headers => auth_header
follow_redirect!
follow_redirect!
check_trace_data anon_trace_file, "db4cb5ed2d7d2b627b3b504296c4f701"
end
# Test downloading a trace that doesn't exist through the api
def test_data_not_found
deleted_trace_file = create(:trace, :deleted)
# Try first with no auth, as it should require it
get api_trace_data_path(:id => 0)
assert_response :unauthorized
# Login, and try again
auth_header = basic_authorization_header create(:user).display_name, "test"
get api_trace_data_path(:id => 0), :headers => auth_header
assert_response :not_found
# Now try a trace which did exist but has been deleted
auth_header = basic_authorization_header deleted_trace_file.user.display_name, "test"
get api_trace_data_path(deleted_trace_file), :headers => auth_header
assert_response :not_found
end
# Test creating a trace through the api
def test_create
# Get file to use
fixture = Rails.root.join("test/gpx/fixtures/a.gpx")
file = Rack::Test::UploadedFile.new(fixture, "application/gpx+xml")
user = create(:user)
# First with no auth
post gpx_create_path, :params => { :file => file, :description => "New Trace", :tags => "new,trace", :visibility => "trackable" }
assert_response :unauthorized
# Rewind the file
file.rewind
# Now authenticated
create(:user_preference, :user => user, :k => "gps.trace.visibility", :v => "identifiable")
assert_not_equal "trackable", user.preferences.where(:k => "gps.trace.visibility").first.v
auth_header = basic_authorization_header user.display_name, "test"
post gpx_create_path, :params => { :file => file, :description => "New Trace", :tags => "new,trace", :visibility => "trackable" }, :headers => auth_header
assert_response :success
trace = Trace.find(response.body.to_i)
assert_equal "a.gpx", trace.name
assert_equal "New Trace", trace.description
assert_equal %w[new trace], trace.tags.order(:tag).collect(&:tag)
assert_equal "trackable", trace.visibility
assert_not trace.inserted
assert_equal File.new(fixture).read, trace.file.blob.download
trace.destroy
assert_equal "trackable", user.preferences.where(:k => "gps.trace.visibility").first.v
# Rewind the file
file.rewind
# Now authenticated, with the legacy public flag
assert_not_equal "public", user.preferences.where(:k => "gps.trace.visibility").first.v
auth_header = basic_authorization_header user.display_name, "test"
post gpx_create_path, :params => { :file => file, :description => "New Trace", :tags => "new,trace", :public => 1 }, :headers => auth_header
assert_response :success
trace = Trace.find(response.body.to_i)
assert_equal "a.gpx", trace.name
assert_equal "New Trace", trace.description
assert_equal %w[new trace], trace.tags.order(:tag).collect(&:tag)
assert_equal "public", trace.visibility
assert_not trace.inserted
assert_equal File.new(fixture).read, trace.file.blob.download
trace.destroy
assert_equal "public", user.preferences.where(:k => "gps.trace.visibility").first.v
# Rewind the file
file.rewind
# Now authenticated, with the legacy private flag
second_user = create(:user)
assert_nil second_user.preferences.where(:k => "gps.trace.visibility").first
auth_header = basic_authorization_header second_user.display_name, "test"
post gpx_create_path, :params => { :file => file, :description => "New Trace", :tags => "new,trace", :public => 0 }, :headers => auth_header
assert_response :success
trace = Trace.find(response.body.to_i)
assert_equal "a.gpx", trace.name
assert_equal "New Trace", trace.description
assert_equal %w[new trace], trace.tags.order(:tag).collect(&:tag)
assert_equal "private", trace.visibility
assert_not trace.inserted
assert_equal File.new(fixture).read, trace.file.blob.download
trace.destroy
assert_equal "private", second_user.preferences.where(:k => "gps.trace.visibility").first.v
end
# Check updating a trace through the api
def test_update
public_trace_file = create(:trace, :visibility => "public", :fixture => "a")
deleted_trace_file = create(:trace, :deleted)
anon_trace_file = create(:trace, :visibility => "private")
# First with no auth
put api_trace_path(public_trace_file), :params => create_trace_xml(public_trace_file)
assert_response :unauthorized
# Now with some other user, which should fail
auth_header = basic_authorization_header create(:user).display_name, "test"
put api_trace_path(public_trace_file), :params => create_trace_xml(public_trace_file), :headers => auth_header
assert_response :forbidden
# Now with a trace which doesn't exist
auth_header = basic_authorization_header create(:user).display_name, "test"
put api_trace_path(:id => 0), :params => create_trace_xml(public_trace_file), :headers => auth_header
assert_response :not_found
# Now with a trace which did exist but has been deleted
auth_header = basic_authorization_header deleted_trace_file.user.display_name, "test"
put api_trace_path(deleted_trace_file), :params => create_trace_xml(deleted_trace_file), :headers => auth_header
assert_response :not_found
# Now try an update with the wrong ID
auth_header = basic_authorization_header public_trace_file.user.display_name, "test"
put api_trace_path(public_trace_file), :params => create_trace_xml(anon_trace_file), :headers => auth_header
assert_response :bad_request,
"should not be able to update a trace with a different ID from the XML"
# And finally try an update that should work
auth_header = basic_authorization_header public_trace_file.user.display_name, "test"
t = public_trace_file
t.description = "Changed description"
t.visibility = "private"
put api_trace_path(t), :params => create_trace_xml(t), :headers => auth_header
assert_response :success
nt = Trace.find(t.id)
assert_equal nt.description, t.description
assert_equal nt.visibility, t.visibility
end
# Test that updating a trace doesn't duplicate the tags
def test_update_tags
tracetag = create(:tracetag)
trace = tracetag.trace
auth_header = basic_authorization_header trace.user.display_name, "test"
put api_trace_path(trace), :params => create_trace_xml(trace), :headers => auth_header
assert_response :success
updated = Trace.find(trace.id)
# Ensure there's only one tag in the database after updating
assert_equal(1, Tracetag.count)
# The new tag object might have a different id, so check the string representation
assert_equal trace.tagstring, updated.tagstring
end
# Check deleting a trace through the api
def test_destroy
public_trace_file = create(:trace, :visibility => "public")
# First with no auth
delete api_trace_path(public_trace_file)
assert_response :unauthorized
# Now with some other user, which should fail
auth_header = basic_authorization_header create(:user).display_name, "test"
delete api_trace_path(public_trace_file), :headers => auth_header
assert_response :forbidden
# Now with a trace which doesn't exist
auth_header = basic_authorization_header create(:user).display_name, "test"
delete api_trace_path(:id => 0), :headers => auth_header
assert_response :not_found
# And finally we should be able to do it with the owner of the trace
auth_header = basic_authorization_header public_trace_file.user.display_name, "test"
delete api_trace_path(public_trace_file), :headers => auth_header
assert_response :success
# Try it a second time, which should fail
auth_header = basic_authorization_header public_trace_file.user.display_name, "test"
delete api_trace_path(public_trace_file), :headers => auth_header
assert_response :not_found
end
private
def check_trace_data(trace, digest, content_type = "application/gpx+xml", extension = "gpx")
assert_response :success
assert_equal digest, Digest::MD5.hexdigest(response.body)
assert_equal content_type, response.media_type
assert_equal "attachment; filename=\"#{trace.id}.#{extension}\"; filename*=UTF-8''#{trace.id}.#{extension}", @response.header["Content-Disposition"]
end
##
# build XML for traces
# this builds a minimum viable XML for the tests in this suite
def create_trace_xml(trace)
root = XML::Document.new
root.root = XML::Node.new "osm"
trc = XML::Node.new "gpx_file"
trc["id"] = trace.id.to_s
trc["visibility"] = trace.visibility
trc["visible"] = trace.visible.to_s
desc = XML::Node.new "description"
desc << trace.description
trc << desc
trace.tags.each do |tag|
t = XML::Node.new "tag"
t << tag.tag
trc << t
end
root.root << trc
root.to_s
end
end
end
| tomhughes/openstreetmap-website | test/controllers/api/traces_controller_test.rb | Ruby | gpl-2.0 | 15,842 |
<?php
/**
* @package EasyDiscuss
* @copyright Copyright (C) 2010 Stack Ideas Private Limited. All rights reserved.
* @license GNU/GPL, see LICENSE.php
*
* EasyDiscuss is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
defined('_JEXEC') or die('Restricted access');
require_once dirname( __FILE__ ) . '/model.php';
class EasyDiscussModelLabels extends EasyDiscussModel
{
protected $_total = null;
protected $_pagination = null;
protected $_data = null;
public function __construct()
{
parent::__construct( array() );
$app = JFactory::getApplication();
$limit = $app->getUserStateFromRequest( 'com_easydiscuss.labels.limit', 'limit', DiscussHelper::getListLimit(), 'int');
$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
$this->setState('limit' , $limit);
$this->setState('limitstart', $limitstart);
}
/**
* Method to get the total number of the labels
*
* @access public
* @return integer
*/
public function getTotal()
{
// Lets load the content if it doesn't already exist
if (empty($this->_total))
{
$query = $this->_buildQuery();
$this->_total = $this->_getListCount($query);
}
return $this->_total;
}
/**
* Method to get a pagination object for the labels
*
* @access public
* @return integer
*/
public function getPagination()
{
// Lets load the content if it doesn't already exist
if (empty($this->_pagination))
{
jimport('joomla.html.pagination');
$this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
}
return $this->_pagination;
}
/**
* Method to build the query for the labels
*
* @access private
* @return string
*/
private function _buildQuery()
{
// Get the WHERE and ORDER BY clauses for the query
$where = $this->_buildQueryWhere();
$orderby = $this->_buildQueryOrderBy();
$db = DiscussHelper::getDBO();
$query = 'SELECT * FROM ' . $db->nameQuote( '#__discuss_posts_labels' )
. $where . ' '
. $orderby;
return $query;
}
private function _buildQueryWhere()
{
$app = JFactory::getApplication();
$db = DiscussHelper::getDBO();
$filter_state = $app->getUserStateFromRequest( 'com_easydiscuss.labels.filter_state', 'filter_state', '', 'word' );
$search = $app->getUserStateFromRequest( 'com_easydiscuss.labels.search', 'search', '', 'string' );
$search = $db->getEscaped( trim(JString::strtolower( $search ) ) );
$where = array();
if ( $filter_state )
{
if ( $filter_state == 'P' )
{
$where[] = $db->nameQuote( 'published' ) . '=' . $db->Quote( '1' );
}
else if ($filter_state == 'U' )
{
$where[] = $db->nameQuote( 'published' ) . '=' . $db->Quote( '0' );
}
}
if ($search)
{
$where[] = ' LOWER( title ) LIKE \'%' . $search . '%\' ';
}
$where = ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );
return $where;
}
private function _buildQueryOrderBy()
{
$app = JFactory::getApplication();
$filter_order = $app->getUserStateFromRequest( 'com_easydiscuss.labels.filter_order', 'filter_order', 'ordering ASC' , 'int' );
$filter_order_Dir = $app->getUserStateFromRequest( 'com_easydiscuss.labels.filter_order_Dir', 'filter_order_Dir', '' , 'word' );
$orderby = ' ORDER BY '.$filter_order.' '.$filter_order_Dir;
return $orderby;
}
/**
* Method to get labels item data
*
* @access public
* @return array
*/
public function getData()
{
// Lets load the content if it doesn't already exist
if (empty($this->_data))
{
$query = $this->_buildQuery();
$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
}
return $this->_data;
}
/**
* Method to publish or unpublish labels
*
* @access public
* @return boolean
*/
public function publish( $labels = array(), $publish = true )
{
if( is_integer($labels) ) {
$labels = array($labels);
} elseif ( !is_array($labels) || count($labels) < 1 ) {
return false;
}
$labels = implode( ',' , $labels );
$publish = $publish ? 1 : 0;
$db = DiscussHelper::getDBO();
$query = 'UPDATE ' . $db->nameQuote( '#__discuss_posts_labels' )
. ' SET ' . $db->nameQuote( 'published' ) . '=' . $db->Quote( $publish )
. ' WHERE ' . $db->nameQuote( 'id' ) . ' IN (' . $labels . ')';
$db->setQuery( $query );
if( !$db->query() )
{
$this->setError($this->_db->getErrorMsg());
return false;
}
return true;
}
public function searchLabel($title)
{
$db = DiscussHelper::getDBO();
$query = 'SELECT ' . $db->nameQuote('id') . ' '
. 'FROM ' . $db->nameQuote('#__discuss_posts_labels') . ' '
. 'WHERE ' . $db->nameQuote('title') . ' = ' . $db->quote($title) . ' '
. 'LIMIT 1';
$db->setQuery($query);
$result = $db->loadObject();
return $result;
}
public function getLabelTitle($id)
{
$db = DiscussHelper::getDBO();
$query = 'SELECT ' . $db->nameQuote('title') . ' '
. 'FROM ' . $db->nameQuote('#__discuss_posts_labels') . ' '
. 'WHERE ' . $db->nameQuote('id') . ' = ' . $db->quote($id) . ' '
. 'LIMIT 1';
$db->setQuery($query);
$result = $db->loadResult();
return $result;
}
/**
* Method to get total labels
*
* @access public
* @return integer
*/
public function getTotalLabels( $ignoreUnpublish = false )
{
$db = DiscussHelper::getDBO();
$query = 'SELECT COUNT(1) FROM ' . $db->nameQuote( '#__discuss_posts_labels' );
$query .= $ignoreUnpublish ? '' : ' WHERE `published` = 1';
$db->setQuery( $query );
$result = $db->loadResult();
return (empty($result)) ? 0 : $result;
}
public function getLabels()
{
$db = DiscussHelper::getDBO();
$query = ' SELECT `id`, `title` '
. ' FROM #__discuss_posts_labels '
. ' WHERE `published` = 1 '
. ' ORDER BY `ordering`';
$db->setQuery($query);
$result = $db->loadObjectList();
return $result;
}
}
| BetterBetterBetter/B3App | components/com_easydiscuss/models/labels.php | PHP | gpl-2.0 | 6,201 |
/**
* Playlist Loader
*/
import Event from '../events';
import EventHandler from '../event-handler';
import {ErrorTypes, ErrorDetails} from '../errors';
import URLHelper from '../utils/url';
import AttrList from '../utils/attr-list';
//import {logger} from '../utils/logger';
class PlaylistLoader extends EventHandler {
constructor(hls) {
super(hls,
Event.MANIFEST_LOADING,
Event.LEVEL_LOADING);
}
destroy() {
if (this.loader) {
this.loader.destroy();
this.loader = null;
}
this.url = this.id = null;
EventHandler.prototype.destroy.call(this);
}
onManifestLoading(data) {
this.load(data.url, null);
}
onLevelLoading(data) {
this.load(data.url, data.level, data.id);
}
load(url, id1, id2) {
var config = this.hls.config,
retry,
timeout,
retryDelay;
if (this.loading && this.loader) {
if (this.url === url && this.id === id1 && this.id2 === id2) {
// same request than last pending one, don't do anything
return;
} else {
// one playlist load request is pending, but with different params, abort it before loading new playlist
this.loader.abort();
}
}
this.url = url;
this.id = id1;
this.id2 = id2;
if(this.id === null) {
retry = config.manifestLoadingMaxRetry;
timeout = config.manifestLoadingTimeOut;
retryDelay = config.manifestLoadingRetryDelay;
} else {
retry = config.levelLoadingMaxRetry;
timeout = config.levelLoadingTimeOut;
retryDelay = config.levelLoadingRetryDelay;
}
this.loader = typeof(config.pLoader) !== 'undefined' ? new config.pLoader(config) : new config.loader(config);
this.loading = true;
this.loader.load(url, '', this.loadsuccess.bind(this), this.loaderror.bind(this), this.loadtimeout.bind(this), timeout, retry, retryDelay);
}
resolve(url, baseUrl) {
return URLHelper.buildAbsoluteURL(baseUrl, url);
}
parseMasterPlaylist(string, baseurl) {
let levels = [], result;
// https://regex101.com is your friend
const re = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g;
while ((result = re.exec(string)) != null){
const level = {};
var attrs = level.attrs = new AttrList(result[1]);
level.url = this.resolve(result[2], baseurl);
var resolution = attrs.decimalResolution('RESOLUTION');
if(resolution) {
level.width = resolution.width;
level.height = resolution.height;
}
level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');
level.name = attrs.NAME;
var codecs = attrs.CODECS;
if(codecs) {
codecs = codecs.split(',');
for (let i = 0; i < codecs.length; i++) {
const codec = codecs[i];
if (codec.indexOf('avc1') !== -1) {
level.videoCodec = this.avc1toavcoti(codec);
} else {
level.audioCodec = codec;
}
}
}
levels.push(level);
}
return levels;
}
avc1toavcoti(codec) {
var result, avcdata = codec.split('.');
if (avcdata.length > 2) {
result = avcdata.shift() + '.';
result += parseInt(avcdata.shift()).toString(16);
result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
} else {
result = codec;
}
return result;
}
cloneObj(obj) {
return JSON.parse(JSON.stringify(obj));
}
parseLevelPlaylist(string, baseurl, id) {
var currentSN = 0,
totalduration = 0,
level = {url: baseurl, fragments: [], live: true, startSN: 0},
levelkey = {method : null, key : null, iv : null, uri : null},
cc = 0,
programDateTime = null,
frag = null,
result,
regexp,
byteRangeEndOffset,
byteRangeStartOffset;
regexp = /(?:#EXT-X-(MEDIA-SEQUENCE):(\d+))|(?:#EXT-X-(TARGETDURATION):(\d+))|(?:#EXT-X-(KEY):(.*))|(?:#EXT(INF):([\d\.]+)[^\r\n]*([\r\n]+[^#|\r\n]+)?)|(?:#EXT-X-(BYTERANGE):([\d]+[@[\d]*)]*[\r\n]+([^#|\r\n]+)?|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(PROGRAM-DATE-TIME):(.*))/g;
while ((result = regexp.exec(string)) !== null) {
result.shift();
result = result.filter(function(n) { return (n !== undefined); });
switch (result[0]) {
case 'MEDIA-SEQUENCE':
currentSN = level.startSN = parseInt(result[1]);
break;
case 'TARGETDURATION':
level.targetduration = parseFloat(result[1]);
break;
case 'ENDLIST':
level.live = false;
break;
case 'DIS':
cc++;
break;
case 'BYTERANGE':
var params = result[1].split('@');
if (params.length === 1) {
byteRangeStartOffset = byteRangeEndOffset;
} else {
byteRangeStartOffset = parseInt(params[1]);
}
byteRangeEndOffset = parseInt(params[0]) + byteRangeStartOffset;
if (frag && !frag.url) {
frag.byteRangeStartOffset = byteRangeStartOffset;
frag.byteRangeEndOffset = byteRangeEndOffset;
frag.url = this.resolve(result[2], baseurl);
}
break;
case 'INF':
var duration = parseFloat(result[1]);
if (!isNaN(duration)) {
var fragdecryptdata,
sn = currentSN++;
if (levelkey.method && levelkey.uri && !levelkey.iv) {
fragdecryptdata = this.cloneObj(levelkey);
var uint8View = new Uint8Array(16);
for (var i = 12; i < 16; i++) {
uint8View[i] = (sn >> 8*(15-i)) & 0xff;
}
fragdecryptdata.iv = uint8View;
} else {
fragdecryptdata = levelkey;
}
var url = result[2] ? this.resolve(result[2], baseurl) : null;
frag = {url: url, duration: duration, start: totalduration, sn: sn, level: id, cc: cc, byteRangeStartOffset: byteRangeStartOffset, byteRangeEndOffset: byteRangeEndOffset, decryptdata : fragdecryptdata, programDateTime: programDateTime};
level.fragments.push(frag);
totalduration += duration;
byteRangeStartOffset = null;
programDateTime = null;
}
break;
case 'KEY':
// https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4
var decryptparams = result[1];
var keyAttrs = new AttrList(decryptparams);
var decryptmethod = keyAttrs.enumeratedString('METHOD'),
decrypturi = keyAttrs.URI,
decryptiv = keyAttrs.hexadecimalInteger('IV');
if (decryptmethod) {
levelkey = { method: null, key: null, iv: null, uri: null };
if ((decrypturi) && (decryptmethod === 'AES-128')) {
levelkey.method = decryptmethod;
// URI to get the key
levelkey.uri = this.resolve(decrypturi, baseurl);
levelkey.key = null;
// Initialization Vector (IV)
levelkey.iv = decryptiv;
}
}
break;
case 'PROGRAM-DATE-TIME':
programDateTime = new Date(Date.parse(result[1]));
break;
default:
break;
}
}
//logger.log('found ' + level.fragments.length + ' fragments');
if(frag && !frag.url) {
level.fragments.pop();
totalduration-=frag.duration;
}
level.totalduration = totalduration;
level.endSN = currentSN - 1;
return level;
}
loadsuccess(event, stats) {
var target = event.currentTarget,
string = target.responseText,
url = target.responseURL,
id = this.id,
id2 = this.id2,
hls = this.hls,
levels;
this.loading = false;
// responseURL not supported on some browsers (it is used to detect URL redirection)
if (url === undefined) {
// fallback to initial URL
url = this.url;
}
stats.tload = performance.now();
stats.mtime = new Date(target.getResponseHeader('Last-Modified'));
if (string.indexOf('#EXTM3U') === 0) {
if (string.indexOf('#EXTINF:') > 0) {
// 1 level playlist
// if first request, fire manifest loaded event, level will be reloaded afterwards
// (this is to have a uniform logic for 1 level/multilevel playlists)
if (this.id === null) {
hls.trigger(Event.MANIFEST_LOADED, {levels: [{url: url}], url: url, stats: stats});
} else {
var levelDetails = this.parseLevelPlaylist(string, url, id);
stats.tparsed = performance.now();
hls.trigger(Event.LEVEL_LOADED, {details: levelDetails, level: id, id: id2, stats: stats});
}
} else {
levels = this.parseMasterPlaylist(string, url);
// multi level playlist, parse level info
if (levels.length) {
hls.trigger(Event.MANIFEST_LOADED, {levels: levels, url: url, stats: stats});
} else {
hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no level found in manifest'});
}
}
} else {
hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no EXTM3U delimiter'});
}
}
loaderror(event) {
var details, fatal;
if (this.id === null) {
details = ErrorDetails.MANIFEST_LOAD_ERROR;
fatal = true;
} else {
details = ErrorDetails.LEVEL_LOAD_ERROR;
fatal = false;
}
if (this.loader) {
this.loader.abort();
}
this.loading = false;
this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: this.url, loader: this.loader, response: event.currentTarget, level: this.id, id: this.id2});
}
loadtimeout() {
var details, fatal;
if (this.id === null) {
details = ErrorDetails.MANIFEST_LOAD_TIMEOUT;
fatal = true;
} else {
details = ErrorDetails.LEVEL_LOAD_TIMEOUT;
fatal = false;
}
if (this.loader) {
this.loader.abort();
}
this.loading = false;
this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: this.url, loader: this.loader, level: this.id, id: this.id2});
}
}
export default PlaylistLoader;
| ChubbyArse/Emby | MediaBrowser.WebDashboard/dashboard-ui/bower_components/hls.js/src/loader/playlist-loader.js | JavaScript | gpl-2.0 | 10,482 |
/***************************************************************************
qgsmapthemes.cpp
--------------------------------------
Date : September 2014
Copyright : (C) 2014 by Martin Dobias
Email : wonder dot sk at gmail dot 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 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsmapthemes.h"
#include "qgsmapthemecollection.h"
#include "qgslayertree.h"
#include "qgslayertreemapcanvasbridge.h"
#include "qgslayertreemodel.h"
#include "qgslayertreemodellegendnode.h"
#include "qgslayertreeview.h"
#include "qgsmaplayerstylemanager.h"
#include "qgsproject.h"
#include "qgsrenderer.h"
#include "qgsvectorlayer.h"
#include "qgisapp.h"
#include "qgsnewnamedialog.h"
#include <QInputDialog>
#include <QMessageBox>
QgsMapThemes *QgsMapThemes::sInstance;
QgsMapThemes::QgsMapThemes()
: mMenu( new QMenu )
{
mMenu->addAction( QgisApp::instance()->actionShowAllLayers() );
mMenu->addAction( QgisApp::instance()->actionHideAllLayers() );
mMenu->addAction( QgisApp::instance()->actionShowSelectedLayers() );
mMenu->addAction( QgisApp::instance()->actionHideSelectedLayers() );
mMenu->addAction( QgisApp::instance()->actionHideDeselectedLayers() );
mMenu->addSeparator();
mReplaceMenu = new QMenu( tr( "Replace Theme" ) );
mMenu->addMenu( mReplaceMenu );
mActionAddPreset = mMenu->addAction( tr( "Add Theme…" ), this, SLOT( addPreset() ) );
mMenuSeparator = mMenu->addSeparator();
mActionRemoveCurrentPreset = mMenu->addAction( tr( "Remove Current Theme" ), this, SLOT( removeCurrentPreset() ) );
connect( mMenu, &QMenu::aboutToShow, this, &QgsMapThemes::menuAboutToShow );
}
QgsMapThemeCollection::MapThemeRecord QgsMapThemes::currentState()
{
QgsLayerTreeGroup *root = QgsProject::instance()->layerTreeRoot();
QgsLayerTreeModel *model = QgisApp::instance()->layerTreeView()->layerTreeModel();
return QgsMapThemeCollection::createThemeFromCurrentState( root, model );
}
QgsMapThemes *QgsMapThemes::instance()
{
if ( !sInstance )
sInstance = new QgsMapThemes();
return sInstance;
}
void QgsMapThemes::addPreset( const QString &name )
{
QgsProject::instance()->mapThemeCollection()->insert( name, currentState() );
}
void QgsMapThemes::updatePreset( const QString &name )
{
QgsProject::instance()->mapThemeCollection()->update( name, currentState() );
}
QList<QgsMapLayer *> QgsMapThemes::orderedPresetVisibleLayers( const QString &name ) const
{
QStringList visibleIds = QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayerIds( name );
// also make sure to order the layers according to map canvas order
QList<QgsMapLayer *> lst;
Q_FOREACH ( QgsMapLayer *layer, QgsProject::instance()->layerTreeRoot()->layerOrder() )
{
if ( visibleIds.contains( layer->id() ) )
{
lst << layer;
}
}
return lst;
}
QMenu *QgsMapThemes::menu()
{
return mMenu;
}
void QgsMapThemes::addPreset()
{
QStringList existingNames = QgsProject::instance()->mapThemeCollection()->mapThemes();
QgsNewNameDialog dlg( tr( "theme" ), tr( "Theme" ), QStringList(), existingNames, QRegExp(), Qt::CaseInsensitive, mMenu );
dlg.setWindowTitle( tr( "Map Themes" ) );
dlg.setHintString( tr( "Name of the new theme" ) );
dlg.setOverwriteEnabled( false );
dlg.setConflictingNameWarning( tr( "A theme with this name already exists." ) );
if ( dlg.exec() != QDialog::Accepted || dlg.name().isEmpty() )
return;
addPreset( dlg.name() );
}
void QgsMapThemes::presetTriggered()
{
QAction *actionPreset = qobject_cast<QAction *>( sender() );
if ( !actionPreset )
return;
applyState( actionPreset->text() );
}
void QgsMapThemes::replaceTriggered()
{
QAction *actionPreset = qobject_cast<QAction *>( sender() );
if ( !actionPreset )
return;
int res = QMessageBox::question( mMenu, tr( "Replace Theme" ),
trUtf8( "Are you sure you want to replace the existing theme “%1”?" ).arg( actionPreset->text() ),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
if ( res != QMessageBox::Yes )
return;
//adding preset with same name is effectively a replace
addPreset( actionPreset->text() );
}
void QgsMapThemes::applyState( const QString &presetName )
{
if ( !QgsProject::instance()->mapThemeCollection()->hasMapTheme( presetName ) )
return;
QgsLayerTreeGroup *root = QgsProject::instance()->layerTreeRoot();
QgsLayerTreeModel *model = QgisApp::instance()->layerTreeView()->layerTreeModel();
QgsProject::instance()->mapThemeCollection()->applyTheme( presetName, root, model );
}
void QgsMapThemes::removeCurrentPreset()
{
for ( QAction *actionPreset : qgis::as_const( mMenuPresetActions ) )
{
if ( actionPreset->isChecked() )
{
int res = QMessageBox::question( mMenu, tr( "Remove Theme" ),
trUtf8( "Are you sure you want to remove the existing theme “%1”?" ).arg( actionPreset->text() ),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
if ( res == QMessageBox::Yes )
QgsProject::instance()->mapThemeCollection()->removeMapTheme( actionPreset->text() );
break;
}
}
}
void QgsMapThemes::menuAboutToShow()
{
qDeleteAll( mMenuPresetActions );
mMenuPresetActions.clear();
mReplaceMenu->clear();
qDeleteAll( mMenuReplaceActions );
mMenuReplaceActions.clear();
QgsMapThemeCollection::MapThemeRecord rec = currentState();
bool hasCurrent = false;
Q_FOREACH ( const QString &grpName, QgsProject::instance()->mapThemeCollection()->mapThemes() )
{
QAction *a = new QAction( grpName, mMenu );
a->setCheckable( true );
if ( !hasCurrent && rec == QgsProject::instance()->mapThemeCollection()->mapThemeState( grpName ) )
{
a->setChecked( true );
hasCurrent = true;
}
connect( a, &QAction::triggered, this, &QgsMapThemes::presetTriggered );
mMenuPresetActions.append( a );
QAction *replaceAction = new QAction( grpName, mReplaceMenu );
connect( replaceAction, &QAction::triggered, this, &QgsMapThemes::replaceTriggered );
mReplaceMenu->addAction( replaceAction );
}
mMenu->insertActions( mMenuSeparator, mMenuPresetActions );
mReplaceMenu->addActions( mMenuReplaceActions );
mActionAddPreset->setEnabled( !hasCurrent );
mActionRemoveCurrentPreset->setEnabled( hasCurrent );
}
| stevenmizuno/QGIS | src/app/qgsmapthemes.cpp | C++ | gpl-2.0 | 7,007 |
<?php
namespace PayPal\Api;
use PayPal\Common\PPModel;
use PayPal\Common\FormatConverter;
use PayPal\Validation\NumericValidator;
/**
* Class Currency
*
* Base object for all financial value related fields (balance, payment due, etc.)
*
* @package PayPal\Api
*
* @property string currency
* @property string value
*/
class Currency extends PPModel
{
/**
* 3 letter currency code as defined by ISO 4217.
*
* @param string $currency
*
* @return $this
*/
public function setCurrency($currency)
{
$this->currency = $currency;
return $this;
}
/**
* 3 letter currency code as defined by ISO 4217.
*
* @return string
*/
public function getCurrency()
{
return $this->currency;
}
/**
* amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
*
* @param string|double $value
*
* @return $this
*/
public function setValue($value)
{
NumericValidator::validate($value, "Value");
$value = FormatConverter::formatToTwoDecimalPlaces($value);
$this->value = $value;
return $this;
}
/**
* amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
*
* @return string
*/
public function getValue()
{
return $this->value;
}
}
| tectronics/tyres-wordpress | wp-content/plugins/directory/libraries/PayPal-PHP-SDK/lib/PayPal/Api/Currency.php | PHP | gpl-2.0 | 1,453 |
(function(){
var PushBullet = {};
PushBullet.init = function(clientId, redirectUri){
this.clientId = clientId;
this.redirectUri = redirectUri;
this.accessToken = localStorage.pushBulletAccessToken;
};
//tests if we are authorized
PushBullet.checkAuth = function(callback){
request("https://api.pushbullet.com/v2/users/me",true,function(results){
callback(results != null);
});
};
//attempts to obtain a working accessToken, once Obtained it callsback with true
PushBullet.doAuth = function(callback){
var popup = window.open("https://www.pushbullet.com/authorize?client_id=" + encodeURIComponent(PushBullet.clientId) + "&redirect_uri=" + encodeURIComponent(this.redirectUri) + "&response_type=token",
"_blank","height=600,width=500,left=" + Math.round($(document).width() / 2 - 250) + ",top=" + Math.round($(document).height() / 2 - 300));
function onClosed(){
PushBullet.accessToken = localStorage.pushBulletAccessToken;
PushBullet.checkAuth(callback);
}
var popupInterval = setInterval(function(){
if (popup == null || popup.closed){
clearInterval(popupInterval);
onClosed();
}
},50);
};
PushBullet.Note = function(title, body){
this.type = "note";
this.title = title;
this.body = body;
};
PushBullet.Link = function(title,body,url){
this.type = "link";
this.title = title;
this.body = body;
this.url = url;
};
PushBullet.CheckList = function(title,items){
this.type = "list";
this.title = title;
this.items = items;
}
PushBullet.pushToChannel = function (channelName,pushBulletMessage){
var params = {
channel_tag: channelName
};
for (var param in pushBulletMessage){
params[param] = pushBulletMessage[param];
}
post("https://api.pushbullet.com/v2/pushes",true,params,function(results){
console.log(results);
});
}
function request(url, useAuth,callback){
var options = {};
if (useAuth && PushBullet.accessToken != null){
options.headers = {
'Authorization': 'Bearer ' + PushBullet.accessToken
};
}
options.success = function(response){
callback(response);
};
options.error = function(){
callback(null);
}
$.ajax(url,options);
}
function post(url,useAuth,params,callback){
var options = {};
if (useAuth && PushBullet.accessToken != null){
options.headers = {
'Authorization': 'Bearer ' + PushBullet.accessToken
};
}
options.type = "POST";
options.data = params;
options.success = function(response){
callback(response);
};
options.error = function(){
callback(null);
}
$.ajax(url,options);
}
window.PushBullet = PushBullet;
})(); | Belthazor2008/googulator | public_html/lib/pushbullet.js | JavaScript | gpl-3.0 | 3,181 |
/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Nathan Binkert
*/
/* @file
* Device module for modelling an ethernet hub
*/
#include "dev/net/etherbus.hh"
#include <cmath>
#include <deque>
#include <string>
#include <vector>
#include "base/logging.hh"
#include "base/trace.hh"
#include "debug/Ethernet.hh"
#include "debug/EthernetData.hh"
#include "dev/net/etherdump.hh"
#include "dev/net/etherint.hh"
#include "dev/net/etherpkt.hh"
#include "params/EtherBus.hh"
#include "sim/core.hh"
using namespace std;
EtherBus::EtherBus(const Params *p)
: EtherObject(p), ticksPerByte(p->speed), loopback(p->loopback),
event([this]{ txDone(); }, "ethernet bus completion"),
sender(0), dump(p->dump)
{
}
void
EtherBus::txDone()
{
devlist_t::iterator i = devlist.begin();
devlist_t::iterator end = devlist.end();
DPRINTF(Ethernet, "ethernet packet received: length=%d\n", packet->length);
DDUMP(EthernetData, packet->data, packet->length);
while (i != end) {
if (loopback || *i != sender)
(*i)->sendPacket(packet);
++i;
}
sender->sendDone();
if (dump)
dump->dump(packet);
sender = 0;
packet = 0;
}
EtherInt*
EtherBus::getEthPort(const std::string &if_name, int idx)
{
panic("Etherbus doesn't work\n");
}
bool
EtherBus::send(EtherInt *sndr, EthPacketPtr &pkt)
{
if (busy()) {
DPRINTF(Ethernet, "ethernet packet not sent, bus busy\n", curTick());
return false;
}
DPRINTF(Ethernet, "ethernet packet sent: length=%d\n", pkt->length);
DDUMP(EthernetData, pkt->data, pkt->length);
packet = pkt;
sender = sndr;
int delay = (int)ceil(((double)pkt->simLength * ticksPerByte) + 1.0);
DPRINTF(Ethernet, "scheduling packet: delay=%d, (rate=%f)\n",
delay, ticksPerByte);
schedule(event, curTick() + delay);
return true;
}
EtherBus *
EtherBusParams::create()
{
return new EtherBus(this);
}
| vineodd/PIMSim | GEM5Simulation/gem5/src/dev/net/etherbus.cc | C++ | gpl-3.0 | 3,498 |
<?php
/**
*
* @package mahara
* @subpackage blocktype-newviews
* @author Catalyst IT Ltd
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
* @copyright For copyright information on Mahara, please see the README file distributed with this software.
*
*/
defined('INTERNAL') || die();
class PluginBlocktypeNewViews extends MaharaCoreBlocktype {
public static function get_title() {
return get_string('title1', 'blocktype.newviews');
}
public static function get_description() {
return get_string('description2', 'blocktype.newviews');
}
public static function get_categories() {
return array('general' => 21000);
}
public static function get_viewtypes() {
return array('dashboard');
}
public static function render_instance(BlockInstance $instance, $editing=false) {
global $USER;
require_once('view.php');
$configdata = $instance->get('configdata');
$nviews = isset($configdata['limit']) ? intval($configdata['limit']) : 5;
$view = $instance->get_view();
$sort = array(array('column' => 'mtime', 'desc' => true));
$views = View::view_search(
null, // $query
null, // $ownerquery
null, // $ownedby
null, // $copyableby
$nviews, // $limit
0, // $offset
true, // $extra
$sort, // $sort
array('portfolio'), // $types
null, // $collection
null, // $accesstypes
null, // $tag
null, // $viewid
$view->get('owner'), // $excludeowner
true // $groupbycollection
);
$smarty = smarty_core();
$smarty->assign('loggedin', $USER->is_logged_in());
$smarty->assign('views', $views->data);
return $smarty->fetch('blocktype:newviews:newviews.tpl');
}
public static function has_instance_config() {
return true;
}
public static function instance_config_form(BlockInstance $instance) {
$configdata = $instance->get('configdata');
return array('limit' => array(
'type' => 'text',
'title' => get_string('viewstoshow1', 'blocktype.newviews'),
'description' => get_string('viewstoshowdescription', 'blocktype.newviews'),
'defaultvalue' => (isset($configdata['limit'])) ? intval($configdata['limit']) : 5,
'size' => 3,
'minvalue' => 1,
'maxvalue' => 100,
));
}
public static function default_copy_type() {
return 'shallow';
}
public static function get_instance_title(BlockInstance $instance) {
return get_string('title1', 'blocktype.newviews');
}
public static function should_ajaxify() {
return true;
}
/**
* Shouldn't be linked to any artefacts via the view_artefacts table.
*
* @param BlockInstance $instance
* @return multitype:
*/
public static function get_artefacts(BlockInstance $instance) {
return array();
}
}
| piersharding/mahara | htdocs/blocktype/newviews/lib.php | PHP | gpl-3.0 | 3,184 |
package at.tyron.vintagecraft.Block.Utility;
import at.tyron.vintagecraft.VintageCraft;
import at.tyron.vintagecraft.Block.BlockContainerVC;
import at.tyron.vintagecraft.TileEntity.TECokeOvenDoor;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.properties.PropertyDirection;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class BlockCokeOvenDoor extends BlockContainerVC {
public static PropertyBool OPENED = PropertyBool.create("opened");
public static PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL);
public BlockCokeOvenDoor() {
super(Material.iron);
setCreativeTab(VintageCraft.craftedBlocksTab);
setDefaultState(blockState.getBaseState().withProperty(OPENED, false).withProperty(FACING, EnumFacing.NORTH));
}
@Override
public int getRenderType() {
return 3;
}
@Override
public String getSubType(ItemStack stack) {
return null;
}
@Override
public TileEntity createNewTileEntity(World worldIn, int meta) {
return new TECokeOvenDoor();
}
public IBlockState getStateFromMeta(int meta) {
EnumFacing enumfacing = EnumFacing.getFront(meta >> 1);
if (enumfacing.getAxis() == EnumFacing.Axis.Y) {
enumfacing = EnumFacing.NORTH;
}
boolean opened = (meta & 1) > 0;
return this.getDefaultState().withProperty(FACING, enumfacing).withProperty(OPENED, opened);
}
public int getMetaFromState(IBlockState state) {
boolean opened = (Boolean)state.getValue(OPENED);
return (((EnumFacing)state.getValue(FACING)).getIndex() << 1) + (opened ? 1 : 0);
}
protected BlockState createBlockState() {
return new BlockState(this, new IProperty[] {OPENED, FACING});
}
@Override
public void onNeighborBlockChange(World world, BlockPos pos, IBlockState state, Block neighborBlock) {
EnumFacing facing = (EnumFacing) state.getValue(FACING);
// if (!suitableGround(world, pos.down())) {
// world.destroyBlock(pos, true);
// }
}
@Override
public int damageDropped(IBlockState state) {
return 0;
}
@Override
public boolean canPlaceBlockOnSide(World world, BlockPos pos, EnumFacing side) {
return true; //this.canPlaceBlockAt(world, pos) && suitableGround(world, pos.down());
}
@Override
public boolean isSideSolid(IBlockAccess world, BlockPos pos, EnumFacing side) {
return false;
}
@Override
public boolean shouldSideBeRendered(IBlockAccess worldIn, BlockPos pos, EnumFacing side) {
return true;
}
public boolean isFullCube() {
return false;
}
@Override
public boolean isOpaqueCube() {
return false;
}
public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) {
return this.getDefaultState().withProperty(FACING, placer.getHorizontalFacing().getOpposite());
}
public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) {
worldIn.setBlockState(pos, state.withProperty(FACING, placer.getHorizontalFacing().getOpposite()), 2);
}
@Override
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumFacing side, float hitX, float hitY, float hitZ) {
boolean opened = (Boolean)state.getValue(OPENED);
worldIn.setBlockState(pos, state.withProperty(OPENED, !opened));
if (opened) {
worldIn.playSound(pos.getX(), pos.getY(), pos.getZ(), "vintagecraft:ironstovedoor_close", 1f, 1f, false);
} else {
worldIn.playSound(pos.getX(), pos.getY(), pos.getZ(), "vintagecraft:ironstovedoor_open", 1f, 1f, false);
}
worldIn.getBlockState(pos).getBlock().setBlockBoundsBasedOnState(worldIn, pos);
// TECokeOvenDoor te = (TECokeOvenDoor)worldIn.getTileEntity(pos);
// if (te != null) {
// System.out.println("valid: " + te.isValidCokeOven());
// }
return super.onBlockActivated(worldIn, pos, state, playerIn, side, hitX, hitY, hitZ);
}
@Override
public AxisAlignedBB getCollisionBoundingBox(World worldIn, BlockPos pos, IBlockState state) {
EnumFacing face = (EnumFacing) state.getValue(FACING);
boolean opened = (Boolean)state.getValue(OPENED);
if (opened) {
switch (face) {
case NORTH:
return AxisAlignedBB.fromBounds(pos.getX() + 1f, pos.getY(), pos.getZ() - 0.8125f, pos.getX() + 0.8125f, pos.getY() + 1f, pos.getZ() + 0.1875f);
case SOUTH:
return AxisAlignedBB.fromBounds(pos.getX(), pos.getY(), pos.getZ() + 0.8125f, pos.getX() + 0.1875f, pos.getY() + 1f, pos.getZ() + 1.8125f);
case WEST:
return AxisAlignedBB.fromBounds(pos.getX() - 0.8125f, pos.getY(), pos.getZ(), pos.getX() + 0.1875f, pos.getY() + 1f, pos.getZ() + 0.1875f);
case EAST:
return AxisAlignedBB.fromBounds(pos.getX() + 0.8125f, pos.getY(), pos.getZ() + 0.8125f, pos.getX() + 1.8125f, pos.getY() + 1f, pos.getZ() + 1f);
default: return null;
}
} else {
switch (face) {
case NORTH:
return AxisAlignedBB.fromBounds(pos.getX(), pos.getY(), pos.getZ(), pos.getX() + 1f, pos.getY() + 1f, pos.getZ() + 0.1875f);
case SOUTH:
return AxisAlignedBB.fromBounds(pos.getX(), pos.getY(), pos.getZ() + 0.8125f, pos.getX() + 1f, pos.getY() + 1f, pos.getZ() + 1f);
case WEST:
return AxisAlignedBB.fromBounds(pos.getX(), pos.getY(), pos.getZ(), pos.getX() + 0.1875f, pos.getY() + 1f, pos.getZ() + 1f);
case EAST:
return AxisAlignedBB.fromBounds(pos.getX() + 0.8125f, pos.getY(), pos.getZ(), pos.getX() + 1f, pos.getY() + 1f, pos.getZ() + 1f);
default: return null;
}
}
}
@Override
public void setBlockBoundsBasedOnState(IBlockAccess worldIn, BlockPos pos) {
AxisAlignedBB bounds = getCollisionBoundingBox(null, pos, worldIn.getBlockState(pos));
setBlockBounds((float)bounds.minX - pos.getX(), (float)bounds.minY - pos.getY(), (float)bounds.minZ - pos.getZ(), (float)bounds.maxX - pos.getX(), (float)bounds.maxY - pos.getY(), (float)bounds.maxZ - pos.getZ());
}
@Override
public AxisAlignedBB getSelectedBoundingBox(World worldIn, BlockPos pos) {
return getCollisionBoundingBox(worldIn, pos, worldIn.getBlockState(pos));
}
}
| nanakisan/vintagecraft | src/main/java/at/tyron/vintagecraft/Block/Utility/BlockCokeOvenDoor.java | Java | gpl-3.0 | 7,072 |
package net.minecraft.world.chunk;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class BlockStatePaletteLinear implements IBlockStatePalette
{
private final IBlockState[] states;
private final IBlockStatePaletteResizer resizeHandler;
private final int bits;
private int arraySize;
public BlockStatePaletteLinear(int bitsIn, IBlockStatePaletteResizer resizeHandlerIn)
{
this.states = new IBlockState[1 << bitsIn];
this.bits = bitsIn;
this.resizeHandler = resizeHandlerIn;
}
public int idFor(IBlockState state)
{
for (int i = 0; i < this.arraySize; ++i)
{
if (this.states[i] == state)
{
return i;
}
}
int j = this.arraySize;
if (j < this.states.length)
{
this.states[j] = state;
++this.arraySize;
return j;
}
else
{
return this.resizeHandler.onResize(this.bits + 1, state);
}
}
/**
* Gets the block state by the palette id.
*/
@Nullable
public IBlockState getBlockState(int indexKey)
{
return indexKey >= 0 && indexKey < this.arraySize ? this.states[indexKey] : null;
}
@SideOnly(Side.CLIENT)
public void read(PacketBuffer buf)
{
this.arraySize = buf.readVarInt();
for (int i = 0; i < this.arraySize; ++i)
{
this.states[i] = Block.BLOCK_STATE_IDS.getByValue(buf.readVarInt());
}
}
public void write(PacketBuffer buf)
{
buf.writeVarInt(this.arraySize);
for (int i = 0; i < this.arraySize; ++i)
{
buf.writeVarInt(Block.BLOCK_STATE_IDS.get(this.states[i]));
}
}
public int getSerializedSize()
{
int i = PacketBuffer.getVarIntSize(this.arraySize);
for (int j = 0; j < this.arraySize; ++j)
{
i += PacketBuffer.getVarIntSize(Block.BLOCK_STATE_IDS.get(this.states[j]));
}
return i;
}
} | Severed-Infinity/technium | build/tmp/recompileMc/sources/net/minecraft/world/chunk/BlockStatePaletteLinear.java | Java | gpl-3.0 | 2,268 |
/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#include "neigh_list_kokkos.h"
#include "atom.h"
#include "memory.h"
using namespace LAMMPS_NS;
enum{NSQ,BIN,MULTI};
/* ---------------------------------------------------------------------- */
template<class Device>
NeighListKokkos<Device>::NeighListKokkos(class LAMMPS *lmp):NeighList(lmp)
{
_stride = 1;
maxneighs = 16;
kokkos = 1;
maxatoms = 0;
execution_space = ExecutionSpaceFromDevice<Device>::space;
};
/* ---------------------------------------------------------------------- */
template<class Device>
void NeighListKokkos<Device>::grow(int nmax)
{
// skip if this list is already long enough to store nmax atoms
if (nmax <= maxatoms) return;
maxatoms = nmax;
k_ilist =
DAT::tdual_int_1d("neighlist:ilist",maxatoms);
d_ilist = k_ilist.view<Device>();
d_numneigh =
typename ArrayTypes<Device>::t_int_1d("neighlist:numneigh",maxatoms);
d_neighbors =
typename ArrayTypes<Device>::t_neighbors_2d("neighlist:neighbors",
maxatoms,maxneighs);
}
/* ---------------------------------------------------------------------- */
namespace LAMMPS_NS {
template class NeighListKokkos<LMPDeviceType>;
#ifdef KOKKOS_HAVE_CUDA
template class NeighListKokkos<LMPHostType>;
#endif
}
| ovilab/atomify | libs/lammps/src/KOKKOS/neigh_list_kokkos.cpp | C++ | gpl-3.0 | 1,894 |
#include <stdio.h>
int modularInverse(int number, int mod);
void extendedEuclid(int, int, int* d, int* x, int* y);
int main()
{
int number, mod;
scanf("%d %d", &number, &mod);
int ans = modularInverse(number, mod);
if (ans == -1)
fprintf(stderr, "Couldn't calculate modular inverse!\n");
else
printf("%d", ans);
}
int modularInverse(int number, int mod)
{
if (1 <= number && number <= mod - 1)
{
int x, y, d;
extendedEuclid(number, mod, &d, &x, &y);
if (d == 1)
{
while (x < 0)
x += mod;
return x;
}
else
fprintf(stderr, "The number and mod need to be coprime\n");
}
else
fprintf(stderr, "Number needs to be between 1 and mod!\n");
return -1;
}
void extendedEuclid(int a, int b, int* d, int* x, int* y)
{
if (b == 0)
{
*x = 1;
*y = 0;
*d = a;
return;
}
int x0, y0;
extendedEuclid(b, a % b, d, &x0, &y0);
*x = y0;
*y = x0 - (a / b) * y0;
}
| OpenGenus/cosmos | code/mathematical_algorithms/src/modular_inverse/modular_inverse.cpp | C++ | gpl-3.0 | 1,064 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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 Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** 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-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qqmldelayedcallqueue_p.h"
#include <private/qv8engine_p.h>
#include <private/qqmlengine_p.h>
#include <private/qqmljavascriptexpression_p.h>
#include <private/qv4value_p.h>
#include <private/qv4qobjectwrapper_p.h>
#include <QQmlError>
QT_BEGIN_NAMESPACE
//
// struct QQmlDelayedCallQueue::DelayedFunctionCall
//
void QQmlDelayedCallQueue::DelayedFunctionCall::execute(QV4::ExecutionEngine *engine) const
{
if (!m_guarded ||
(!m_objectGuard.isNull() &&
!QQmlData::wasDeleted(m_objectGuard) &&
QQmlData::get(m_objectGuard) &&
!QQmlData::get(m_objectGuard)->isQueuedForDeletion)) {
QV4::Scope scope(engine);
QV4::ArrayObject *array = m_args.as<QV4::ArrayObject>();
const int argCount = array ? array->getLength() : 0;
QV4::ScopedCallData callData(scope, argCount);
callData->thisObject = QV4::Encode::undefined();
for (int i = 0; i < argCount; i++) {
callData->args[i] = array->getIndexed(i);
}
const QV4::FunctionObject *callback = m_function.as<QV4::FunctionObject>();
Q_ASSERT(callback);
callback->call(scope, callData);
if (scope.engine->hasException) {
QQmlError error = scope.engine->catchExceptionAsQmlError();
error.setDescription(error.description() + QLatin1String(" (exception occurred during delayed function evaluation)"));
QQmlEnginePrivate::warning(QQmlEnginePrivate::get(scope.engine->qmlEngine()), error);
}
}
}
//
// class QQmlDelayedCallQueue
//
QQmlDelayedCallQueue::QQmlDelayedCallQueue()
: QObject(0), m_engine(0), m_callbackOutstanding(false)
{
}
QQmlDelayedCallQueue::~QQmlDelayedCallQueue()
{
}
void QQmlDelayedCallQueue::init(QV4::ExecutionEngine* engine)
{
m_engine = engine;
const QMetaObject &metaObject = QQmlDelayedCallQueue::staticMetaObject;
int methodIndex = metaObject.indexOfSlot("ticked()");
m_tickedMethod = metaObject.method(methodIndex);
}
void QQmlDelayedCallQueue::addUniquelyAndExecuteLater(const QV4::BuiltinFunction *, QV4::Scope &scope, QV4::CallData *callData)
{
if (callData->argc == 0)
THROW_GENERIC_ERROR("Qt.callLater: no arguments given");
const QV4::FunctionObject *func = callData->args[0].as<QV4::FunctionObject>();
if (!func)
THROW_GENERIC_ERROR("Qt.callLater: first argument not a function or signal");
QPair<QObject *, int> functionData = QV4::QObjectMethod::extractQtMethod(func);
QVector<DelayedFunctionCall>::Iterator iter;
if (functionData.second != -1) {
// This is a QObject function wrapper
iter = m_delayedFunctionCalls.begin();
while (iter != m_delayedFunctionCalls.end()) {
DelayedFunctionCall& dfc = *iter;
QPair<QObject *, int> storedFunctionData = QV4::QObjectMethod::extractQtMethod(dfc.m_function.as<QV4::FunctionObject>());
if (storedFunctionData == functionData) {
break; // Already stored!
}
++iter;
}
} else {
// This is a JavaScript function (dynamic slot on VMEMO)
iter = m_delayedFunctionCalls.begin();
while (iter != m_delayedFunctionCalls.end()) {
DelayedFunctionCall& dfc = *iter;
if (callData->argument(0) == dfc.m_function.value()) {
break; // Already stored!
}
++iter;
}
}
const bool functionAlreadyStored = (iter != m_delayedFunctionCalls.end());
if (functionAlreadyStored) {
DelayedFunctionCall dfc = *iter;
m_delayedFunctionCalls.erase(iter);
m_delayedFunctionCalls.append(dfc);
} else {
m_delayedFunctionCalls.append(QV4::PersistentValue(m_engine, callData->argument(0)));
}
DelayedFunctionCall& dfc = m_delayedFunctionCalls.last();
if (dfc.m_objectGuard.isNull()) {
if (functionData.second != -1) {
// if it's a qobject function wrapper, guard against qobject deletion
dfc.m_objectGuard = QQmlGuard<QObject>(functionData.first);
dfc.m_guarded = true;
} else if (func->scope()->type == QV4::Heap::ExecutionContext::Type_QmlContext) {
QV4::QmlContext::Data *g = static_cast<QV4::QmlContext::Data *>(func->scope());
Q_ASSERT(g->qml->scopeObject);
dfc.m_objectGuard = QQmlGuard<QObject>(g->qml->scopeObject);
dfc.m_guarded = true;
}
}
storeAnyArguments(dfc, callData, 1, m_engine);
if (!m_callbackOutstanding) {
m_tickedMethod.invoke(this, Qt::QueuedConnection);
m_callbackOutstanding = true;
}
scope.result = QV4::Encode::undefined();
}
void QQmlDelayedCallQueue::storeAnyArguments(DelayedFunctionCall &dfc, const QV4::CallData *callData, int offset, QV4::ExecutionEngine *engine)
{
const int length = callData->argc - offset;
if (length == 0) {
dfc.m_args.clear();
return;
}
QV4::Scope scope(engine);
QV4::ScopedArrayObject array(scope, engine->newArrayObject(length));
int i = 0;
for (int j = offset; j < callData->argc; ++i, ++j) {
array->putIndexed(i, callData->args[j]);
}
dfc.m_args.set(engine, array);
}
void QQmlDelayedCallQueue::executeAllExpired_Later()
{
// Make a local copy of the list and clear m_delayedFunctionCalls
// This ensures correct behavior in the case of recursive calls to Qt.callLater()
QVector<DelayedFunctionCall> delayedCalls = m_delayedFunctionCalls;
m_delayedFunctionCalls.clear();
QVector<DelayedFunctionCall>::Iterator iter = delayedCalls.begin();
while (iter != delayedCalls.end()) {
DelayedFunctionCall& dfc = *iter;
dfc.execute(m_engine);
++iter;
}
}
void QQmlDelayedCallQueue::ticked()
{
m_callbackOutstanding = false;
executeAllExpired_Later();
}
QT_END_NAMESPACE
#include "moc_qqmldelayedcallqueue_p.cpp"
| geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtdeclarative/src/qml/qml/qqmldelayedcallqueue.cpp | C++ | gpl-3.0 | 7,883 |
import math
def PrimeFactors(num):
primeFactors = []
for i in range(2, int(math.sqrt(num)) + 1):
while num % i == 0:
primeFactors.append(i)
num //= i
if num > 2:
primeFactors.append(num)
return primeFactors
def main():
factors = PrimeFactors(36)
print(factors)
if __name__ == '__main__':
main()
| gauravsitlani/programming | prime_factors/prime_factors.py | Python | gpl-3.0 | 315 |
"""
Test of basic 1D plotting methods in MantidPlot
"""
import mantidplottests
from mantidplottests import *
from mantidplot import *
from PyQt4 import QtGui, QtCore
class MantidPlotMdiSubWindowTest(unittest.TestCase):
def test_table(self):
self.doTest( newTable() )
def test_graph(self):
self.doTest( newGraph() )
def doTest(self, w):
if w.isFloating():
w.dock()
self.assertFalse( w.isFloating() )
self.assertTrue( w.isDocked() )
size = w.size()
w.undock()
self.assertTrue( w.isFloating() )
self.assertFalse( w.isDocked() )
w.dock()
self.assertFalse( w.isFloating() )
self.assertTrue( w.isDocked() )
# TODO: sizes are not equal. Should we fix it?
# self.assertEqual( size, w.size() )
w.close()
# Run the unit tests
mantidplottests.runTests(MantidPlotMdiSubWindowTest)
| dymkowsk/mantid | MantidPlot/test/MantidPlotMdiSubWindowTest.py | Python | gpl-3.0 | 922 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Pdf
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Pdf_Filter_Interface */
require_once 'Zend/Pdf/Filter/Interface.php';
/**
* ASCII85 stream filter
*
* @package Zend_Pdf
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Pdf_Filter_Compression implements Zend_Pdf_Filter_Interface
{
/**
* Paeth prediction function
*
* @param integer $a
* @param integer $b
* @param integer $c
* @return integer
*/
private static function _paeth($a, $b, $c)
{
// $a - left, $b - above, $c - upper left
$p = $a + $b - $c; // initial estimate
$pa = abs($p - $a); // distances to a, b, c
$pb = abs($p - $b);
$pc = abs($p - $c);
// return nearest of a,b,c,
// breaking ties in order a,b,c.
if ($pa <= $pb && $pa <= $pc) {
return $a;
} else if ($pb <= $pc) {
return $b;
} else {
return $c;
}
}
/**
* Get Predictor decode param value
*
* @param array $params
* @return integer
* @throws Zend_Pdf_Exception
*/
private static function _getPredictorValue(&$params)
{
if (isset($params['Predictor'])) {
$predictor = $params['Predictor'];
if ($predictor != 1 && $predictor != 2 &&
$predictor != 10 && $predictor != 11 && $predictor != 12 &&
$predictor != 13 && $predictor != 14 && $predictor != 15) {
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('Invalid value of \'Predictor\' decode param - ' . $predictor . '.' );
}
return $predictor;
} else {
return 1;
}
}
/**
* Get Colors decode param value
*
* @param array $params
* @return integer
* @throws Zend_Pdf_Exception
*/
private static function _getColorsValue(&$params)
{
if (isset($params['Colors'])) {
$colors = $params['Colors'];
if ($colors != 1 && $colors != 2 && $colors != 3 && $colors != 4) {
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('Invalid value of \'Color\' decode param - ' . $colors . '.' );
}
return $colors;
} else {
return 1;
}
}
/**
* Get BitsPerComponent decode param value
*
* @param array $params
* @return integer
* @throws Zend_Pdf_Exception
*/
private static function _getBitsPerComponentValue(&$params)
{
if (isset($params['BitsPerComponent'])) {
$bitsPerComponent = $params['BitsPerComponent'];
if ($bitsPerComponent != 1 && $bitsPerComponent != 2 &&
$bitsPerComponent != 4 && $bitsPerComponent != 8 &&
$bitsPerComponent != 16 ) {
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('Invalid value of \'BitsPerComponent\' decode param - ' . $bitsPerComponent . '.' );
}
return $bitsPerComponent;
} else {
return 8;
}
}
/**
* Get Columns decode param value
*
* @param array $params
* @return integer
*/
private static function _getColumnsValue(&$params)
{
if (isset($params['Columns'])) {
return $params['Columns'];
} else {
return 1;
}
}
/**
* Convert stream data according to the filter params set before encoding.
*
* @param string $data
* @param array $params
* @return string
* @throws Zend_Pdf_Exception
*/
protected static function _applyEncodeParams($data, $params) {
$predictor = self::_getPredictorValue($params);
$colors = self::_getColorsValue($params);
$bitsPerComponent = self::_getBitsPerComponentValue($params);
$columns = self::_getColumnsValue($params);
/** None of prediction */
if ($predictor == 1) {
return $data;
}
/** TIFF Predictor 2 */
if ($predictor == 2) {
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('Not implemented yet' );
}
/** Optimal PNG prediction */
if ($predictor == 15) {
/** Use Paeth prediction as optimal */
$predictor = 14;
}
/** PNG prediction */
if ($predictor == 10 || /** None of prediction */
$predictor == 11 || /** Sub prediction */
$predictor == 12 || /** Up prediction */
$predictor == 13 || /** Average prediction */
$predictor == 14 /** Paeth prediction */
) {
$predictor -= 10;
if($bitsPerComponent == 16) {
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception("PNG Prediction with bit depth greater than 8 not yet supported.");
}
$bitsPerSample = $bitsPerComponent*$colors;
$bytesPerSample = (int)(($bitsPerSample + 7)/8); // (int)ceil(...) emulation
$bytesPerRow = (int)(($bitsPerSample*$columns + 7)/8); // (int)ceil(...) emulation
$rows = strlen($data)/$bytesPerRow;
$output = '';
$offset = 0;
if (!is_integer($rows)) {
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('Wrong data length.');
}
switch ($predictor) {
case 0: // None of prediction
for ($count = 0; $count < $rows; $count++) {
$output .= chr($predictor);
$output .= substr($data, $offset, $bytesPerRow);
$offset += $bytesPerRow;
}
break;
case 1: // Sub prediction
for ($count = 0; $count < $rows; $count++) {
$output .= chr($predictor);
$lastSample = array_fill(0, $bytesPerSample, 0);
for ($count2 = 0; $count2 < $bytesPerRow; $count2++) {
$newByte = ord($data[$offset++]);
// Note. chr() automatically cuts input to 8 bit
$output .= chr($newByte - $lastSample[$count2 % $bytesPerSample]);
$lastSample[$count2 % $bytesPerSample] = $newByte;
}
}
break;
case 2: // Up prediction
$lastRow = array_fill(0, $bytesPerRow, 0);
for ($count = 0; $count < $rows; $count++) {
$output .= chr($predictor);
for ($count2 = 0; $count2 < $bytesPerRow; $count2++) {
$newByte = ord($data[$offset++]);
// Note. chr() automatically cuts input to 8 bit
$output .= chr($newByte - $lastRow[$count2]);
$lastRow[$count2] = $newByte;
}
}
break;
case 3: // Average prediction
$lastRow = array_fill(0, $bytesPerRow, 0);
for ($count = 0; $count < $rows; $count++) {
$output .= chr($predictor);
$lastSample = array_fill(0, $bytesPerSample, 0);
for ($count2 = 0; $count2 < $bytesPerRow; $count2++) {
$newByte = ord($data[$offset++]);
// Note. chr() automatically cuts input to 8 bit
$output .= chr($newByte - floor(( $lastSample[$count2 % $bytesPerSample] + $lastRow[$count2])/2));
$lastSample[$count2 % $bytesPerSample] = $lastRow[$count2] = $newByte;
}
}
break;
case 4: // Paeth prediction
$lastRow = array_fill(0, $bytesPerRow, 0);
$currentRow = array();
for ($count = 0; $count < $rows; $count++) {
$output .= chr($predictor);
$lastSample = array_fill(0, $bytesPerSample, 0);
for ($count2 = 0; $count2 < $bytesPerRow; $count2++) {
$newByte = ord($data[$offset++]);
// Note. chr() automatically cuts input to 8 bit
$output .= chr($newByte - self::_paeth( $lastSample[$count2 % $bytesPerSample],
$lastRow[$count2],
($count2 - $bytesPerSample < 0)?
0 : $lastRow[$count2 - $bytesPerSample] ));
$lastSample[$count2 % $bytesPerSample] = $currentRow[$count2] = $newByte;
}
$lastRow = $currentRow;
}
break;
}
return $output;
}
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('Unknown prediction algorithm - ' . $predictor . '.' );
}
/**
* Convert stream data according to the filter params set after decoding.
*
* @param string $data
* @param array $params
* @return string
*/
protected static function _applyDecodeParams($data, $params) {
$predictor = self::_getPredictorValue($params);
$colors = self::_getColorsValue($params);
$bitsPerComponent = self::_getBitsPerComponentValue($params);
$columns = self::_getColumnsValue($params);
/** None of prediction */
if ($predictor == 1) {
return $data;
}
/** TIFF Predictor 2 */
if ($predictor == 2) {
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('Not implemented yet' );
}
/**
* PNG prediction
* Prediction code is duplicated on each row.
* Thus all cases can be brought to one
*/
if ($predictor == 10 || /** None of prediction */
$predictor == 11 || /** Sub prediction */
$predictor == 12 || /** Up prediction */
$predictor == 13 || /** Average prediction */
$predictor == 14 || /** Paeth prediction */
$predictor == 15 /** Optimal prediction */) {
$bitsPerSample = $bitsPerComponent*$colors;
$bytesPerSample = ceil($bitsPerSample/8);
$bytesPerRow = ceil($bitsPerSample*$columns/8);
$rows = ceil(strlen($data)/($bytesPerRow + 1));
$output = '';
$offset = 0;
$lastRow = array_fill(0, $bytesPerRow, 0);
for ($count = 0; $count < $rows; $count++) {
$lastSample = array_fill(0, $bytesPerSample, 0);
switch (ord($data[$offset++])) {
case 0: // None of prediction
$output .= substr($data, $offset, $bytesPerRow);
for ($count2 = 0; $count2 < $bytesPerRow && $offset < strlen($data); $count2++) {
$lastSample[$count2 % $bytesPerSample] = $lastRow[$count2] = ord($data[$offset++]);
}
break;
case 1: // Sub prediction
for ($count2 = 0; $count2 < $bytesPerRow && $offset < strlen($data); $count2++) {
$decodedByte = (ord($data[$offset++]) + $lastSample[$count2 % $bytesPerSample]) & 0xFF;
$lastSample[$count2 % $bytesPerSample] = $lastRow[$count2] = $decodedByte;
$output .= chr($decodedByte);
}
break;
case 2: // Up prediction
for ($count2 = 0; $count2 < $bytesPerRow && $offset < strlen($data); $count2++) {
$decodedByte = (ord($data[$offset++]) + $lastRow[$count2]) & 0xFF;
$lastSample[$count2 % $bytesPerSample] = $lastRow[$count2] = $decodedByte;
$output .= chr($decodedByte);
}
break;
case 3: // Average prediction
for ($count2 = 0; $count2 < $bytesPerRow && $offset < strlen($data); $count2++) {
$decodedByte = (ord($data[$offset++]) +
floor(( $lastSample[$count2 % $bytesPerSample] + $lastRow[$count2])/2)
) & 0xFF;
$lastSample[$count2 % $bytesPerSample] = $lastRow[$count2] = $decodedByte;
$output .= chr($decodedByte);
}
break;
case 4: // Paeth prediction
$currentRow = array();
for ($count2 = 0; $count2 < $bytesPerRow && $offset < strlen($data); $count2++) {
$decodedByte = (ord($data[$offset++]) +
self::_paeth($lastSample[$count2 % $bytesPerSample],
$lastRow[$count2],
($count2 - $bytesPerSample < 0)?
0 : $lastRow[$count2 - $bytesPerSample])
) & 0xFF;
$lastSample[$count2 % $bytesPerSample] = $currentRow[$count2] = $decodedByte;
$output .= chr($decodedByte);
}
$lastRow = $currentRow;
break;
default:
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('Unknown prediction tag.');
}
}
return $output;
}
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('Unknown prediction algorithm - ' . $predictor . '.' );
}
}
| areeves/openfisma | library/Zend/Pdf/Filter/Compression.php | PHP | gpl-3.0 | 15,570 |
/*
This file is part of ZAX.
ZAX 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.
ZAX 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 ZAX. If not, see <http://www.gnu.org/licenses/>.
*/
package com.inovex.zabbixmobile.widget;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* This broadcast receiver listens for replacements of the application package.
* If the package receives an update, widget update alarm needs to be set again.
*
*/
public class PackageReplacedReceiver extends BroadcastReceiver {
private static final String TAG = PackageReplacedReceiver.class
.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "package replaced. Sending widget update broadcast.");
Intent broadcastIntent = new Intent(context,
WidgetUpdateBroadcastReceiver.class);
broadcastIntent.putExtra(WidgetUpdateBroadcastReceiver.REFRESH_RATE_CHANGED,
true);
context.sendBroadcast(broadcastIntent);
}
}
| inovex/zax | src/main/java/com/inovex/zabbixmobile/widget/PackageReplacedReceiver.java | Java | gpl-3.0 | 1,490 |
/**
* Copyright (C) 2005-2013, Stefan Strömberg <stefangs@nethome.nu>
*
* This file is part of OpenNetHome (http://www.nethome.nu)
*
* OpenNetHome 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.
*
* OpenNetHome 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/>.
*/
/**
* @author Peter Lagerhem
*
* History:
* 2010-10-27 pela Created.
*
*/
package nu.nethome.home.items.web.servergui;
import nu.nethome.home.item.Attribute;
/**
* This class can be used to collect errors of home item attributes. You could
* typically use it where IllegalFormat (and alike) exceptions are caught and
* you want to record the cause for the error and the attribute.
*
* The printPage() method of the EditItemPage class uses this class for
* displaying the attribute errors.
*/
public class HomeItemError {
private Attribute attribute;
private String errorMessage;
public ErrorType type;
public enum ErrorType {
general, attribute
}
/**
* @return the attribute
*/
public Attribute getAttribute() {
return attribute;
}
/**
* @return the errorMessage
*/
public String getErrorMessage() {
return errorMessage;
}
public HomeItemError(Attribute attribute, String errorMessage) {
this.attribute = attribute;
this.errorMessage = errorMessage;
type = ErrorType.attribute;
}
public HomeItemError(String errorMessage) {
this.errorMessage = errorMessage;
type = ErrorType.general;
}
}
| stefangs/NetHomeServer | home-items/web-items/src/main/java/nu/nethome/home/items/web/servergui/HomeItemError.java | Java | gpl-3.0 | 1,950 |
import { Routes } from '@angular/router';
import {
auditsRoute,
configurationRoute,
docsRoute,
healthRoute,
logsRoute,
metricsRoute,
trackerRoute,
userMgmtRoute,
userDialogRoute
} from './';
import { UserRouteAccessService } from '../shared';
const ADMIN_ROUTES = [
auditsRoute,
configurationRoute,
docsRoute,
healthRoute,
logsRoute,
trackerRoute,
...userMgmtRoute,
metricsRoute
];
export const adminState: Routes = [{
path: '',
data: {
authorities: ['ROLE_ADMIN']
},
canActivate: [UserRouteAccessService],
children: ADMIN_ROUTES
},
...userDialogRoute
];
| SGKhmCs/wBoard | src/main/webapp/app/admin/admin.route.ts | TypeScript | gpl-3.0 | 659 |
var gr__expj_8h =
[
[ "gr_expj", "gr__expj_8h.html#a7d0144e5774158b746199c1da4d5b5ac", null ]
]; | aviralchandra/Sandhi | build/gr36/docs/doxygen/html/gr__expj_8h.js | JavaScript | gpl-3.0 | 100 |
#include "./class.h"
#include "../../util/trace.h"
#include "../../util/log.h"
#include <map>
#include <algorithm>
#include "../common/method.h"
#include "../common/property.h"
#include "../common/ref.h"
#include "./ivar.h"
#include "./protocol.h"
#include "../TopologySort.h"
extern std::map<const void*,Class> g_classPointers;
Class RegisterClass(const class_t* cls, intptr_t slide)
{
LOG << "Processing ObjC class " << cls->data()->className << std::endl;
const class_t* meta = cls->isa;
Class conv, super;
auto itSuper = g_classPointers.find(cls->superclass);
if (itSuper != g_classPointers.end())
super = itSuper->second;
else
super = reinterpret_cast<Class>(cls->superclass);
LOG << "...superclass is @" << super << std::endl;
conv = objc_allocateClassPair(super, cls->data()->className, 0);
const class_ro_t* ro = cls->data();
const class_ro_t* roMeta = meta->data();
if (ro->baseMethods)
ConvertMethodListGen(conv, ro->baseMethods);
if (roMeta->baseMethods)
ConvertMethodListGen(object_getClass(id(conv)), roMeta->baseMethods);
if (ro->ivars)
ConvertIvarList(conv, ro->ivars);
if (ro->baseProtocols)
AddClassProtocols(conv, ro->baseProtocols, slide);
if (ro->baseProperties)
{
ConvertProperties(ro->baseProperties, [conv](const char* name, const objc_property_attribute_t* attr, unsigned int count) { class_addProperty(conv, name, attr, count); bug_gnustepFixPropertyCount(conv); });
}
// conv->instance_size = ro->instSize;
// conv->isa->instance_size = roMeta->instSize;
objc_registerClassPair(conv);
LOG << "ObjC class " << cls->data()->className << " now @" << conv << std::endl;
g_classPointers[cls] = conv;
return conv;
}
void ProcessClassesNew(const struct mach_header* mh, intptr_t slide, const class_t** classes, unsigned long size)
{
class_t **class_refs, **class_refs_end, **super_refs, **super_refs_end;
unsigned long refsize, refsize_s;
std::vector<const class_t*> vecClasses;
std::set<const class_t*> setClasses;
class_refs = reinterpret_cast<class_t**>(
getsectdata(mh, SEG_OBJC_CLASSREFS_NEW, SECT_OBJC_CLASSREFS_NEW, &refsize)
);
super_refs = reinterpret_cast<class_t**>(
getsectdata(mh, SEG_OBJC_SUPERREFS_NEW, SECT_OBJC_SUPERREFS_NEW, &refsize_s)
);
if (class_refs)
class_refs_end = class_refs + refsize / sizeof(class_t*);
if (super_refs)
super_refs_end = super_refs + refsize_s / sizeof(class_t*);
std::copy(classes, classes+size/sizeof(class_t*), std::inserter(setClasses, setClasses.begin()));
topology_sort<const class_t>(setClasses, vecClasses,
[&setClasses](const class_t* t) { return setClasses.count(t->superclass) ? std::set<const class_t*>{t->superclass} : std::set<const class_t*>(); }
);
for (const class_t* cls : vecClasses)
{
Class c = RegisterClass(cls, slide);
if (class_refs)
{
find_and_fix(class_refs, class_refs_end, cls, c);
find_and_fix(class_refs, class_refs_end, cls->isa, object_getClass(id(c)));
}
if (super_refs)
{
find_and_fix(super_refs, super_refs_end, cls, c);
find_and_fix(super_refs, super_refs_end, cls->isa, object_getClass(id(c)));
}
}
}
| magicpriest/darling-FC-edition | src/libobjcdarwin/new/class.cpp | C++ | gpl-3.0 | 3,116 |
/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/test/channel_transport/include/channel_transport.h"
#include <stdio.h>
#if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS)
#include "testing/gtest/include/gtest/gtest.h"
#endif
#include "webrtc/test/channel_transport/udp_transport.h"
#include "webrtc/video_engine/include/vie_network.h"
#include "webrtc/video_engine/vie_defines.h"
#include "webrtc/voice_engine/include/voe_network.h"
#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
#undef NDEBUG
#include <assert.h>
#endif
namespace webrtc {
namespace test {
VoiceChannelTransport::VoiceChannelTransport(VoENetwork* voe_network,
int channel)
: channel_(channel),
voe_network_(voe_network) {
uint8_t socket_threads = 1;
socket_transport_ = UdpTransport::Create(channel, socket_threads);
int registered = voe_network_->RegisterExternalTransport(channel,
*socket_transport_);
#if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS)
EXPECT_EQ(0, registered);
#else
assert(registered == 0);
#endif
}
VoiceChannelTransport::~VoiceChannelTransport() {
voe_network_->DeRegisterExternalTransport(channel_);
UdpTransport::Destroy(socket_transport_);
}
void VoiceChannelTransport::IncomingRTPPacket(
const int8_t* incoming_rtp_packet,
const int32_t packet_length,
const char* /*from_ip*/,
const uint16_t /*from_port*/) {
voe_network_->ReceivedRTPPacket(channel_, incoming_rtp_packet, packet_length);
}
void VoiceChannelTransport::IncomingRTCPPacket(
const int8_t* incoming_rtcp_packet,
const int32_t packet_length,
const char* /*from_ip*/,
const uint16_t /*from_port*/) {
voe_network_->ReceivedRTCPPacket(channel_, incoming_rtcp_packet,
packet_length);
}
int VoiceChannelTransport::SetLocalReceiver(uint16_t rtp_port) {
int return_value = socket_transport_->InitializeReceiveSockets(this,
rtp_port);
if (return_value == 0) {
return socket_transport_->StartReceiving(kViENumReceiveSocketBuffers);
}
return return_value;
}
int VoiceChannelTransport::SetSendDestination(const char* ip_address,
uint16_t rtp_port) {
return socket_transport_->InitializeSendSockets(ip_address, rtp_port);
}
VideoChannelTransport::VideoChannelTransport(ViENetwork* vie_network,
int channel)
: channel_(channel),
vie_network_(vie_network) {
uint8_t socket_threads = 1;
socket_transport_ = UdpTransport::Create(channel, socket_threads);
int registered = vie_network_->RegisterSendTransport(channel,
*socket_transport_);
#if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS)
EXPECT_EQ(0, registered);
#else
assert(registered == 0);
#endif
}
VideoChannelTransport::~VideoChannelTransport() {
vie_network_->DeregisterSendTransport(channel_);
UdpTransport::Destroy(socket_transport_);
}
void VideoChannelTransport::IncomingRTPPacket(
const int8_t* incoming_rtp_packet,
const int32_t packet_length,
const char* /*from_ip*/,
const uint16_t /*from_port*/) {
vie_network_->ReceivedRTPPacket(
channel_, incoming_rtp_packet, packet_length, PacketTime());
}
void VideoChannelTransport::IncomingRTCPPacket(
const int8_t* incoming_rtcp_packet,
const int32_t packet_length,
const char* /*from_ip*/,
const uint16_t /*from_port*/) {
vie_network_->ReceivedRTCPPacket(channel_, incoming_rtcp_packet,
packet_length);
}
int VideoChannelTransport::SetLocalReceiver(uint16_t rtp_port) {
int return_value = socket_transport_->InitializeReceiveSockets(this,
rtp_port);
if (return_value == 0) {
return socket_transport_->StartReceiving(kViENumReceiveSocketBuffers);
}
return return_value;
}
int VideoChannelTransport::SetSendDestination(const char* ip_address,
uint16_t rtp_port) {
return socket_transport_->InitializeSendSockets(ip_address, rtp_port);
}
} // namespace test
} // namespace webrtc
| liyouchang/webrtc-qt | webrtc/test/channel_transport/channel_transport.cc | C++ | gpl-3.0 | 4,688 |
// ***************************************************************** -*- C++ -*-
/*
* Copyright (C) 2004-2017 Andreas Huggel <ahuggel@gmx.net>
*
* This program is part of the Exiv2 distribution.
*
* 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, 5th Floor, Boston, MA 02110-1301 USA.
*/
/*!
@file xmp.hpp
@brief Encoding and decoding of XMP data
@version $Rev: 3090 $
@author Andreas Huggel (ahu)
<a href="mailto:ahuggel@gmx.net">ahuggel@gmx.net</a>
@date 13-Jul-07, ahu: created
*/
#ifndef XMP_HPP_
#define XMP_HPP_
// *****************************************************************************
// included header files
#include "metadatum.hpp"
#include "properties.hpp"
#include "value.hpp"
#include "types.hpp"
#include "datasets.hpp"
#include "properties.hpp"
// + standard includes
#include <string>
#include <vector>
// *****************************************************************************
// namespace extensions
namespace Exiv2 {
// *****************************************************************************
// class declarations
class ExifData;
// *****************************************************************************
// class definitions
/*!
@brief Information related to an XMP property. An XMP metadatum consists
of an XmpKey and a Value and provides methods to manipulate these.
*/
class EXIV2API Xmpdatum : public Metadatum {
public:
//! @name Creators
//@{
/*!
@brief Constructor for new tags created by an application. The
%Xmpdatum is created from a key / value pair. %Xmpdatum
copies (clones) the value if one is provided. Alternatively, a
program can create an 'empty' %Xmpdatum with only a key and
set the value using setValue().
@param key The key of the %Xmpdatum.
@param pValue Pointer to a %Xmpdatum value.
@throw Error if the key cannot be parsed and converted
to a known schema namespace prefix and property name.
*/
explicit Xmpdatum(const XmpKey& key,
const Value* pValue =0);
//! Copy constructor
Xmpdatum(const Xmpdatum& rhs);
//! Destructor
virtual ~Xmpdatum();
//@}
//! @name Manipulators
//@{
//! Assignment operator
Xmpdatum& operator=(const Xmpdatum& rhs);
/*!
@brief Assign std::string \em value to the %Xmpdatum.
Calls setValue(const std::string&).
*/
Xmpdatum& operator=(const std::string& value);
/*!
@brief Assign const char* \em value to the %Xmpdatum.
Calls operator=(const std::string&).
*/
Xmpdatum& operator=(const char* value);
/*!
@brief Assign a boolean \em value to the %Xmpdatum.
Translates the value to a string "true" or "false".
*/
Xmpdatum& operator=(const bool& value);
/*!
@brief Assign a \em value of any type with an output operator
to the %Xmpdatum. Calls operator=(const std::string&).
*/
template<typename T>
Xmpdatum& operator=(const T& value);
/*!
@brief Assign Value \em value to the %Xmpdatum.
Calls setValue(const Value*).
*/
Xmpdatum& operator=(const Value& value);
void setValue(const Value* pValue);
/*!
@brief Set the value to the string \em value. Uses Value::read(const
std::string&). If the %Xmpdatum does not have a Value yet,
then a %Value of the correct type for this %Xmpdatum is
created. If the key is unknown, a XmpTextValue is used as
default. Return 0 if the value was read successfully.
*/
int setValue(const std::string& value);
//@}
//! @name Accessors
//@{
//! Not implemented. Calling this method will raise an exception.
long copy(byte* buf, ByteOrder byteOrder) const;
std::ostream& write(std::ostream& os, const ExifData* pMetadata =0) const;
/*!
@brief Return the key of the Xmpdatum. The key is of the form
'<b>Xmp</b>.prefix.property'. Note however that the
key is not necessarily unique, i.e., an XmpData object may
contain multiple metadata with the same key.
*/
std::string key() const;
const char* familyName() const;
//! Return the (preferred) schema namespace prefix.
std::string groupName() const;
//! Return the property name.
std::string tagName() const;
std::string tagLabel() const;
//! Properties don't have a tag number. Return 0.
uint16_t tag() const;
TypeId typeId() const;
const char* typeName() const;
// Todo: Remove this method from the baseclass
//! The Exif typeSize doesn't make sense here. Return 0.
long typeSize() const;
long count() const;
long size() const;
std::string toString() const;
std::string toString(long n) const;
long toLong(long n =0) const;
float toFloat(long n =0) const;
Rational toRational(long n =0) const;
Value::AutoPtr getValue() const;
const Value& value() const;
//@}
private:
// Pimpl idiom
struct Impl;
Impl* p_;
}; // class Xmpdatum
//! Container type to hold all metadata
typedef std::vector<Xmpdatum> XmpMetadata;
/*!
@brief A container for XMP data. This is a top-level class of
the %Exiv2 library.
Provide high-level access to the XMP data of an image:
- read XMP information from an XML block
- access metadata through keys and standard C++ iterators
- add, modify and delete metadata
- serialize XMP data to an XML block
*/
class EXIV2API XmpData {
public:
//! XmpMetadata iterator type
typedef XmpMetadata::iterator iterator;
//! XmpMetadata const iterator type
typedef XmpMetadata::const_iterator const_iterator;
//! @name Manipulators
//@{
/*!
@brief Returns a reference to the %Xmpdatum that is associated with a
particular \em key. If %XmpData does not already contain such
an %Xmpdatum, operator[] adds object \em Xmpdatum(key).
@note Since operator[] might insert a new element, it can't be a const
member function.
*/
Xmpdatum& operator[](const std::string& key);
/*!
@brief Add an %Xmpdatum from the supplied key and value pair. This
method copies (clones) the value.
@return 0 if successful.
*/
int add(const XmpKey& key, const Value* value);
/*!
@brief Add a copy of the Xmpdatum to the XMP metadata.
@return 0 if successful.
*/
int add(const Xmpdatum& xmpdatum);
/*!
@brief Delete the Xmpdatum at iterator position pos, return the
position of the next Xmpdatum.
@note Iterators into the metadata, including pos, are potentially
invalidated by this call.
*/
iterator erase(iterator pos);
//! Delete all Xmpdatum instances resulting in an empty container.
void clear();
//! Sort metadata by key
void sortByKey();
//! Begin of the metadata
iterator begin();
//! End of the metadata
iterator end();
/*!
@brief Find the first Xmpdatum with the given key, return an iterator
to it.
*/
iterator findKey(const XmpKey& key);
//@}
//! @name Accessors
//@{
//! Begin of the metadata
const_iterator begin() const;
//! End of the metadata
const_iterator end() const;
/*!
@brief Find the first Xmpdatum with the given key, return a const
iterator to it.
*/
const_iterator findKey(const XmpKey& key) const;
//! Return true if there is no XMP metadata
bool empty() const;
//! Get the number of metadata entries
long count() const;
//! are we to use the packet?
bool usePacket() const { return usePacket_; } ;
//! set usePacket_
bool usePacket(bool b) { bool r = usePacket_; usePacket_=b ; return r; };
//! setPacket
void setPacket(const std::string& xmpPacket) { xmpPacket_ = xmpPacket ; usePacket(false); };
// ! getPacket
const std::string& xmpPacket() const { return xmpPacket_ ; };
//@}
private:
// DATA
XmpMetadata xmpMetadata_;
std::string xmpPacket_ ;
bool usePacket_ ;
}; // class XmpData
/*!
@brief Stateless parser class for XMP packets. Images use this
class to parse and serialize XMP packets. The parser uses
the XMP toolkit to do the job.
*/
class EXIV2API XmpParser {
public:
//! Options to control the format of the serialized XMP packet.
enum XmpFormatFlags {
omitPacketWrapper = 0x0010UL, //!< Omit the XML packet wrapper.
readOnlyPacket = 0x0020UL, //!< Default is a writeable packet.
useCompactFormat = 0x0040UL, //!< Use a compact form of RDF.
includeThumbnailPad = 0x0100UL, //!< Include a padding allowance for a thumbnail image.
exactPacketLength = 0x0200UL, //!< The padding parameter is the overall packet length.
writeAliasComments = 0x0400UL, //!< Show aliases as XML comments.
omitAllFormatting = 0x0800UL //!< Omit all formatting whitespace.
};
/*!
@brief Decode XMP metadata from an XMP packet \em xmpPacket into
\em xmpData. The format of the XMP packet must follow the
XMP specification. This method clears any previous contents
of \em xmpData.
@param xmpData Container for the decoded XMP properties
@param xmpPacket The raw XMP packet to decode
@return 0 if successful;<BR>
1 if XMP support has not been compiled-in;<BR>
2 if the XMP toolkit failed to initialize;<BR>
3 if the XMP toolkit failed and raised an XMP_Error
*/
static int decode( XmpData& xmpData,
const std::string& xmpPacket);
/*!
@brief Encode (serialize) XMP metadata from \em xmpData into a
string xmpPacket. The XMP packet returned in the string
follows the XMP specification. This method only modifies
\em xmpPacket if the operations succeeds (return code 0).
@param xmpPacket Reference to a string to hold the encoded XMP
packet.
@param xmpData XMP properties to encode.
@param formatFlags Flags that control the format of the XMP packet,
see enum XmpFormatFlags.
@param padding Padding length.
@return 0 if successful;<BR>
1 if XMP support has not been compiled-in;<BR>
2 if the XMP toolkit failed to initialize;<BR>
3 if the XMP toolkit failed and raised an XMP_Error
*/
static int encode( std::string& xmpPacket,
const XmpData& xmpData,
uint16_t formatFlags =useCompactFormat,
uint32_t padding =0);
/*!
@brief Lock/unlock function type
A function of this type can be passed to initialize() to
make subsequent registration of XMP namespaces thread-safe.
See the initialize() function for more information.
@param pLockData Pointer to the pLockData passed to initialize()
@param lockUnlock Indicates whether to lock (true) or unlock (false)
*/
typedef void (*XmpLockFct)(void* pLockData, bool lockUnlock);
/*!
@brief Initialize the XMP Toolkit.
Calling this method is usually not needed, as encode() and
decode() will initialize the XMP Toolkit if necessary.
The function takes optional pointers to a callback function
\em xmpLockFct and related data \em pLockData that the parser
uses when XMP namespaces are subsequently registered.
The initialize() function itself still is not thread-safe and
needs to be called in a thread-safe manner (e.g., on program
startup), but if used with suitable additional locking
parameters, any subsequent registration of namespaces will be
thread-safe.
Example usage on Windows using a critical section:
@code
void main()
{
struct XmpLock
{
CRITICAL_SECTION cs;
XmpLock() { InitializeCriticalSection(&cs); }
~XmpLock() { DeleteCriticalSection(&cs); }
static void LockUnlock(void* pData, bool fLock)
{
XmpLock* pThis = reinterpret_cast<XmpLock*>(pData);
if (pThis)
{
(fLock) ? EnterCriticalSection(&pThis->cs)
: LeaveCriticalSection(&pThis->cs);
}
}
} xmpLock;
// Pass the locking mechanism to the XMP parser on initialization.
// Note however that this call itself is still not thread-safe.
Exiv2::XmpParser::initialize(XmpLock::LockUnlock, &xmpLock);
// Program continues here, subsequent registrations of XMP
// namespaces are serialized using xmpLock.
}
@endcode
@return True if the initialization was successful, else false.
*/
static bool initialize(XmpParser::XmpLockFct xmpLockFct =0, void* pLockData =0);
/*!
@brief Terminate the XMP Toolkit and unregister custom namespaces.
Call this method when the XmpParser is no longer needed to
allow the XMP Toolkit to cleanly shutdown.
*/
static void terminate();
private:
/*!
@brief Register a namespace with the XMP Toolkit.
*/
static void registerNs(const std::string& ns,
const std::string& prefix);
/*!
@brief Delete a namespace from the XMP Toolkit.
XmpProperties::unregisterNs calls this to synchronize namespaces.
*/
static void unregisterNs(const std::string& ns);
/*!
@brief Get namespaces registered with XMPsdk
*/
static void registeredNamespaces(Exiv2::Dictionary&);
// DATA
static bool initialized_; //! Indicates if the XMP Toolkit has been initialized
static XmpLockFct xmpLockFct_;
static void* pLockData_;
friend class XmpProperties; // permit XmpProperties -> registerNs() and registeredNamespaces()
}; // class XmpParser
// *****************************************************************************
// free functions, template and inline definitions
inline Xmpdatum& Xmpdatum::operator=(const char* value)
{
return Xmpdatum::operator=(std::string(value));
}
inline Xmpdatum& Xmpdatum::operator=(const bool& value)
{
return operator=(value ? "True" : "False");
}
template<typename T>
Xmpdatum& Xmpdatum::operator=(const T& value)
{
setValue(Exiv2::toString(value));
return *this;
}
} // namespace Exiv2
#endif // #ifndef XMP_HPP_
| aferrero2707/PhotoFlow | src/external/exiv2/include/exiv2/xmp.hpp | C++ | gpl-3.0 | 16,837 |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import uuid
import base64
import os
from django.contrib.gis.db import models
from treemap.models import User
class APIAccessCredential(models.Model):
access_key = models.CharField(max_length=100, null=False, blank=False)
secret_key = models.CharField(max_length=256, null=False, blank=False)
# If a user is specified then this credential
# is always authorized as the given user
#
# If user is None this credential can access
# any user's data if that user's username
# and password are also provided
user = models.ForeignKey(User, null=True)
enabled = models.BooleanField(default=True)
@classmethod
def create(clz, user=None):
secret_key = base64.urlsafe_b64encode(os.urandom(64))
access_key = base64.urlsafe_b64encode(uuid.uuid4().bytes)\
.replace('=', '')
return APIAccessCredential.objects.create(
user=user, access_key=access_key, secret_key=secret_key)
| ctaylo37/OTM2 | opentreemap/api/models.py | Python | gpl-3.0 | 1,113 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-08-14 18:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sessao', '0009_auto_20170619_1441'),
]
operations = [
migrations.AddField(
model_name='tiporesultadovotacao',
name='natureza',
field=models.CharField(choices=[('A', 'Aprovado'), ('R', 'Rejeitado')], max_length=100, null=True, verbose_name='Natureza do Tipo'),
),
migrations.AlterField(
model_name='tiporesultadovotacao',
name='nome',
field=models.CharField(max_length=100, verbose_name='Nome do Tipo'),
),
]
| cmjatai/cmj | sapl/sessao/migrations/0010_auto_20170814_1804.py | Python | gpl-3.0 | 753 |
package com.nutiteq.utils;
import com.nutiteq.components.Envelope;
import com.nutiteq.components.MapPos;
import com.nutiteq.projections.Projection;
public class TileUtils {
private static final double TILESIZE = 256;
private static final double initialResolution = 2.0f * Math.PI * 6378137.0f
/ TILESIZE;
private static final double originShift = 2.0f * Math.PI * 6378137.0f / 2.0f;
// following is from
// http://code.google.com/p/gmap-tile-generator/source/browse/trunk/gmaps-tile-creator/src/gov/ca/maps/tile/geom/GlobalMercator.java?r=15
/**
* Returns tile for given Mercator coordinates
*
* @return
*/
public static MapPos MetersToTile(MapPos mp, int zoom) {
int[] p = MetersToPixels(mp.x, mp.y, zoom);
return PixelsToTile(p[0], p[1], zoom);
}
/**
* Returns a tile covering region in given pixel coordinates
*
* @param px
* @param py
* @param zoom
* @return
*/
public static MapPos PixelsToTile(int px, int py, int zoom) {
int tx = (int) Math.ceil(px / ((double) TILESIZE) - 1);
int ty = (int) Math.ceil(py / ((double) TILESIZE) - 1);
return new MapPos(tx, (1<<(zoom))-1-ty);
}
/**
* Converts EPSG:900913 to pyramid pixel coordinates in given zoom level
*
* @param mx
* @param my
* @param zoom
* @return
*/
public static int[] MetersToPixels(double mx, double my, int zoom) {
double res = Resolution(zoom);
int px = (int) Math.round((mx + originShift) / res);
int py = (int) Math.round((my + originShift) / res);
return new int[] { px, py };
}
/**
* Resolution (meters/pixel) for given zoom level (measured at Equator)
*
* @return
*/
public static double Resolution(int zoom) {
// return (2 * Math.PI * 6378137) / (this.tileSize * 2**zoom)
return initialResolution / Math.pow(2, zoom);
}
/**
* Returns bounds of the given tile in EPSG:900913 (EPSG:3857) coordinates
*
* @param tx
* @param ty (bottom-top)
* @param zoom
* @return
* @deprecated use TileBounds with projection instead
*/
public static Envelope TileBounds(int tx, int ty, int zoom) {
double[] min = PixelsToMeters(tx * TILESIZE, ty * TILESIZE, zoom);
double minx = min[0], miny = min[1];
double[] max = PixelsToMeters((tx + 1) * TILESIZE, (ty + 1) * TILESIZE,
zoom);
double maxx = max[0], maxy = max[1];
return new Envelope( minx, maxx, miny, maxy);
}
/**
* Get bounds of tile
* @param tx tile x (left-right)
* @param ty tile y (top-bottom)
* @param zoom zoom (0 = world)
* @param proj
* @return bounds, in given projection
*/
public static Envelope TileBounds(int tx, int ty, int zoom, Projection proj) {
double originShift = (proj.getBounds().right-proj.getBounds().left) / 2.0;
double res = (originShift * 2.0) / (TILESIZE * (double) (1<<(zoom))); // 1<<(zoom) is same as power(2;zoom)
double minx = ((double) tx) * TILESIZE * res - originShift;
double miny = (((double) (1<<(zoom))-1-ty) * TILESIZE * res) - originShift;
double maxx = (double)(tx+1) * TILESIZE * res - originShift;
double maxy = ((double)( (1<<(zoom))-1-ty + 1) * TILESIZE * res) - originShift;
return new Envelope( minx, maxx, miny, maxy);
}
/**
* Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84
* Datum
*
* @return
*/
public static double[] MetersToLatLon(double mx, double my) {
double lon = (mx / originShift) * 180.0;
double lat = (my / originShift) * 180.0;
lat = 180
/ Math.PI
* (2 * Math.atan(Math.exp(lat * Math.PI / 180.0)) - Math.PI / 2.0);
return new double[] { lat, lon };
}
/**
* Converts pixel coordinates in given zoom level of pyramid to EPSG:900913
*
* @return
*/
public static double[] PixelsToMeters(double px, double py, int zoom) {
double res = Resolution(zoom);
double mx = px * res - originShift;
double my = originShift - (py * res);
return new double[] { mx, my };
}
}
| FAIMS/faims-android | faimsandroidapp/src/main/java/com/nutiteq/utils/TileUtils.java | Java | gpl-3.0 | 4,474 |
// RUN: %clang_cc1 -std=c++11 -triple x86_64-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix=LINUX
// RUN: %clang_cc1 -std=c++11 -triple x86_64-windows-pc -emit-llvm %s -o - | FileCheck %s --check-prefix=WINDOWS
int __attribute__((target("sse4.2"))) foo_overload(int) { return 0; }
int __attribute__((target("arch=sandybridge"))) foo_overload(int);
int __attribute__((target("arch=ivybridge"))) foo_overload(int) {return 1;}
int __attribute__((target("default"))) foo_overload(int) { return 2; }
int __attribute__((target("sse4.2"))) foo_overload(void) { return 0; }
int __attribute__((target("arch=sandybridge"))) foo_overload(void);
int __attribute__((target("arch=ivybridge"))) foo_overload(void) {return 1;}
int __attribute__((target("default"))) foo_overload(void) { return 2; }
int bar2() {
return foo_overload() + foo_overload(1);
}
// LINUX: @_Z12foo_overloadv.ifunc = weak_odr ifunc i32 (), i32 ()* ()* @_Z12foo_overloadv.resolver
// LINUX: @_Z12foo_overloadi.ifunc = weak_odr ifunc i32 (i32), i32 (i32)* ()* @_Z12foo_overloadi.resolver
// LINUX: define{{.*}} i32 @_Z12foo_overloadi.sse4.2(i32 %0)
// LINUX: ret i32 0
// LINUX: define{{.*}} i32 @_Z12foo_overloadi.arch_ivybridge(i32 %0)
// LINUX: ret i32 1
// LINUX: define{{.*}} i32 @_Z12foo_overloadi(i32 %0)
// LINUX: ret i32 2
// LINUX: define{{.*}} i32 @_Z12foo_overloadv.sse4.2()
// LINUX: ret i32 0
// LINUX: define{{.*}} i32 @_Z12foo_overloadv.arch_ivybridge()
// LINUX: ret i32 1
// LINUX: define{{.*}} i32 @_Z12foo_overloadv()
// LINUX: ret i32 2
// WINDOWS: define dso_local i32 @"?foo_overload@@YAHH@Z.sse4.2"(i32 %0)
// WINDOWS: ret i32 0
// WINDOWS: define dso_local i32 @"?foo_overload@@YAHH@Z.arch_ivybridge"(i32 %0)
// WINDOWS: ret i32 1
// WINDOWS: define dso_local i32 @"?foo_overload@@YAHH@Z"(i32 %0)
// WINDOWS: ret i32 2
// WINDOWS: define dso_local i32 @"?foo_overload@@YAHXZ.sse4.2"()
// WINDOWS: ret i32 0
// WINDOWS: define dso_local i32 @"?foo_overload@@YAHXZ.arch_ivybridge"()
// WINDOWS: ret i32 1
// WINDOWS: define dso_local i32 @"?foo_overload@@YAHXZ"()
// WINDOWS: ret i32 2
// LINUX: define{{.*}} i32 @_Z4bar2v()
// LINUX: call i32 @_Z12foo_overloadv.ifunc()
// LINUX: call i32 @_Z12foo_overloadi.ifunc(i32 1)
// WINDOWS: define dso_local i32 @"?bar2@@YAHXZ"()
// WINDOWS: call i32 @"?foo_overload@@YAHXZ.resolver"()
// WINDOWS: call i32 @"?foo_overload@@YAHH@Z.resolver"(i32 1)
// LINUX: define weak_odr i32 ()* @_Z12foo_overloadv.resolver() comdat
// LINUX: ret i32 ()* @_Z12foo_overloadv.arch_sandybridge
// LINUX: ret i32 ()* @_Z12foo_overloadv.arch_ivybridge
// LINUX: ret i32 ()* @_Z12foo_overloadv.sse4.2
// LINUX: ret i32 ()* @_Z12foo_overloadv
// WINDOWS: define weak_odr dso_local i32 @"?foo_overload@@YAHXZ.resolver"() comdat
// WINDOWS: call i32 @"?foo_overload@@YAHXZ.arch_sandybridge"
// WINDOWS: call i32 @"?foo_overload@@YAHXZ.arch_ivybridge"
// WINDOWS: call i32 @"?foo_overload@@YAHXZ.sse4.2"
// WINDOWS: call i32 @"?foo_overload@@YAHXZ"
// LINUX: define weak_odr i32 (i32)* @_Z12foo_overloadi.resolver() comdat
// LINUX: ret i32 (i32)* @_Z12foo_overloadi.arch_sandybridge
// LINUX: ret i32 (i32)* @_Z12foo_overloadi.arch_ivybridge
// LINUX: ret i32 (i32)* @_Z12foo_overloadi.sse4.2
// LINUX: ret i32 (i32)* @_Z12foo_overloadi
// WINDOWS: define weak_odr dso_local i32 @"?foo_overload@@YAHH@Z.resolver"(i32 %0) comdat
// WINDOWS: call i32 @"?foo_overload@@YAHH@Z.arch_sandybridge"
// WINDOWS: call i32 @"?foo_overload@@YAHH@Z.arch_ivybridge"
// WINDOWS: call i32 @"?foo_overload@@YAHH@Z.sse4.2"
// WINDOWS: call i32 @"?foo_overload@@YAHH@Z"
// LINUX: declare i32 @_Z12foo_overloadv.arch_sandybridge()
// LINUX: declare i32 @_Z12foo_overloadi.arch_sandybridge(i32)
// WINDOWS: declare dso_local i32 @"?foo_overload@@YAHXZ.arch_sandybridge"()
// WINDOWS: declare dso_local i32 @"?foo_overload@@YAHH@Z.arch_sandybridge"(i32)
| sabel83/metashell | 3rd/templight/clang/test/CodeGenCXX/attr-target-mv-overloads.cpp | C++ | gpl-3.0 | 3,859 |
/*
* #%L
* GeoWE Project
* %%
* Copyright (C) 2015 - 2016 GeoWE.org
* %%
* This file is part of GeoWE.org.
*
* GeoWE 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.
*
* GeoWE 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 GeoWE. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.geowe.client.local.main.tool.project;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import org.geowe.client.local.ImageProvider;
import org.geowe.client.local.main.tool.ButtonTool;
import org.geowe.client.local.messages.UIMessages;
import org.geowe.client.local.ui.ProgressBarDialog;
import org.jboss.errai.common.client.api.tasks.ClientTaskManager;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.DOM;
import com.google.inject.Inject;
import com.sencha.gxt.core.client.Style.Side;
import com.sencha.gxt.widget.core.client.Dialog.PredefinedButton;
import com.sencha.gxt.widget.core.client.box.AlertMessageBox;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler;
import com.sencha.gxt.widget.core.client.event.SubmitCompleteEvent;
import com.sencha.gxt.widget.core.client.event.SubmitCompleteEvent.SubmitCompleteHandler;
/**
* Responsable de cargar la configuración de un proyecto de geowe
*
* @author jose@geowe.org
* @since 11-02-2017
* @author rafa@geowe.org
* fix issue 303
*
*/
@ApplicationScoped
public class OpenProjectTool extends ButtonTool {
private ProgressBarDialog autoMessageBox;
@Inject
private ClientTaskManager taskManager;
@Inject
private OpenProjectDialog openProjectDialog;
@Inject
private ProjectLoader projectLoader;
@Inject
private URLProjectLoader urlProjectLoader;
public OpenProjectTool() {
super(UIMessages.INSTANCE.openProject(), ImageProvider.INSTANCE
.openProject24());
setToolTipConfig(createTooltipConfig(UIMessages.INSTANCE.openProject(),
UIMessages.INSTANCE.openProjectToolTipText(), Side.LEFT));
}
@Override
protected void onRelease() {
openProjectDialog.clear();
openProjectDialog.show();
}
@PostConstruct
private void initialize() {
addDialogListener();
addCloseButtonHandler();
openProjectDialog.getUploadPanel().addSubmitCompleteHandler(new SubmitCompleteHandler() {
public void onSubmitComplete(final SubmitCompleteEvent event) {
final Element label = DOM.createLabel();
label.setInnerHTML(event.getResults());
final String jsonProject = label.getInnerText();
openProjectDialog.hide();
if (hasError(jsonProject)) {
autoMessageBox.hide();
showAlert("Error: " + jsonProject);
return;
}
projectLoader.load(jsonProject);
autoMessageBox.hide();
}
private boolean hasError(final String contentFile) {
return contentFile.startsWith("413")
|| contentFile.startsWith("500")
|| contentFile.startsWith("204")
|| contentFile.startsWith("406");
}
});
}
private void showAlert(final String errorMsg) {
AlertMessageBox messageBox = new AlertMessageBox(
UIMessages.INSTANCE.warning(), errorMsg);
messageBox.show();
}
private void addDialogListener() {
openProjectDialog.getButton(PredefinedButton.OK).addSelectHandler(new SelectHandler() {
@Override
public void onSelect(final SelectEvent event) {
taskManager.execute(new Runnable() {
@Override
public void run() {
if (openProjectDialog.getActiveTab().equals(UIMessages.INSTANCE.file())) {
if(openProjectDialog.isFileFieldCorrectFilled()){
autoMessageBox = new ProgressBarDialog(false,
UIMessages.INSTANCE.processing());
autoMessageBox.show();
openProjectDialog.getUploadPanel().submit();
}else{
showAlert(UIMessages.INSTANCE.lrasterdAlertMessageBoxLabel(UIMessages.INSTANCE.file()));
}
}
if (openProjectDialog.getActiveTab().equals(UIMessages.INSTANCE.url())) {
if(openProjectDialog.isurlFieldCorrectFilled()){
urlProjectLoader.open(urlProjectLoader, openProjectDialog.getUrl());
openProjectDialog.hide();
}else{
showAlert(UIMessages.INSTANCE.lrasterdAlertMessageBoxLabel(UIMessages.INSTANCE.url()));
}
}
}
});
}
});
}
protected void addCloseButtonHandler() {
openProjectDialog.getButton(PredefinedButton.CANCEL).addSelectHandler(
new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
openProjectDialog.hide();
}
});
}
}
| geowe/geowe-core | src/main/java/org/geowe/client/local/main/tool/project/OpenProjectTool.java | Java | gpl-3.0 | 5,059 |
<?php
/**
* The template for displaying all WooCommerce pages.
*
* @package zerif-lite
*/
get_header(); ?>
<div class="clear"></div>
</header> <!-- / END HOME SECTION -->
<?php zerif_after_header_trigger(); ?>
<div id="content" class="site-content">
<div class="container">
<div class="content-left-wrap col-md-12">
<div id="primary" class="content-area">
<main id="main" class="site-main">
<?php woocommerce_content(); ?>
</main><!-- #main -->
</div><!-- #primary -->
</div><!-- .content-left-wrap -->
</div><!-- .container -->
<?php get_footer(); ?>
| Codeinwp/zerif-lite | woocommerce.php | PHP | gpl-3.0 | 594 |
namespace OmniXaml.Wpf
{
using System.Threading.Tasks;
using System.Windows;
using Services.Mvvm;
public class WpfWindow : Window, IView
{
public new Task ShowDialog()
{
return new Task(() => this.ShowDialog());
}
public void SetViewModel(object viewModel)
{
this.DataContext = viewModel;
}
}
} | grokys/OmniXAML | Source/OmniXaml.Wpf/WpfWindow.cs | C# | gpl-3.0 | 400 |
/*
* Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of the <ORGANIZATION> nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
*/
/*
* cci_log.cpp -
*/
#include <errno.h>
#include <stdarg.h>
#if defined(WINDOWS)
#include <winsock2.h>
#include <windows.h>
#include <time.h>
#include <direct.h>
#include <io.h>
#else
#include <sys/time.h>
#include <sys/stat.h>
#if !defined(AIX)
#include <sys/syscall.h>
#endif
#include <unistd.h>
#endif
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <list>
#include <sstream>
#include "cci_common.h"
#include "cci_mutex.h"
#include "cci_log.h"
static const int ONE_DAY = 86400;
static const int LOG_BUFFER_SIZE = 1024 * 20;
static const int LOG_ER_OPEN = -1;
static const long int LOG_FLUSH_SIZE = 1024 * 1024; /* byte */
static const long int LOG_FLUSH_USEC = 1 * 1000000; /* usec */
static const long int LOG_CHECK_FILE_INTERVAL_USEC = 10 * 1000000; /* usec */
static const char *cci_log_level_string[] =
{ "OFF", "ERROR", "WARN", "INFO", "DEBUG" };
struct _LoggerContext;
class _Logger;
class _LogAppender
{
public:
_LogAppender(const _LoggerContext &context);
virtual ~_LogAppender() {}
virtual void open() = 0;
virtual void close() = 0;
virtual void write(const char *msg) = 0;
virtual void flush() = 0;
protected:
const _LoggerContext &context;
};
class _LogAppenderBase : public _LogAppender
{
public:
_LogAppenderBase(const _LoggerContext &context);
virtual ~_LogAppenderBase();
virtual void open();
virtual void close();
virtual void write(const char *msg);
virtual void flush();
protected:
virtual void roll() = 0;
virtual bool isRolling() = 0;
std::string rename(const char *newPath, const char *postfix);
int getLogSizeKBytes();
std::string getCurrDate();
std::string getCurrDateTime();
void makeLogDir();
private:
void checkFileIsOpen();
protected:
std::ofstream out;
long int nextCheckTime;
};
class _PostFixAppender : public _LogAppenderBase
{
public:
_PostFixAppender(const _LoggerContext &context, CCI_LOG_POSTFIX postfix);
virtual ~_PostFixAppender() {}
virtual void open();
protected:
virtual void roll();
virtual bool isRolling();
private:
void checkFileIsOpen();
std::string getNewPath();
private:
CCI_LOG_POSTFIX postfix;
int prevDate;
};
class _MaxSizeLogAppender : public _LogAppenderBase
{
public:
_MaxSizeLogAppender(const _LoggerContext &context, int maxFileSizeKBytes,
int maxBackupCount);
virtual ~_MaxSizeLogAppender() {}
protected:
virtual void roll();
virtual bool isRolling();
private:
int maxFileSizeKBytes;
int maxBackupCount;
int currBackupCount;
std::list<std::string> backupList;
};
class _DailyLogAppender : public _LogAppenderBase
{
public:
_DailyLogAppender(const _LoggerContext &context);
virtual ~_DailyLogAppender() {}
protected:
virtual void roll();
virtual bool isRolling();
private:
int prevDate;
};
struct _LoggerContext
{
std::string path;
struct timeval now;
};
class _Logger
{
public:
_Logger(const char *path);
virtual ~_Logger();
void setLogLevel(CCI_LOG_LEVEL level);
void setUseDefaultPrefix(bool useDefaultPrefix);
void setUseDefaultNewLine(bool useDefaultNewLine);
void setForceFlush(bool isForceFlush);
void log(CCI_LOG_LEVEL level, const char *msg);
void changeMaxFileSizeAppender(int maxFileSizeKBytes, int maxBackupCount);
void changePostfixAppender(CCI_LOG_POSTFIX postfix);
public:
const char *getPath();
bool isWritable(CCI_LOG_LEVEL level);
private:
void write(const char *msg);
void logPrefix(CCI_LOG_LEVEL level);
private:
cci::_Mutex critical;
_LoggerContext context;
_LogAppender *logAppender;
CCI_LOG_LEVEL level;
bool useDefaultPrefix;
bool useDefaultNewLine;
bool isForceFlush;
int unflushedBytes;
unsigned long nextFlushTime;
};
_LogAppender::_LogAppender(const _LoggerContext &context) :
context(context)
{
}
_LogAppenderBase::_LogAppenderBase(const _LoggerContext &context) :
_LogAppender(context), nextCheckTime(0)
{
open();
}
_LogAppenderBase::~_LogAppenderBase()
{
close();
}
void _LogAppenderBase::open()
{
if (out.is_open())
{
return;
}
makeLogDir();
out.open(context.path.c_str(), std::fstream::out | std::fstream::app);
if (out.fail())
{
out.open(context.path.c_str(), std::fstream::out | std::fstream::app);
if (out.fail())
{
throw LOG_ER_OPEN;
}
}
}
void _LogAppenderBase::close()
{
if (!out.is_open())
{
return;
}
out.close();
}
void _LogAppenderBase::write(const char *msg)
{
checkFileIsOpen();
try
{
if (!out.is_open())
{
open();
}
if (this->isRolling())
{
this->roll();
}
out << msg;
}
catch (...)
{
}
}
void _LogAppenderBase::flush()
{
if (!out.is_open())
{
return;
}
out.flush();
}
std::string _LogAppenderBase::rename(const char *newPath, const char *postfix)
{
std::stringstream newPathStream;
newPathStream << newPath;
close();
if (access(newPath, F_OK) == 0 && postfix != NULL)
{
newPathStream << postfix;
}
int e = std::rename(context.path.c_str(), newPathStream.str().c_str());
if (e != 0)
{
}
try
{
open();
}
catch (...)
{
}
return newPathStream.str();
}
int _LogAppenderBase::getLogSizeKBytes()
{
if (!out.is_open())
{
return 0;
}
else
{
return out.tellp() / 1024;
}
}
std::string _LogAppenderBase::getCurrDate()
{
struct tm cal;
char buf[16];
time_t t = context.now.tv_sec;
localtime_r(&t, &cal);
cal.tm_year += 1900;
cal.tm_mon += 1;
snprintf(buf, 16, "%d-%02d-%02d", cal.tm_year, cal.tm_mon, cal.tm_mday);
return buf;
}
std::string _LogAppenderBase::getCurrDateTime()
{
struct tm cal;
char buf[16];
time_t t = context.now.tv_sec;
localtime_r(&t, &cal);
cal.tm_year += 1900;
cal.tm_mon += 1;
snprintf(buf, 16, "%d%02d%02d%02d%02d%02d", cal.tm_year, cal.tm_mon,
cal.tm_mday, cal.tm_hour, cal.tm_min, cal.tm_sec);
return buf;
}
void _LogAppenderBase::makeLogDir()
{
const char *sep = "/\\";
char dir[FILENAME_MAX];
char *p = dir;
const char *q = context.path.c_str();
while (*q)
{
*p++ = *q;
*p = '\0';
if (*q == sep[0] || *q == sep[1])
{
mkdir(dir, 0755);
}
q++;
}
}
void _LogAppenderBase::checkFileIsOpen()
{
long int currentTime = context.now.tv_sec * 1000000 + context.now.tv_usec;
if (nextCheckTime == 0 || currentTime >= nextCheckTime)
{
if (access(context.path.c_str(), F_OK) != 0)
{
if (out.is_open())
{
out.close();
}
try
{
open();
}
catch (...)
{
}
}
nextCheckTime = currentTime + LOG_CHECK_FILE_INTERVAL_USEC;
}
}
_PostFixAppender::_PostFixAppender(const _LoggerContext &context,
CCI_LOG_POSTFIX postfix) :
_LogAppenderBase(context), postfix(postfix), prevDate(time(NULL) / ONE_DAY)
{
}
void _PostFixAppender::open()
{
if (out.is_open())
{
return;
}
makeLogDir();
std::string newPath = getNewPath();
out.open(newPath.c_str(), std::fstream::out | std::fstream::app);
if (out.fail())
{
out.open(newPath.c_str(), std::fstream::out | std::fstream::app);
if (out.fail())
{
throw LOG_ER_OPEN;
}
}
}
void _PostFixAppender::roll()
{
close();
try
{
open();
}
catch (...)
{
}
prevDate = context.now.tv_sec / ONE_DAY;
}
bool _PostFixAppender::isRolling()
{
if (postfix == CCI_LOG_POSTFIX_DATE)
{
int nowDay = context.now.tv_sec / ONE_DAY;
return prevDate < nowDay;
}
else
{
return false;
}
}
void _PostFixAppender::checkFileIsOpen()
{
long int currentTime = context.now.tv_sec * 1000000 + context.now.tv_usec;
if (nextCheckTime == 0 || currentTime >= nextCheckTime)
{
std::string newPath = getNewPath();
if (access(newPath.c_str(), F_OK) != 0)
{
if (out.is_open())
{
out.close();
}
try
{
open();
}
catch (...)
{
}
}
nextCheckTime = currentTime + LOG_CHECK_FILE_INTERVAL_USEC;
}
}
std::string _PostFixAppender::getNewPath()
{
std::stringstream newPath;
newPath << context.path;
if (postfix == CCI_LOG_POSTFIX_DATE)
{
newPath << "." << getCurrDate();
}
return newPath.str();
}
_MaxSizeLogAppender::_MaxSizeLogAppender(const _LoggerContext &context,
int maxFileSizeKBytes, int maxBackupCount) :
_LogAppenderBase(context), maxFileSizeKBytes(maxFileSizeKBytes),
maxBackupCount(maxBackupCount), currBackupCount(0)
{
}
void _MaxSizeLogAppender::roll()
{
std::stringstream newPath_stream;
newPath_stream << context.path << "." << getCurrDateTime();
std::stringstream postfix_stream;
postfix_stream << "(" << currBackupCount++ << ")";
std::string newPath = rename(newPath_stream.str().c_str(),
postfix_stream.str().c_str());
backupList.push_back(newPath);
if (backupList.size() > (size_t) maxBackupCount)
{
std::string remove_path = backupList.front();
backupList.pop_front();
int e = remove(remove_path.c_str());
if (e != 0)
{
perror("remove");
}
}
}
bool _MaxSizeLogAppender::isRolling()
{
return getLogSizeKBytes() > maxFileSizeKBytes;
}
_DailyLogAppender::_DailyLogAppender(const _LoggerContext &context) :
_LogAppenderBase(context), prevDate(time(NULL) / ONE_DAY)
{
}
void _DailyLogAppender::roll()
{
prevDate = context.now.tv_sec / ONE_DAY;
std::stringstream newPathStream;
newPathStream << context.path << "." << getCurrDate();
rename(newPathStream.str().c_str(), NULL);
}
bool _DailyLogAppender::isRolling()
{
int nowDay = context.now.tv_sec / ONE_DAY;
return prevDate < nowDay;
}
_Logger::_Logger(const char *path) :
logAppender(NULL), level(CCI_LOG_LEVEL_INFO), useDefaultPrefix(true),
useDefaultNewLine(true), isForceFlush(true), unflushedBytes(0),
nextFlushTime(0)
{
context.path = path;
gettimeofday(&context.now, NULL);
nextFlushTime = context.now.tv_usec + LOG_FLUSH_USEC;
logAppender = new _DailyLogAppender(context);
}
_Logger::~_Logger()
{
cci::_MutexAutolock lock(&critical);
if (logAppender != NULL)
{
delete logAppender;
}
}
void _Logger::setLogLevel(CCI_LOG_LEVEL level)
{
cci::_MutexAutolock lock(&critical);
this->level = level;
}
void _Logger::setUseDefaultPrefix(bool useDefaultPrefix)
{
cci::_MutexAutolock lock(&critical);
this->useDefaultPrefix = useDefaultPrefix;
}
void _Logger::setUseDefaultNewLine(bool useDefaultNewLine)
{
cci::_MutexAutolock lock(&critical);
this->useDefaultNewLine = useDefaultNewLine;
}
void _Logger::setForceFlush(bool isForceFlush)
{
cci::_MutexAutolock lock(&critical);
this->isForceFlush = isForceFlush;
}
void _Logger::log(CCI_LOG_LEVEL level, const char *msg)
{
cci::_MutexAutolock lock(&critical);
gettimeofday(&context.now, NULL);
if (useDefaultPrefix)
{
logPrefix(level);
}
write(msg);
if (useDefaultNewLine)
{
write("\n");
}
}
void _Logger::changeMaxFileSizeAppender(int maxFileSizeKBytes, int maxBackupCount)
{
cci::_MutexAutolock lock(&critical);
if (this->logAppender != NULL)
{
delete this->logAppender;
}
this->logAppender = new _MaxSizeLogAppender(context, maxFileSizeKBytes,
maxBackupCount);
}
void _Logger::changePostfixAppender(CCI_LOG_POSTFIX postfix)
{
cci::_MutexAutolock lock(&critical);
if (this->logAppender != NULL)
{
delete this->logAppender;
}
if (postfix == CCI_LOG_POSTFIX_NONE)
{
this->logAppender = new _DailyLogAppender(context);
}
else
{
this->logAppender = new _PostFixAppender(context, postfix);
}
}
const char *_Logger::getPath()
{
cci::_MutexAutolock lock(&critical);
return context.path.c_str();
}
bool _Logger::isWritable(CCI_LOG_LEVEL level)
{
cci::_MutexAutolock lock(&critical);
return this->level >= level;
}
void _Logger::write(const char *msg)
{
logAppender->write(msg);
unflushedBytes += strlen(msg);
if (isForceFlush || unflushedBytes >= LOG_FLUSH_SIZE
|| nextFlushTime >= (unsigned long) context.now.tv_usec)
{
logAppender->flush();
unflushedBytes = 0;
nextFlushTime = context.now.tv_usec + LOG_FLUSH_USEC;
}
}
void _Logger::logPrefix(CCI_LOG_LEVEL level)
{
struct tm cal;
time_t t;
t = context.now.tv_sec;
localtime_r((const time_t *) &t, &cal);
cal.tm_year += 1900;
cal.tm_mon += 1;
char buf[128];
unsigned long tid = gettid();
snprintf(buf, 128, "%d-%02d-%02d %02d:%02d:%02d.%03d [TID:%lu] [%5s]",
cal.tm_year, cal.tm_mon, cal.tm_mday, cal.tm_hour, cal.tm_min,
cal.tm_sec, (int)(context.now.tv_usec / 1000), tid,
cci_log_level_string[level]);
write(buf);
}
typedef std::pair<_Logger *, int> _LoggerReference;
typedef std::map<std::string, _LoggerReference> _LoggerMap;
class _LoggerManager
{
public:
_LoggerManager() {}
virtual ~_LoggerManager() {}
_Logger *getLogger(const char *path);
void removeLogger(const char *path);
void clearLogger();
private:
cci::_Mutex critical;
_LoggerMap map;
};
_Logger *_LoggerManager::getLogger(const char *path)
{
cci::_MutexAutolock lock(&critical);
_LoggerMap::iterator it = map.find(path);
if (it == map.end())
{
try
{
_Logger *logger = new _Logger(path);
map[path] = _LoggerReference(logger, 1);
return logger;
}
catch (...)
{
return NULL;
}
}
else
{
it->second.second++;
}
return it->second.first;
}
void _LoggerManager::removeLogger(const char *path)
{
cci::_MutexAutolock lock(&critical);
_LoggerMap::iterator it = map.find(path);
if (it != map.end())
{
it->second.second--;
if (it->second.second == 0)
{
delete it->second.first;
map.erase(it);
}
}
}
void _LoggerManager::clearLogger()
{
cci::_MutexAutolock lock(&critical);
_LoggerMap::iterator it = map.begin();
for (; it != map.end(); it++)
{
delete it->second.first;
}
map.clear();
}
static _LoggerManager loggerManager;
Logger cci_log_add(const char *path)
{
return loggerManager.getLogger(path);
}
Logger cci_log_get(const char *path)
{
return loggerManager.getLogger(path);
}
void cci_log_finalize(void)
{
loggerManager.clearLogger();
}
void cci_log_writef(CCI_LOG_LEVEL level, Logger logger, const char *format, ...)
{
_Logger *l = (_Logger *) logger;
if (l == NULL)
{
return;
}
char buf[LOG_BUFFER_SIZE];
va_list vl;
va_start(vl, format);
vsnprintf(buf, LOG_BUFFER_SIZE, format, vl);
va_end(vl);
l->log(level, buf);
}
void cci_log_write(CCI_LOG_LEVEL level, Logger logger, const char *log)
{
_Logger *l = (_Logger *) logger;
if (l == NULL)
{
return;
}
l->log(level, (char *) log);
}
void cci_log_remove(const char *path)
{
loggerManager.removeLogger(path);
}
void cci_log_set_level(Logger logger, CCI_LOG_LEVEL level)
{
_Logger *l = (_Logger *) logger;
if (l == NULL)
{
return;
}
l->setLogLevel(level);
}
bool cci_log_is_writable(Logger logger, CCI_LOG_LEVEL level)
{
_Logger *l = (_Logger *) logger;
if (l == NULL)
{
return false;
}
return l->isWritable(level);
}
void cci_log_set_force_flush(Logger logger, bool force_flush)
{
_Logger *l = (_Logger *) logger;
if (l == NULL)
{
return;
}
l->setForceFlush(force_flush);
}
void cci_log_use_default_newline(Logger logger, bool use_default_newline)
{
_Logger *l = (_Logger *) logger;
if (l == NULL)
{
return;
}
l->setUseDefaultNewLine(use_default_newline);
}
void cci_log_use_default_prefix(Logger logger, bool use_default_prefix)
{
_Logger *l = (_Logger *) logger;
if (l == NULL)
{
return;
}
l->setUseDefaultPrefix(use_default_prefix);
}
void cci_log_change_max_file_size_appender(Logger logger,
int maxFileSizeKBytes, int maxBackupCount)
{
_Logger *l = (_Logger *) logger;
if (l == NULL)
{
return;
}
try
{
l->changeMaxFileSizeAppender(maxFileSizeKBytes, maxBackupCount);
}
catch (...)
{
}
}
void cci_log_set_default_postfix(Logger logger, CCI_LOG_POSTFIX postfix)
{
_Logger *l = (_Logger *) logger;
if (l == NULL)
{
return;
}
l->changePostfixAppender(postfix);
}
| andrei14vl/cubrid | src/cci/cci_log.cpp | C++ | gpl-3.0 | 18,272 |
export function QuerySelectorAllIterate(el:HTMLElement, query:string) : HTMLElement[] {
let els :HTMLElement[] = [];
if ('function'==typeof el.matches) {
if (el.matches(query)) {
els.push(el);
}
} else if ('function'==typeof (el as any).matchesSelector) {
if ((el as any).matchesSelector(query)) {
els.push(el as HTMLElement);
}
}
let childSelector = el.querySelectorAll(query);
for (let i=0; i<childSelector.length; i++) {
els.push(childSelector.item(i) as HTMLElement);
}
return els;
}
| katmutua/electric-book-gui | src/ts/querySelectorAll-extensions.ts | TypeScript | gpl-3.0 | 514 |
package de.persosim.simulator.tlv;
import java.util.Comparator;
import de.persosim.simulator.utils.Utils;
/**
* This class implements a comparator for sorting TLV data objects in DER-TLV
* order. Sorting is performed based on the sorting of tags. In detail tags
* again are sorted based on their indicated class and tag number.
*
* !Attention!: Sorting is performed without checking either explicitly or
* implicitly for valid DER encoding of the objects to be sorted. Checks for
* valid DER encoding must be performed separately. Sorting however will also
* work correctly for valid BER but not DER encoded TLV data objects.
*
* @author slutters
*
*/
public class TlvDataObjectComparatorDer implements Comparator<TlvDataObject> {
@Override
public int compare(TlvDataObject tlvdo1, TlvDataObject tlvdo2) {
TlvTag tlvTag1;
TlvTag tlvTag2;
tlvTag1 = tlvdo1.getTlvTag();
tlvTag2 = tlvdo2.getTlvTag();
return compare(tlvTag1, tlvTag2);
}
/**
* Performs Comparator's sorting based on tags
* @param tlvTag1 tag 1
* @param tlvTag2 tag 2
* @return the Comparator's compare result
*/
private int compare(TlvTag tlvTag1, TlvTag tlvTag2) {
short class1 = Utils.maskUnsignedByteToShort(tlvTag1.getEncodedClass());
short class2 = Utils.maskUnsignedByteToShort(tlvTag2.getEncodedClass());
short classDiff = (short) (class1 - class2);
if(classDiff != 0) {
return classDiff;
} else{
return tlvTag1.getIndicatedTagNo() - tlvTag2.getIndicatedTagNo();
}
}
}
| PersoSim/de.persosim.simulator | de.persosim.simulator/src/de/persosim/simulator/tlv/TlvDataObjectComparatorDer.java | Java | gpl-3.0 | 1,516 |
<?php
/*
* ©2013 Croce Rossa Italiana
*/
paginaPrivata();
caricaSelettore();
controllaParametri(['id'], 'attivita.gestione&err');
$a = Attivita::id($_GET['id']);
paginaAttivita($a);
if (!$a->haPosizione()) {
redirect('attivita.localita&id=' . $a->id);
}
$del = $me->delegazioni(APP_ATTIVITA);
$comitati = $me->comitatiDelegazioni(APP_ATTIVITA);
$domini = $me->dominiDelegazioni(APP_ATTIVITA);
$g = GeoPolitica::daOid($a->comitato);
$visMinima = $a->visibilitaMinima($g);
?>
<form action="?p=attivita.modifica.ok" method="POST">
<input type="hidden" name="id" value="<?php echo $a->id; ?>" />
<div class="row-fluid">
<div class="span7">
<h2><i class="icon-flag muted"></i> Dettagli dell'attività</h2>
</div>
<div class="btn-group pull-right">
<button type="submit" name="azione" value="salva" class="btn btn-success btn-large">
<i class="icon-save"></i> Salva l'attività
</button>
</div>
</div>
<hr />
<div class="row-fluid">
<div class="span8">
<div class="alert alert-info">
<i class="icon-info-sign"></i>
Presta molta attenzione quando decidi <strong> quali volontari possono partecipare </strong>:</br>
<ul>
<li>Se selezioni <strong>Tutti i Volontari della Croce Rossa Italiana</strong> permetti a tutti gli
iscritti su Gaia di dare disponibilità per l'attività. </li>
<li>Se selezioni <strong>Pubblica</strong> permetti anche a chi <strong>non</strong> è Volontario
di partecipare. </li>
</ul>
</div>
<div class="form-horizontal">
<div class="control-group">
<label class="control-label" for="inputNome">Nome</label>
<div class="controls">
<input class="input-xlarge grassetto" value="<?php echo $a->nome; ?>" type="text" id="inputNome" name="inputNome" placeholder="Es.: Aggiungi un Posto a Tavola" required autofocus pattern=".{2,}" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputVisibilita">Quali volontari possono chiedere di partecipare?</label>
<div class="controls">
<select class="input-xxlarge" name="inputVisibilita">
<?php foreach ( $conf['att_vis'] as $num => $nom ) {
if ($num < $visMinima) { continue; }?>
<option value="<?php echo $num; ?>"
<?php if ( $a->visibilita == $num ) { ?>
selected="selected"
<?php } ?>
>
<?php echo $nom; ?>
</option>
<?php } ?>
</select>
<p class="text-info"><i class="icon-info-sign"></i> I volontari al di fuori di questa selezione non vedranno l'attività nel calendario.</p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputDescrizione">Descrizione ed informazioni per i volontari</label>
<div class="controls">
<textarea rows="10" class="input-xlarge conEditor" type="text" id="inputDescrizione" name="inputDescrizione"><?php echo $a->descrizione; ?></textarea>
</div>
</div>
</div>
</div>
<div class="span4">
<p>
<strong>Referente</strong><br />
<?php echo $a->referente()->nomeCompleto(); ?>
</p>
<p>
<strong>Organizzatore</strong><br />
<?php
echo $g->nomeCompleto(); ?>
</p>
<p>
<strong>Area d'intervento</strong><br />
<?php echo $a->area()->nomeCompleto(); ?>
</p>
<p>
<strong>Posizione geografica</strong><br />
<?php echo $a->luogo; ?><br />
<a href='?p=attivita.localita&id=<?= $a->id; ?>'>
<i class='icon-pencil'></i>
modifica la località
</a>
</p>
</div>
</div>
</form> | CroceRossaCatania/gaia | inc/attivita.modifica.php | PHP | gpl-3.0 | 4,359 |
<?php
$rangeid=122;
$prevcid=126;
$prevwidth=754;
$interval=false;
$range=array (
32 =>
array (
0 => 286,
1 => 360,
2 => 414,
3 => 754,
4 => 572,
5 => 855,
6 => 702,
7 => 247,
),
40 =>
array (
0 => 351,
1 => 351,
'interval' => true,
),
42 =>
array (
0 => 450,
1 => 754,
2 => 286,
3 => 325,
4 => 286,
5 => 303,
),
48 =>
array (
0 => 572,
1 => 572,
'interval' => true,
2 => 572,
3 => 572,
4 => 572,
5 => 572,
6 => 572,
7 => 572,
8 => 572,
9 => 572,
),
58 =>
array (
0 => 303,
1 => 303,
'interval' => true,
),
60 =>
array (
0 => 754,
1 => 754,
'interval' => true,
2 => 754,
),
63 =>
array (
0 => 478,
1 => 900,
2 => 615,
3 => 617,
4 => 628,
5 => 693,
6 => 568,
7 => 518,
8 => 697,
9 => 677,
),
73 =>
array (
0 => 265,
1 => 265,
'interval' => true,
),
75 =>
array (
0 => 590,
1 => 501,
2 => 776,
3 => 673,
4 => 708,
5 => 542,
6 => 708,
7 => 625,
8 => 571,
9 => 549,
10 => 659,
11 => 615,
12 => 890,
13 => 616,
14 => 549,
15 => 616,
16 => 351,
17 => 303,
18 => 351,
19 => 754,
),
95 =>
array (
0 => 450,
1 => 450,
'interval' => true,
),
97 =>
array (
0 => 551,
1 => 571,
2 => 495,
3 => 571,
4 => 554,
5 => 316,
6 => 571,
7 => 570,
),
105 =>
array (
0 => 250,
1 => 250,
'interval' => true,
),
107 =>
array (
0 => 521,
1 => 250,
2 => 876,
3 => 570,
4 => 550,
),
112 =>
array (
0 => 571,
1 => 571,
'interval' => true,
),
114 =>
array (
0 => 370,
1 => 469,
2 => 353,
3 => 570,
4 => 532,
5 => 736,
),
120 =>
array (
0 => 532,
1 => 532,
'interval' => true,
),
122 =>
array (
0 => 472,
1 => 572,
2 => 303,
3 => 572,
4 => 754,
),
);
| Tinchosan/wingpanel | admin/lib/vendor/mpdf/mpdf/tmp/ttfontdata/dejavusanscondensed.cw127.php | PHP | gpl-3.0 | 2,055 |
/* ************************************************************************
Copyright:
License:
Authors:
************************************************************************ */
qx.Theme.define("${Namespace}.theme.modern.Decoration",
{
decorations :
{
}
}); | 09zwcbupt/undergrad_thesis | ext/poxdesk/qx/component/skeleton/contribution/trunk/source/class/custom/theme/modern/Decoration.tmpl.js | JavaScript | gpl-3.0 | 280 |
<?php
include ('lib/twitese.php');
$title = "Settings";
include ('inc/header.php');
if (!loginStatus()) header('location: login.php');
?>
<script src="js/colorpicker.js"></script>
<script src="js/setting.js"></script>
<link rel="stylesheet" href="css/colorpicker.css" />
<div id="statuses" class="column round-left">
<div id="setting">
<div id="setting_nav">
<?php
$settingType = isset($_GET['t'])? $_GET['t'] : 1;
switch($settingType){
case 'profile':
?>
<span class="subnavLink"><a href="setting.php">Customize</a></span><span class="subnavNormal">Profile</span>
<?php
break;
default:
?>
<span class="subnavNormal">Customize</span><span class="subnavLink"><a href="setting.php?t=profile">Profile</a></span>
<?php
}
?>
</div>
<?php
switch($settingType){
case 'profile':
$user = getTwitter()->veverify(true);
?>
<form id="setting_form" action="ajax/uploadImage.php?do=profile" method="post" enctype="multipart/form-data">
<fieldset class="settings">
<legend>Avatar</legend>
<ol>
<li style="display:inline-block"><img src="<?php echo isset($_COOKIE['imgurl']) ? $_COOKIE['imgurl'] : getAvatar($user->profile_image_url)?>" id="avatarimg"></img></li>
<ol style="margin-left:29px">
<li><input type="file" name="image" id="profile_image"/></li>
<li><input type="submit" id="AvatarUpload" class="btn" value="Upload"/><small style="margin-left:10px;vertical-align: middle;">BMP,JPG or PNG accepted, less than 800K.</small></li>
</ol></ol>
</fieldset>
</form>
<form id="setting_form" action="ajax/uploadImage.php?do=background" method="post" enctype="multipart/form-data">
<fieldset class="settings">
<legend>Background</legend>
<ol>
<li style="display:inline-block"><img src="<?php echo getAvatar($user->profile_background_image_url)?>" id="backgroundimg" style="max-width: 460px;"></img></li>
<li><input type="file" name="image" id="profile_background"/></li>
<li><input type="submit" id="BackgroundUpload" class="btn" value="Upload"/><small style="margin-left:10px;vertical-align: middle;">BMP,JPG or PNG accepted, less than 800K.</small></li>
<li>
<input id="tile" type="checkbox" <?php echo $user->profile_background_tile ? 'checked="checked"' : '' ?> />
<label>Tile the profile background</label>
</li>
</ol>
</fieldset>
</form>
<form id="setting_form" action="ajax/updateProfile.php" method="post">
<fieldset class="settings">
<legend>Literature</legend>
<table id="setting_table">
<tr>
<td class="setting_title">Name: </td>
<td><input class="setting_input" type="text" name="name" value="<?php echo isset($user->name) ? $user->name : ''?>" /></td>
</tr>
<tr>
<td class="setting_title">URL: </td>
<td><input class="setting_input" type="text" name="url" value="<?php
if (!isset($user->url))
echo '';
else {
$hops = array();
$newurl = expandRedirect($user->url, $hops);
echo $newurl;
}
?>" /></td>
</tr>
<tr>
<td class="setting_title">Location: </td>
<td><input class="setting_input" type="text" name="location" value="<?php echo isset($user->location) ? $user->location : '' ?>" /></td>
</tr>
<tr>
<td class="setting_title">Bio: </td><td><small style="margin-left:5px;vertical-align: top;">*Max 160 chars</small></td>
</tr><tr>
<td></td>
<td><textarea id="setting_text" name="description"><?php echo isset($user->description) ? $user->description : '' ?></textarea></td>
</tr>
</table>
<input type="submit" id="saveProfile" class="btn" value="Save" />
</fieldset>
<?php
break;
default:
?>
<form id="style_form" action="setting.php" method="post">
<fieldset class="settings">
<legend>Utility</legend>
<input id="proxifyAvatar" type="checkbox" />
<label>Proxify the Avatar</label>
<br /><br />
<input id="autoscroll" type="checkbox" />
<label>Timeline Autopaging</label>
<br /><br />
<input id="sidebarscroll" type="checkbox" />
<label>Fixed Sidebar</label>
<br /><br />
Share to Twitter: <a class="share" title="Drag me to share!" href="javascript:var%20d=document,w=window,f='<?php echo $base_url."/share.php" ?>',l=d.location,e=encodeURIComponent,p='?u='+e(l.href)+'&t='+e(d.title)+'&d='+e(w.getSelection?w.getSelection().toString():d.getSelection?d.getSelection():d.selection.createRange().text)+'&s=bm';a=function(){if(!w.open(f+p,'sharer','toolbar=0,status=0,resizable=0,width=600,height=300,left=175,top=150'))l.href=f+'.new'+p};if(/Firefox/.test(navigator.userAgent))setTimeout(a,0);else{a()}void(0);">Share</a>
<small>(Bookmark this link for future use)</small>
</fieldset>
<fieldset class="settings">
<legend>Media Preview</legend>
<input id="showpic" type="checkbox" checked="checked" />
<label>Enable Images Preview</label>
<small>(Supports common image hostings)</small>
<br /><br />
<input id="mediaPreSelect" type="checkbox" checked="checked" />
<label>Enable Videos Preview</label>
<small>(Supports Xiami and Tudou)</small><br />
</fieldset>
<fieldset class="settings">
<legend>Auto Refresh Interval</legend>
<label>Home Page</label>
<select id="homeInterval" name="homeInterval" value="<?php echo getCookie('homeInterval')?>">
<option value="1">1 min</option>
<option value="2" selected="selected">2 min (Default)</option>
<option value="3">3 min</option>
<option value="5">5 min</option>
<option value="10">10 min</option>
<option value="0">Never</option>
</select>
<label>Updates Page</label>
<select id="updatesInterval" name="updatesInterval" value="<?php echo getCookie('updatesInterval')?>">
<option value="1">1 min</option>
<option value="2">2 min</option>
<option value="3" selected="selected">3 min (Default)</option>
<option value="5">5 min</option>
<option value="10">10 min</option>
<option value="0">Never</option>
</select>
</fieldset>
<fieldset class="settings">
<legend>UI Preferences</legend>
<input id="twitterbg" type="checkbox" />
<label>Use twitter account background</label>
<br /><br />
<input id="shownick" type="checkbox" />
<label>Use nickname instead of username</label>
<br /><br />
<label>Background Color</label>
<input class="bg_input" type="text" id="bodyBg" name="bodyBg" value="<?php echo getDefCookie("Bgcolor","") ?>" />
<small>(Choose your favorite color here)</small>
<br /><br />
<label>Font Size</label>
<select id="fontsize" name="fontsize" value="<?php echo getCookie('fontsize')?>">
<option value="12px">Small</option>
<option value="13px" selected="selected">Middle(Default)</option>
<option value="14px">Large</option>
<option value="15px">Extra Large</option>
</select>
<small>(Set the font size)</small>
<br /><br />
<label>Customize CSS</label>
<small>(You can put your own CSS hack here, or your Twitter style code)</small>
<br />
<label>Tips:</label>
<small>You must use <a href="http://i.zou.lu/csstidy/" target="_blank" title="Powered by Showfom">CSSTidy</a> to compress your stylesheet.</small>
<br />
<textarea type="text" id="myCSS" name="myCSS" value="" /><?php echo getDefCookie("myCSS","") ?></textarea>
</fieldset>
<?php
}
?>
<a id="reset_link" href="#" title="You will lose all customized settings!">Reset to default</a>
</form>
</div>
</div>
<?php
include ('inc/sidebar.php');
include ('inc/footer.php');
?>
| xctcc/embrr | setting.php | PHP | gpl-3.0 | 7,543 |
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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.
-----------------------------------------------------------------------------
*/
#include "OgreGLRenderSystemCommon.h"
#include "OgreFrustum.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN
#include <OgreEGLWindow.h>
#endif
namespace Ogre {
void GLRenderSystemCommon::_makeProjectionMatrix(const Radian& fovy, Real aspect,
Real nearPlane, Real farPlane,
Matrix4& dest, bool forGpuProgram)
{
Radian thetaY(fovy / 2.0f);
Real tanThetaY = Math::Tan(thetaY);
// Calc matrix elements
Real w = (1.0f / tanThetaY) / aspect;
Real h = 1.0f / tanThetaY;
Real q, qn;
if (farPlane == 0)
{
// Infinite far plane
q = Frustum::INFINITE_FAR_PLANE_ADJUST - 1;
qn = nearPlane * (Frustum::INFINITE_FAR_PLANE_ADJUST - 2);
}
else
{
q = -(farPlane + nearPlane) / (farPlane - nearPlane);
qn = -2 * (farPlane * nearPlane) / (farPlane - nearPlane);
}
// NB This creates Z in range [-1,1]
//
// [ w 0 0 0 ]
// [ 0 h 0 0 ]
// [ 0 0 q qn ]
// [ 0 0 -1 0 ]
dest = Matrix4::ZERO;
dest[0][0] = w;
dest[1][1] = h;
dest[2][2] = q;
dest[2][3] = qn;
dest[3][2] = -1;
}
void GLRenderSystemCommon::_makeProjectionMatrix(Real left, Real right,
Real bottom, Real top,
Real nearPlane, Real farPlane,
Matrix4& dest, bool forGpuProgram)
{
Real width = right - left;
Real height = top - bottom;
Real q, qn;
if (farPlane == 0)
{
// Infinite far plane
q = Frustum::INFINITE_FAR_PLANE_ADJUST - 1;
qn = nearPlane * (Frustum::INFINITE_FAR_PLANE_ADJUST - 2);
}
else
{
q = -(farPlane + nearPlane) / (farPlane - nearPlane);
qn = -2 * (farPlane * nearPlane) / (farPlane - nearPlane);
}
dest = Matrix4::ZERO;
dest[0][0] = 2 * nearPlane / width;
dest[0][2] = (right+left) / width;
dest[1][1] = 2 * nearPlane / height;
dest[1][2] = (top+bottom) / height;
dest[2][2] = q;
dest[2][3] = qn;
dest[3][2] = -1;
}
void GLRenderSystemCommon::_makeOrthoMatrix(const Radian& fovy, Real aspect,
Real nearPlane, Real farPlane,
Matrix4& dest, bool forGpuProgram)
{
Radian thetaY(fovy / 2.0f);
Real tanThetaY = Math::Tan(thetaY);
// Real thetaX = thetaY * aspect;
Real tanThetaX = tanThetaY * aspect; // Math::Tan(thetaX);
Real half_w = tanThetaX * nearPlane;
Real half_h = tanThetaY * nearPlane;
Real iw = 1.0f / half_w;
Real ih = 1.0f / half_h;
Real q;
if (farPlane == 0)
{
q = 0;
}
else
{
q = 2.0f / (farPlane - nearPlane);
}
dest = Matrix4::ZERO;
dest[0][0] = iw;
dest[1][1] = ih;
dest[2][2] = -q;
dest[2][3] = -(farPlane + nearPlane) / (farPlane - nearPlane);
dest[3][3] = 1;
}
void GLRenderSystemCommon::_applyObliqueDepthProjection(Matrix4& matrix,
const Plane& plane,
bool forGpuProgram)
{
// Thanks to Eric Lenyel for posting this calculation at www.terathon.com
// Calculate the clip-space corner point opposite the clipping plane
// as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and
// transform it into camera space by multiplying it
// by the inverse of the projection matrix
Vector4 q;
q.x = (Math::Sign(plane.normal.x) + matrix[0][2]) / matrix[0][0];
q.y = (Math::Sign(plane.normal.y) + matrix[1][2]) / matrix[1][1];
q.z = -1.0F;
q.w = (1.0F + matrix[2][2]) / matrix[2][3];
// Calculate the scaled plane vector
Vector4 clipPlane4d(plane.normal.x, plane.normal.y, plane.normal.z, plane.d);
Vector4 c = clipPlane4d * (2.0F / (clipPlane4d.dotProduct(q)));
// Replace the third row of the projection matrix
matrix[2][0] = c.x;
matrix[2][1] = c.y;
matrix[2][2] = c.z + 1.0F;
matrix[2][3] = c.w;
}
#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN
void GLRenderSystemCommon::_destroyInternalResources(RenderWindow* pRenderWnd)
{
static_cast<EGLWindow*>(pRenderWnd)->_destroyInternalResources();
}
void GLRenderSystemCommon::_createInternalResources(RenderWindow* pRenderWnd, void* window,
void* config)
{
static_cast<EGLWindow*>(pRenderWnd)
->_createInternalResources(reinterpret_cast<EGLNativeWindowType>(window), config);
}
#endif
}
| GDevs/mission-farpoint | ogre/RenderSystems/GLSupport/src/OgreGLRenderSystemCommon.cpp | C++ | gpl-3.0 | 6,592 |
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2016-2017 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package builtin
import (
"github.com/snapcore/snapd/osutil"
)
const networkControlSummary = `allows configuring networking and network namespaces`
const networkControlBaseDeclarationSlots = `
network-control:
allow-installation:
slot-snap-type:
- core
deny-auto-connection: true
`
const networkControlConnectedPlugAppArmor = `
# Description: Can configure networking and network namespaces via the standard
# 'ip netns' command (man ip-netns(8)). This interface is restricted because it
# gives wide, privileged access to networking and should only be used with
# trusted apps.
#include <abstractions/nameservice>
/run/systemd/resolve/stub-resolv.conf rk,
# systemd-resolved (not yet included in nameservice abstraction)
#
# Allow access to the safe members of the systemd-resolved D-Bus API:
#
# https://www.freedesktop.org/wiki/Software/systemd/resolved/
#
# This API may be used directly over the D-Bus system bus or it may be used
# indirectly via the nss-resolve plugin:
#
# https://www.freedesktop.org/software/systemd/man/nss-resolve.html
#
#include <abstractions/dbus-strict>
dbus send
bus=system
path="/org/freedesktop/resolve1"
interface="org.freedesktop.resolve1.Manager"
member="Resolve{Address,Hostname,Record,Service}"
peer=(name="org.freedesktop.resolve1"),
dbus (send)
bus=system
path="/org/freedesktop/resolve1"
interface="org.freedesktop.resolve1.Manager"
member="SetLink{DNS,MulticastDNS,Domains,LLMNR}"
peer=(label=unconfined),
#include <abstractions/ssl_certs>
capability net_admin,
capability net_raw,
capability setuid, # ping
capability net_broadcast, # openvswitchd
# Allow protocols except those that we blacklist in
# /etc/modprobe.d/blacklist-rare-network.conf
network appletalk,
network bridge,
network inet,
network inet6,
network ipx,
network packet,
network pppox,
network sna,
@{PROC}/@{pid}/net/ r,
@{PROC}/@{pid}/net/** r,
# used by sysctl, et al
@{PROC}/sys/ r,
@{PROC}/sys/net/ r,
@{PROC}/sys/net/core/ r,
@{PROC}/sys/net/core/** rw,
@{PROC}/sys/net/ipv{4,6}/ r,
@{PROC}/sys/net/ipv{4,6}/** rw,
@{PROC}/sys/net/netfilter/ r,
@{PROC}/sys/net/netfilter/** rw,
@{PROC}/sys/net/nf_conntrack_max rw,
# For advanced wireless configuration
/sys/kernel/debug/ieee80211/ r,
/sys/kernel/debug/ieee80211/** rw,
# read netfilter module parameters
/sys/module/nf_*/ r,
/sys/module/nf_*/parameters/{,*} r,
# networking tools
/{,usr/}{,s}bin/arp ixr,
/{,usr/}{,s}bin/arpd ixr,
/{,usr/}{,s}bin/bridge ixr,
/{,usr/}{,s}bin/dhclient Pxr, # use ixr instead if want to limit to snap dirs
/{,usr/}{,s}bin/dhclient-script ixr,
/{,usr/}{,s}bin/ifconfig ixr,
/{,usr/}{,s}bin/ifdown ixr,
/{,usr/}{,s}bin/ifquery ixr,
/{,usr/}{,s}bin/ifup ixr,
/{,usr/}{,s}bin/ip ixr,
/{,usr/}{,s}bin/ipmaddr ixr,
/{,usr/}{,s}bin/iptunnel ixr,
/{,usr/}{,s}bin/iw ixr,
/{,usr/}{,s}bin/nameif ixr,
/{,usr/}{,s}bin/netstat ixr, # -p not supported
/{,usr/}{,s}bin/nstat ixr,
/{,usr/}{,s}bin/ping ixr,
/{,usr/}{,s}bin/ping6 ixr,
/{,usr/}{,s}bin/pppd ixr,
/{,usr/}{,s}bin/pppdump ixr,
/{,usr/}{,s}bin/pppoe-discovery ixr,
#/{,usr/}{,s}bin/pppstats ixr, # needs sys_module
/{,usr/}{,s}bin/route ixr,
/{,usr/}{,s}bin/routef ixr,
/{,usr/}{,s}bin/routel ixr,
/{,usr/}{,s}bin/rtacct ixr,
/{,usr/}{,s}bin/rtmon ixr,
/{,usr/}{,s}bin/ss ixr,
/{,usr/}{,s}bin/sysctl ixr,
/{,usr/}{,s}bin/tc ixr,
/{,usr/}{,s}bin/wpa_action ixr,
/{,usr/}{,s}bin/wpa_cli ixr,
/{,usr/}{,s}bin/wpa_passphrase ixr,
/{,usr/}{,s}bin/wpa_supplicant ixr,
/dev/rfkill rw,
/sys/class/rfkill/ r,
/sys/devices/{pci[0-9a-f]*,platform,virtual}/**/rfkill[0-9]*/{,**} r,
/sys/devices/{pci[0-9a-f]*,platform,virtual}/**/rfkill[0-9]*/state w,
# For reading the address of a particular ethernet interface
/sys/devices/{pci[0-9a-f]*,platform,virtual}/**/net/*/address r,
# arp
network netlink dgram,
# ip, et al
/etc/iproute2/{,**} r,
/etc/iproute2/rt_{protos,realms,scopes,tables} w,
/etc/iproute2/rt_{protos,tables}.d/* w,
# ping - child profile would be nice but seccomp causes problems with that
/{,usr/}{,s}bin/ping ixr,
/{,usr/}{,s}bin/ping6 ixr,
network inet raw,
network inet6 raw,
# pppd
capability setuid,
@{PROC}/@{pid}/loginuid r,
@{PROC}/@{pid}/mounts r,
# static host tables
/etc/hosts w,
# resolvconf
/{,usr/}sbin/resolvconf ixr,
/run/resolvconf/{,**} rk,
/run/resolvconf/** w,
/etc/resolvconf/{,**} r,
/{,usr/}lib/resolvconf/* ix,
# Required by resolvconf
/{,usr/}bin/run-parts ixr,
/etc/resolvconf/update.d/* ix,
# wpa_suplicant
/{,var/}run/wpa_supplicant/ w,
/{,var/}run/wpa_supplicant/** rw,
/etc/wpa_supplicant/{,**} ixr,
#ifup,ifdown, dhclient
/{,var/}run/dhclient.*.pid rw,
/var/lib/dhcp/ r,
/var/lib/dhcp/** rw,
/run/network/ifstate* rw,
/run/network/.ifstate* rw,
/run/network/ifup-* rw,
/run/network/ifdown-* rw,
# route
/etc/networks r,
/etc/ethers r,
/etc/rpc r,
# TUN/TAP - https://www.kernel.org/doc/Documentation/networking/tuntap.txt
#
# We only need to tag /dev/net/tun since the tap[0-9]* and tun[0-9]* devices
# are virtual and don't show up in /dev
/dev/net/tun rw,
# Access to sysfs interfaces for tun/tap device settings.
/sys/devices/virtual/net/tap*/** rw,
# access to bridge sysfs interfaces for bridge settings
/sys/devices/virtual/net/*/bridge/* rw,
# Network namespaces via 'ip netns'. In order to create network namespaces
# that persist outside of the process and be entered (eg, via
# 'ip netns exec ...') the ip command uses mount namespaces such that
# applications can open the /run/netns/NAME object and use it with setns(2).
# For 'ip netns exec' it will also create a mount namespace and bind mount
# network configuration files into /etc in that namespace. See man ip-netns(8)
# for details.
capability sys_admin, # for setns()
network netlink raw,
/ r,
/run/netns/ r, # only 'r' since snap-confine will create this for us
/run/netns/* rw,
mount options=(rw, rshared) -> /run/netns/,
mount options=(rw, bind) /run/netns/ -> /run/netns/,
mount options=(rw, bind) / -> /run/netns/*,
umount /,
# 'ip netns identify <pid>' and 'ip netns pids foo'. Intenionally omit 'ptrace
# (trace)' here since ip netns doesn't actually need to trace other processes.
capability sys_ptrace,
# 'ip netns exec foo /bin/sh'
mount options=(rw, rslave) /,
mount options=(rw, rslave), # LP: #1648245
umount /sys/,
# Eg, nsenter --net=/run/netns/... <command>
/{,usr/}{,s}bin/nsenter ixr,
`
const networkControlConnectedPlugSecComp = `
# Description: Can configure networking and network namespaces via the standard
# 'ip netns' command (man ip-netns(8)). This interface is restricted because it
# gives wide, privileged access to networking and should only be used with
# trusted apps.
# for ping and ping6
capset
# Network namespaces via 'ip netns'. In order to create network namespaces
# that persist outside of the process and be entered (eg, via
# 'ip netns exec ...') the ip command uses mount namespaces such that
# applications can open the /run/netns/NAME object and use it with setns(2).
# For 'ip netns exec' it will also create a mount namespace and bind mount
# network configuration files into /etc in that namespace. See man ip-netns(8)
# for details.
bind
mount
umount
umount2
unshare
setns - CLONE_NEWNET
# For various network related netlink sockets
socket AF_NETLINK - NETLINK_ROUTE
socket AF_NETLINK - NETLINK_FIB_LOOKUP
socket AF_NETLINK - NETLINK_INET_DIAG
socket AF_NETLINK - NETLINK_XFRM
socket AF_NETLINK - NETLINK_DNRTMSG
socket AF_NETLINK - NETLINK_ISCSI
socket AF_NETLINK - NETLINK_RDMA
socket AF_NETLINK - NETLINK_GENERIC
# for receiving kobject_uevent() net messages from the kernel
socket AF_NETLINK - NETLINK_KOBJECT_UEVENT
`
/* https://www.kernel.org/doc/Documentation/networking/tuntap.txt
*
* We only need to tag /dev/net/tun since the tap[0-9]* and tun[0-9]* devices
* are virtual and don't show up in /dev
*/
var networkControlConnectedPlugUDev = []string{
`KERNEL=="rfkill"`,
`KERNEL=="tun"`,
}
var networkControlConnectedPlugMount = []osutil.MountEntry{{
Name: "/var/lib/snapd/hostfs/var/lib/dhcp",
Dir: "/var/lib/dhcp",
Options: []string{"bind", "rw", osutil.XSnapdIgnoreMissing()},
}}
// TODO: Add a layer that derives this sort of data from mount entry, like the
// one above, into a set of apparmor rules for snap-update-ns, like the ones
// below.
//
// When setting up a mount entry, we also need corresponding
// snap-updates-ns rules. Eg, if have:
// []osutil.MountEntry{{
// Name: "/foo/bar",
// Dir: "/bar",
// Options: []string{"rw", "bind"},
// }}
// Then you can expect to need:
// /foo/ r,
// /foo/bar/ r,
// mount options=(rw bind) /foo/bar/ -> /bar/,
// umount /bar/,
// ...
// You'll need 'r' rules for all the directories that need to be traversed,
// starting from the root directory all the way down to the directory being
// mounted. This is required by the safe bind mounting trick employed by
// snap-update-ns.
//
// You'll need 'rw' rules to support cases when snap-update-ns is expected to
// create the missing directory, before performing the bind mount. Note that
// there are two sides, one side is the host visible through
// /var/lib/snapd/hostfs and the other side is everything else. To support
// writes to the host side you need to coordinate with the trespassing rules
// implemented in snap-update-ns/system.go.
var networkControlConnectedPlugUpdateNSAppArmor = `
/var/ r,
/var/lib/ r,
/var/lib/snapd/ r,
/var/lib/snapd/hostfs/ r,
/var/lib/snapd/hostfs/var/ r,
/var/lib/snapd/hostfs/var/lib/ r,
/var/lib/snapd/hostfs/var/lib/dhcp/ r,
/var/lib/dhcp/ r,
mount options=(rw bind) /var/lib/snapd/hostfs/var/lib/dhcp/ -> /var/lib/dhcp/,
umount /var/lib/dhcp/,
`
func init() {
registerIface(&commonInterface{
name: "network-control",
summary: networkControlSummary,
implicitOnCore: true,
implicitOnClassic: true,
baseDeclarationSlots: networkControlBaseDeclarationSlots,
connectedPlugAppArmor: networkControlConnectedPlugAppArmor,
connectedPlugSecComp: networkControlConnectedPlugSecComp,
connectedPlugUDev: networkControlConnectedPlugUDev,
connectedPlugMount: networkControlConnectedPlugMount,
connectedPlugUpdateNSAppArmor: networkControlConnectedPlugUpdateNSAppArmor,
suppressPtraceTrace: true,
suppressSysModuleCapability: true,
// affects the plug snap because of mount backend
affectsPlugOnRefresh: true,
})
}
| sergiocazzolato/snapd | interfaces/builtin/network_control.go | GO | gpl-3.0 | 11,137 |
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/v8.h"
#include "src/arguments.h"
#include "src/compiler.h"
#include "src/deoptimizer.h"
#include "src/frames.h"
#include "src/full-codegen.h"
#include "src/messages.h"
#include "src/runtime/runtime-utils.h"
#include "src/v8threads.h"
#include "src/vm-state-inl.h"
namespace v8 {
namespace internal {
RUNTIME_FUNCTION(Runtime_CompileLazy) {
HandleScope scope(isolate);
DCHECK(args.length() == 1);
CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
#ifdef DEBUG
if (FLAG_trace_lazy && !function->shared()->is_compiled()) {
PrintF("[unoptimized: ");
function->PrintName();
PrintF("]\n");
}
#endif
// Compile the target function.
DCHECK(function->shared()->allows_lazy_compilation());
Handle<Code> code;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, code,
Compiler::GetLazyCode(function));
DCHECK(code->kind() == Code::FUNCTION ||
code->kind() == Code::OPTIMIZED_FUNCTION);
function->ReplaceCode(*code);
return *code;
}
RUNTIME_FUNCTION(Runtime_CompileOptimized) {
HandleScope scope(isolate);
DCHECK(args.length() == 2);
CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
CONVERT_BOOLEAN_ARG_CHECKED(concurrent, 1);
Compiler::ConcurrencyMode mode =
concurrent ? Compiler::CONCURRENT : Compiler::NOT_CONCURRENT;
Handle<Code> code;
Handle<Code> unoptimized(function->shared()->code());
if (Compiler::GetOptimizedCode(function, unoptimized, mode).ToHandle(&code)) {
// Optimization succeeded, return optimized code.
function->ReplaceCode(*code);
} else {
// Optimization failed, get unoptimized code.
if (isolate->has_pending_exception()) { // Possible stack overflow.
return isolate->heap()->exception();
}
code = Handle<Code>(function->shared()->code(), isolate);
if (code->kind() != Code::FUNCTION &&
code->kind() != Code::OPTIMIZED_FUNCTION) {
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, code, Compiler::GetUnoptimizedCode(function));
}
function->ReplaceCode(*code);
}
DCHECK(function->code()->kind() == Code::FUNCTION ||
function->code()->kind() == Code::OPTIMIZED_FUNCTION ||
function->IsInOptimizationQueue());
return function->code();
}
RUNTIME_FUNCTION(Runtime_NotifyStubFailure) {
HandleScope scope(isolate);
DCHECK(args.length() == 0);
Deoptimizer* deoptimizer = Deoptimizer::Grab(isolate);
DCHECK(AllowHeapAllocation::IsAllowed());
delete deoptimizer;
return isolate->heap()->undefined_value();
}
class ActivationsFinder : public ThreadVisitor {
public:
Code* code_;
bool has_code_activations_;
explicit ActivationsFinder(Code* code)
: code_(code), has_code_activations_(false) {}
void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
JavaScriptFrameIterator it(isolate, top);
VisitFrames(&it);
}
void VisitFrames(JavaScriptFrameIterator* it) {
for (; !it->done(); it->Advance()) {
JavaScriptFrame* frame = it->frame();
if (code_->contains(frame->pc())) has_code_activations_ = true;
}
}
};
RUNTIME_FUNCTION(Runtime_NotifyDeoptimized) {
HandleScope scope(isolate);
DCHECK(args.length() == 1);
CONVERT_SMI_ARG_CHECKED(type_arg, 0);
Deoptimizer::BailoutType type =
static_cast<Deoptimizer::BailoutType>(type_arg);
Deoptimizer* deoptimizer = Deoptimizer::Grab(isolate);
DCHECK(AllowHeapAllocation::IsAllowed());
Handle<JSFunction> function = deoptimizer->function();
Handle<Code> optimized_code = deoptimizer->compiled_code();
DCHECK(optimized_code->kind() == Code::OPTIMIZED_FUNCTION);
DCHECK(type == deoptimizer->bailout_type());
// Make sure to materialize objects before causing any allocation.
JavaScriptFrameIterator it(isolate);
deoptimizer->MaterializeHeapObjects(&it);
delete deoptimizer;
JavaScriptFrame* frame = it.frame();
RUNTIME_ASSERT(frame->function()->IsJSFunction());
DCHECK(frame->function() == *function);
// Avoid doing too much work when running with --always-opt and keep
// the optimized code around.
if (FLAG_always_opt || type == Deoptimizer::LAZY) {
return isolate->heap()->undefined_value();
}
// Search for other activations of the same function and code.
ActivationsFinder activations_finder(*optimized_code);
activations_finder.VisitFrames(&it);
isolate->thread_manager()->IterateArchivedThreads(&activations_finder);
if (!activations_finder.has_code_activations_) {
if (function->code() == *optimized_code) {
if (FLAG_trace_deopt) {
PrintF("[removing optimized code for: ");
function->PrintName();
PrintF("]\n");
}
function->ReplaceCode(function->shared()->code());
// Evict optimized code for this function from the cache so that it
// doesn't get used for new closures.
function->shared()->EvictFromOptimizedCodeMap(*optimized_code,
"notify deoptimized");
}
} else {
// TODO(titzer): we should probably do DeoptimizeCodeList(code)
// unconditionally if the code is not already marked for deoptimization.
// If there is an index by shared function info, all the better.
Deoptimizer::DeoptimizeFunction(*function);
}
return isolate->heap()->undefined_value();
}
static bool IsSuitableForOnStackReplacement(Isolate* isolate,
Handle<JSFunction> function) {
// Keep track of whether we've succeeded in optimizing.
if (function->shared()->optimization_disabled()) return false;
// If we are trying to do OSR when there are already optimized
// activations of the function, it means (a) the function is directly or
// indirectly recursive and (b) an optimized invocation has been
// deoptimized so that we are currently in an unoptimized activation.
// Check for optimized activations of this function.
for (JavaScriptFrameIterator it(isolate); !it.done(); it.Advance()) {
JavaScriptFrame* frame = it.frame();
if (frame->is_optimized() && frame->function() == *function) return false;
}
return true;
}
RUNTIME_FUNCTION(Runtime_CompileForOnStackReplacement) {
HandleScope scope(isolate);
DCHECK(args.length() == 1);
CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
Handle<Code> caller_code(function->shared()->code());
// We're not prepared to handle a function with arguments object.
DCHECK(!function->shared()->uses_arguments());
RUNTIME_ASSERT(FLAG_use_osr);
// Passing the PC in the javascript frame from the caller directly is
// not GC safe, so we walk the stack to get it.
JavaScriptFrameIterator it(isolate);
JavaScriptFrame* frame = it.frame();
if (!caller_code->contains(frame->pc())) {
// Code on the stack may not be the code object referenced by the shared
// function info. It may have been replaced to include deoptimization data.
caller_code = Handle<Code>(frame->LookupCode());
}
uint32_t pc_offset =
static_cast<uint32_t>(frame->pc() - caller_code->instruction_start());
#ifdef DEBUG
DCHECK_EQ(frame->function(), *function);
DCHECK_EQ(frame->LookupCode(), *caller_code);
DCHECK(caller_code->contains(frame->pc()));
#endif // DEBUG
BailoutId ast_id = caller_code->TranslatePcOffsetToAstId(pc_offset);
DCHECK(!ast_id.IsNone());
Compiler::ConcurrencyMode mode =
isolate->concurrent_osr_enabled() &&
(function->shared()->ast_node_count() > 512)
? Compiler::CONCURRENT
: Compiler::NOT_CONCURRENT;
Handle<Code> result = Handle<Code>::null();
OptimizedCompileJob* job = NULL;
if (mode == Compiler::CONCURRENT) {
// Gate the OSR entry with a stack check.
BackEdgeTable::AddStackCheck(caller_code, pc_offset);
// Poll already queued compilation jobs.
OptimizingCompileDispatcher* dispatcher =
isolate->optimizing_compile_dispatcher();
if (dispatcher->IsQueuedForOSR(function, ast_id)) {
if (FLAG_trace_osr) {
PrintF("[OSR - Still waiting for queued: ");
function->PrintName();
PrintF(" at AST id %d]\n", ast_id.ToInt());
}
return NULL;
}
job = dispatcher->FindReadyOSRCandidate(function, ast_id);
}
if (job != NULL) {
if (FLAG_trace_osr) {
PrintF("[OSR - Found ready: ");
function->PrintName();
PrintF(" at AST id %d]\n", ast_id.ToInt());
}
result = Compiler::GetConcurrentlyOptimizedCode(job);
} else if (IsSuitableForOnStackReplacement(isolate, function)) {
if (FLAG_trace_osr) {
PrintF("[OSR - Compiling: ");
function->PrintName();
PrintF(" at AST id %d]\n", ast_id.ToInt());
}
MaybeHandle<Code> maybe_result =
Compiler::GetOptimizedCode(function, caller_code, mode, ast_id);
if (maybe_result.ToHandle(&result) &&
result.is_identical_to(isolate->builtins()->InOptimizationQueue())) {
// Optimization is queued. Return to check later.
return NULL;
}
}
// Revert the patched back edge table, regardless of whether OSR succeeds.
BackEdgeTable::Revert(isolate, *caller_code);
// Check whether we ended up with usable optimized code.
if (!result.is_null() && result->kind() == Code::OPTIMIZED_FUNCTION) {
DeoptimizationInputData* data =
DeoptimizationInputData::cast(result->deoptimization_data());
if (data->OsrPcOffset()->value() >= 0) {
DCHECK(BailoutId(data->OsrAstId()->value()) == ast_id);
if (FLAG_trace_osr) {
PrintF("[OSR - Entry at AST id %d, offset %d in optimized code]\n",
ast_id.ToInt(), data->OsrPcOffset()->value());
}
// TODO(titzer): this is a massive hack to make the deopt counts
// match. Fix heuristics for reenabling optimizations!
function->shared()->increment_deopt_count();
if (result->is_turbofanned()) {
// TurboFanned OSR code cannot be installed into the function.
// But the function is obviously hot, so optimize it next time.
function->ReplaceCode(
isolate->builtins()->builtin(Builtins::kCompileOptimized));
} else {
// Crankshafted OSR code can be installed into the function.
function->ReplaceCode(*result);
}
return *result;
}
}
// Failed.
if (FLAG_trace_osr) {
PrintF("[OSR - Failed: ");
function->PrintName();
PrintF(" at AST id %d]\n", ast_id.ToInt());
}
if (!function->IsOptimized()) {
function->ReplaceCode(function->shared()->code());
}
return NULL;
}
RUNTIME_FUNCTION(Runtime_TryInstallOptimizedCode) {
HandleScope scope(isolate);
DCHECK(args.length() == 1);
CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
// First check if this is a real stack overflow.
StackLimitCheck check(isolate);
if (check.JsHasOverflowed()) {
SealHandleScope shs(isolate);
return isolate->StackOverflow();
}
isolate->optimizing_compile_dispatcher()->InstallOptimizedFunctions();
return (function->IsOptimized()) ? function->code()
: function->shared()->code();
}
bool CodeGenerationFromStringsAllowed(Isolate* isolate,
Handle<Context> context) {
DCHECK(context->allow_code_gen_from_strings()->IsFalse());
// Check with callback if set.
AllowCodeGenerationFromStringsCallback callback =
isolate->allow_code_gen_callback();
if (callback == NULL) {
// No callback set and code generation disallowed.
return false;
} else {
// Callback set. Let it decide if code generation is allowed.
VMState<EXTERNAL> state(isolate);
return callback(v8::Utils::ToLocal(context));
}
}
RUNTIME_FUNCTION(Runtime_CompileString) {
HandleScope scope(isolate);
DCHECK(args.length() == 2);
CONVERT_ARG_HANDLE_CHECKED(String, source, 0);
CONVERT_BOOLEAN_ARG_CHECKED(function_literal_only, 1);
// Extract native context.
Handle<Context> context(isolate->native_context());
// Check if native context allows code generation from
// strings. Throw an exception if it doesn't.
if (context->allow_code_gen_from_strings()->IsFalse() &&
!CodeGenerationFromStringsAllowed(isolate, context)) {
Handle<Object> error_message =
context->ErrorMessageForCodeGenerationFromStrings();
THROW_NEW_ERROR_RETURN_FAILURE(
isolate,
NewEvalError(MessageTemplate::kCodeGenFromStrings, error_message));
}
// Compile source string in the native context.
ParseRestriction restriction = function_literal_only
? ONLY_SINGLE_FUNCTION_LITERAL
: NO_PARSE_RESTRICTION;
Handle<SharedFunctionInfo> outer_info(context->closure()->shared(), isolate);
Handle<JSFunction> fun;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, fun,
Compiler::GetFunctionFromEval(source, outer_info, context, SLOPPY,
restriction, RelocInfo::kNoPosition));
return *fun;
}
static ObjectPair CompileGlobalEval(Isolate* isolate, Handle<String> source,
Handle<SharedFunctionInfo> outer_info,
Handle<Object> receiver,
LanguageMode language_mode,
int scope_position) {
Handle<Context> context = Handle<Context>(isolate->context());
Handle<Context> native_context = Handle<Context>(context->native_context());
// Check if native context allows code generation from
// strings. Throw an exception if it doesn't.
if (native_context->allow_code_gen_from_strings()->IsFalse() &&
!CodeGenerationFromStringsAllowed(isolate, native_context)) {
Handle<Object> error_message =
native_context->ErrorMessageForCodeGenerationFromStrings();
Handle<Object> error;
MaybeHandle<Object> maybe_error = isolate->factory()->NewEvalError(
MessageTemplate::kCodeGenFromStrings, error_message);
if (maybe_error.ToHandle(&error)) isolate->Throw(*error);
return MakePair(isolate->heap()->exception(), NULL);
}
// Deal with a normal eval call with a string argument. Compile it
// and return the compiled function bound in the local context.
static const ParseRestriction restriction = NO_PARSE_RESTRICTION;
Handle<JSFunction> compiled;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate, compiled,
Compiler::GetFunctionFromEval(source, outer_info, context, language_mode,
restriction, scope_position),
MakePair(isolate->heap()->exception(), NULL));
return MakePair(*compiled, *receiver);
}
RUNTIME_FUNCTION_RETURN_PAIR(Runtime_ResolvePossiblyDirectEval) {
HandleScope scope(isolate);
DCHECK(args.length() == 6);
Handle<Object> callee = args.at<Object>(0);
// If "eval" didn't refer to the original GlobalEval, it's not a
// direct call to eval.
// (And even if it is, but the first argument isn't a string, just let
// execution default to an indirect call to eval, which will also return
// the first argument without doing anything).
if (*callee != isolate->native_context()->global_eval_fun() ||
!args[1]->IsString()) {
return MakePair(*callee, isolate->heap()->undefined_value());
}
DCHECK(args[4]->IsSmi());
DCHECK(is_valid_language_mode(args.smi_at(4)));
LanguageMode language_mode = static_cast<LanguageMode>(args.smi_at(4));
DCHECK(args[5]->IsSmi());
Handle<SharedFunctionInfo> outer_info(args.at<JSFunction>(2)->shared(),
isolate);
return CompileGlobalEval(isolate, args.at<String>(1), outer_info,
args.at<Object>(3), language_mode, args.smi_at(5));
}
} // namespace internal
} // namespace v8
| zhangf911/fibjs | vender/v8/src/runtime/runtime-compiler.cc | C++ | gpl-3.0 | 15,913 |
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfCacheFilter deals with page caching and action caching.
*
* @package symfony
* @subpackage filter
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfCacheFilter.class.php 13564 2008-11-30 21:34:25Z fabien $
*/
class sfCacheFilter extends sfFilter
{
protected
$cacheManager = null,
$request = null,
$response = null,
$routing = null,
$cache = array();
/**
* Initializes this Filter.
*
* @param sfContext $context The current application context
* @param array $parameters An associative array of initialization parameters
*
* @return bool true, if initialization completes successfully, otherwise false
*
* @throws <b>sfInitializationException</b> If an error occurs while initializing this Filter
*/
public function initialize($context, $parameters = array())
{
parent::initialize($context, $parameters);
$this->cacheManager = $context->getViewCacheManager();
$this->request = $context->getRequest();
$this->response = $context->getResponse();
$this->routing = $context->getRouting();
}
/**
* Executes this filter.
*
* @param sfFilterChain $filterChain A sfFilterChain instance
*/
public function execute($filterChain)
{
// execute this filter only once, if cache is set and no GET or POST parameters
if (!sfConfig::get('sf_cache'))
{
$filterChain->execute();
return;
}
if ($this->executeBeforeExecution())
{
$filterChain->execute();
}
$this->executeBeforeRendering();
}
public function executeBeforeExecution()
{
// register our cache configuration
$this->cacheManager->registerConfiguration($this->context->getModuleName());
$uri = $this->routing->getCurrentInternalUri();
if (is_null($uri))
{
return true;
}
// page cache
$cacheable = $this->cacheManager->isCacheable($uri);
if ($cacheable && $this->cacheManager->withLayout($uri))
{
$inCache = $this->cacheManager->getPageCache($uri);
$this->cache[$uri] = $inCache;
if ($inCache)
{
// page is in cache, so no need to run execution filter
return false;
}
}
return true;
}
/**
* Executes this filter.
*/
public function executeBeforeRendering()
{
// cache only 200 HTTP status
if (200 != $this->response->getStatusCode())
{
return;
}
$uri = $this->routing->getCurrentInternalUri();
// save page in cache
if (isset($this->cache[$uri]) && false === $this->cache[$uri])
{
$this->setCacheExpiration($uri);
$this->setCacheValidation($uri);
// set Vary headers
foreach ($this->cacheManager->getVary($uri, 'page') as $vary)
{
$this->response->addVaryHttpHeader($vary);
}
$this->cacheManager->setPageCache($uri);
}
// cache validation
$this->checkCacheValidation();
}
/**
* Sets cache expiration headers.
*
* @param string An internal URI
*/
protected function setCacheExpiration($uri)
{
// don't add cache expiration (Expires) if
// * the client lifetime is not set
// * the response already has a cache validation (Last-Modified header)
// * the Expires header has already been set
if (!$lifetime = $this->cacheManager->getClientLifeTime($uri, 'page'))
{
return;
}
if ($this->response->hasHttpHeader('Last-Modified'))
{
return;
}
if (!$this->response->hasHttpHeader('Expires'))
{
$this->response->setHttpHeader('Expires', $this->response->getDate(time() + $lifetime), false);
$this->response->addCacheControlHttpHeader('max-age', $lifetime);
}
}
/**
* Sets cache validation headers.
*
* @param string An internal URI
*/
protected function setCacheValidation($uri)
{
// don't add cache validation (Last-Modified) if
// * the client lifetime is set (cache.yml)
// * the response already has a Last-Modified header
if ($this->cacheManager->getClientLifeTime($uri, 'page'))
{
return;
}
if (!$this->response->hasHttpHeader('Last-Modified'))
{
$this->response->setHttpHeader('Last-Modified', $this->response->getDate(time()), false);
}
if (sfConfig::get('sf_etag'))
{
$etag = '"'.md5($this->response->getContent()).'"';
$this->response->setHttpHeader('ETag', $etag);
}
}
/**
* Checks cache validation headers.
*/
protected function checkCacheValidation()
{
// Etag support
if (sfConfig::get('sf_etag'))
{
$etag = '"'.md5($this->response->getContent()).'"';
if ($this->request->getHttpHeader('IF_NONE_MATCH') == $etag)
{
$this->response->setStatusCode(304);
$this->response->setHeaderOnly(true);
if (sfConfig::get('sf_logging_enabled'))
{
$this->context->getEventDispatcher()->notify(new sfEvent($this, 'application.log', array('ETag matches If-None-Match (send 304)')));
}
}
}
// conditional GET support
// never in debug mode
if ($this->response->hasHttpHeader('Last-Modified') && !sfConfig::get('sf_debug'))
{
$lastModified = $this->response->getHttpHeader('Last-Modified');
$lastModified = $lastModified[0];
if ($this->request->getHttpHeader('IF_MODIFIED_SINCE') == $lastModified)
{
$this->response->setStatusCode(304);
$this->response->setHeaderOnly(true);
if (sfConfig::get('sf_logging_enabled'))
{
$this->context->getEventDispatcher()->notify(new sfEvent($this, 'application.log', array('Last-Modified matches If-Modified-Since (send 304)')));
}
}
}
}
}
| sandaru1/codejam | www/lib/symfony/filter/sfCacheFilter.class.php | PHP | gpl-3.0 | 6,072 |
package org.apache.bcel.generic;
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache BCEL" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* "Apache BCEL", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import org.apache.bcel.Constants;
import org.apache.bcel.ExceptionConstants;
/**
* GETFIELD - Fetch field from object
* <PRE>Stack: ..., objectref -> ..., value</PRE>
* OR
* <PRE>Stack: ..., objectref -> ..., value.word1, value.word2</PRE>
*
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
* @version $Id: GETFIELD.java,v 1.2 2006/08/23 13:48:30 andos Exp $
*/
public class GETFIELD extends FieldInstruction
implements ExceptionThrower, StackConsumer, StackProducer {
/**
*
*/
private static final long serialVersionUID = -6510928743515082496L;
/**
* Empty constructor needed for the Class.newInstance() statement in
* Instruction.readInstruction(). Not to be used otherwise.
*/
GETFIELD() {
}
public GETFIELD(int index) {
super(Constants.GETFIELD, index);
}
public int produceStack(ConstantPoolGen cpg) {
return getFieldSize(cpg);
}
public Class[] getExceptions() {
Class[] cs = new Class[2 + ExceptionConstants.EXCS_FIELD_AND_METHOD_RESOLUTION.length];
System.arraycopy(ExceptionConstants.EXCS_FIELD_AND_METHOD_RESOLUTION, 0,
cs, 0, ExceptionConstants.EXCS_FIELD_AND_METHOD_RESOLUTION.length);
cs[ExceptionConstants.EXCS_FIELD_AND_METHOD_RESOLUTION.length + 1] =
ExceptionConstants.INCOMPATIBLE_CLASS_CHANGE_ERROR;
cs[ExceptionConstants.EXCS_FIELD_AND_METHOD_RESOLUTION.length] =
ExceptionConstants.NULL_POINTER_EXCEPTION;
return cs;
}
/**
* Call corresponding visitor method(s). The order is:
* Call visitor methods of implemented interfaces first, then
* call methods according to the class hierarchy in descending order,
* i.e., the most specific visitXXX() call comes last.
*
* @param v Visitor object
*/
public void accept(Visitor v) {
v.visitExceptionThrower(this);
v.visitStackConsumer(this);
v.visitStackProducer(this);
v.visitTypedInstruction(this);
v.visitLoadClass(this);
v.visitCPInstruction(this);
v.visitFieldOrMethod(this);
v.visitFieldInstruction(this);
v.visitGETFIELD(this);
}
}
| miuirussia/KJBE | src/org/apache/bcel/generic/GETFIELD.java | Java | gpl-3.0 | 4,938 |
exports.play = 'afplay';
exports.raise_volume = 'osascript -e "set Volume 10"'; // unmutes as well | prey/prey-node-client | lib/agent/actions/alarm/mac.js | JavaScript | gpl-3.0 | 98 |
package de.metas.ui.web.window.exceptions;
import org.adempiere.exceptions.AdempiereException;
import de.metas.ui.web.window.datatypes.DocumentPath;
import de.metas.ui.web.window.model.Document;
/*
* #%L
* metasfresh-webui-api
* %%
* Copyright (C) 2016 metas GmbH
* %%
* 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, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
@SuppressWarnings("serial")
public class InvalidDocumentStateException extends AdempiereException
{
public InvalidDocumentStateException(final Document document, final String reason)
{
super(buildMsg(document.getDocumentPath(), reason));
}
public InvalidDocumentStateException(final DocumentPath documentPath, final String reason)
{
super(buildMsg(documentPath, reason));
}
private static String buildMsg(final DocumentPath documentPath, final String reason)
{
return "Document " + documentPath + " state is invalid: " + reason;
}
}
| metasfresh/metasfresh-webui-api | src/main/java/de/metas/ui/web/window/exceptions/InvalidDocumentStateException.java | Java | gpl-3.0 | 1,498 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.ode;
import org.apache.commons.math3.RealFieldElement;
import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.MaxCountExceededException;
/**
* This interface allows users to add secondary differential equations to a primary
* set of differential equations.
* <p>
* In some cases users may need to integrate some problem-specific equations along
* with a primary set of differential equations. One example is optimal control where
* adjoined parameters linked to the minimized Hamiltonian must be integrated.
* </p>
* <p>
* This interface allows users to add such equations to a primary set of {@link
* FirstOrderFieldDifferentialEquations first order differential equations}
* thanks to the {@link FieldExpandableODE#addSecondaryEquations(FieldSecondaryEquations)}
* method.
* </p>
* @see FirstOrderFieldDifferentialEquations
* @see FieldExpandableODE
* @param <T> the type of the field elements
* @since 3.6
*/
public interface FieldSecondaryEquations<T extends RealFieldElement<T>> {
/** Get the dimension of the secondary state parameters.
* @return dimension of the secondary state parameters
*/
int getDimension();
/** Initialize equations at the start of an ODE integration.
* <p>
* This method is called once at the start of the integration. It
* may be used by the equations to initialize some internal data
* if needed.
* </p>
* @param t0 value of the independent <I>time</I> variable at integration start
* @param primary0 array containing the value of the primary state vector at integration start
* @param secondary0 array containing the value of the secondary state vector at integration start
* @param finalTime target time for the integration
*/
void init(T t0, T[] primary0, T[] secondary0, T finalTime);
/** Compute the derivatives related to the secondary state parameters.
* @param t current value of the independent <I>time</I> variable
* @param primary array containing the current value of the primary state vector
* @param primaryDot array containing the derivative of the primary state vector
* @param secondary array containing the current value of the secondary state vector
* @return derivative of the secondary state vector
* @exception MaxCountExceededException if the number of functions evaluations is exceeded
* @exception DimensionMismatchException if arrays dimensions do not match equations settings
*/
T[] computeDerivatives(T t, T[] primary, T[] primaryDot, T[] secondary)
throws MaxCountExceededException, DimensionMismatchException;
}
| happyjack27/autoredistrict | src/org/apache/commons/math3/ode/FieldSecondaryEquations.java | Java | gpl-3.0 | 3,524 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ja_JP" version="2.1">
<context>
<name>TestPlugin</name>
<message>
<location filename="../testplugin.cpp" line="122"/>
<source>Close</source>
<translation>閉じる</translation>
</message>
<message>
<location filename="../testplugin.cpp" line="133"/>
<source>Example Plugin Settings</source>
<translation>拡張の設定例</translation>
</message>
<message>
<location filename="../testplugin.cpp" line="163"/>
<source>My first plugin action</source>
<translation>拡張の動作確認</translation>
</message>
<message>
<location filename="../testplugin.cpp" line="178"/>
<source>Hello</source>
<translation>Hello</translation>
</message>
<message>
<location filename="../testplugin.cpp" line="178"/>
<source>First plugin action works :-)</source>
<translation>拡張の動作は正常です :-)</translation>
</message>
</context>
<context>
<name>TestPlugin_Sidebar</name>
<message>
<location filename="../testplugin_sidebar.cpp" line="32"/>
<location filename="../testplugin_sidebar.cpp" line="40"/>
<source>Testing Sidebar</source>
<translation>サイドバーを試す</translation>
</message>
</context>
</TS> | ThaFireDragonOfDeath/qupzilla | src/plugins/TestPlugin/translations/ja_JP.ts | TypeScript | gpl-3.0 | 1,372 |
using GitCommands;
using GitCommands.Utils;
namespace GitUI.CommandsDialogs.SettingsDialog.Pages
{
public partial class FormBrowseRepoSettingsPage : SettingsPageWithHeader
{
public FormBrowseRepoSettingsPage()
{
InitializeComponent();
Text = "Browse repository window";
Translate();
}
protected override void Init(ISettingsPageHost aPageHost)
{
base.Init(aPageHost);
BindSettingsWithControls();
}
protected override void SettingsToPage()
{
chkShowRevisionInfoNextToRevisionGrid.Checked = AppSettings.ShowRevisionInfoNextToRevisionGrid;
chkShowRevisionInfoNextToRevisionGrid.Visible = !EnvUtils.IsMonoRuntime();
base.SettingsToPage();
}
protected override void PageToSettings()
{
AppSettings.ShowRevisionInfoNextToRevisionGrid = chkShowRevisionInfoNextToRevisionGrid.Checked;
base.PageToSettings();
}
private void BindSettingsWithControls()
{
AddSettingBinding(AppSettings.ShowConEmuTab, chkChowConsoleTab);
AddSettingBinding(AppSettings.ConEmuStyle, _NO_TRANSLATE_cboStyle);
AddSettingBinding(AppSettings.ConEmuTerminal, cboTerminal);
AddSettingBinding(AppSettings.ConEmuFontSize, cboFontSize);
AddSettingBinding(AppSettings.ShowGpgInformation, chkShowGpgInformation);
}
private void chkChowConsoleTab_CheckedChanged(object sender, System.EventArgs e)
{
groupBoxConsoleSettings.Enabled = chkChowConsoleTab.Checked;
}
public static SettingsPageReference GetPageReference()
{
return new SettingsPageReferenceByType(typeof(FormBrowseRepoSettingsPage));
}
}
}
| gencer/gitextensions | GitUI/CommandsDialogs/SettingsDialog/Pages/FormBrowseRepoSettingsPage.cs | C# | gpl-3.0 | 1,850 |
/*
* 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.mycompany.mavenTimesheet;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| niuran1993/Deskera-HRMS | mavenTimesheet/src/test/java/com/mycompany/mavenTimesheet/AppTest.java | Java | gpl-3.0 | 1,470 |
#region using directives
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using PoGo.NecroBot.Logic.Event;
using PoGo.NecroBot.Logic.Logging;
using PoGo.NecroBot.Logic.Model.Settings;
using PokemonGo.RocketAPI.Exceptions;
#endregion
namespace PoGo.NecroBot.Logic.State
{
public class StateMachine
{
private IState _initialState;
public Task AsyncStart(IState initialState, Session session, string subPath,
CancellationToken cancellationToken = default(CancellationToken))
{
return Task.Run(() => Start(initialState, session, subPath, cancellationToken), cancellationToken);
}
public void SetFailureState(IState state)
{
_initialState = state;
}
public async Task Start(IState initialState, Session session, string subPath,
CancellationToken cancellationToken = default(CancellationToken))
{
var state = initialState;
var profilePath = Path.Combine(Directory.GetCurrentDirectory(), subPath);
var profileConfigPath = Path.Combine(profilePath, "config");
FileSystemWatcher configWatcher = new FileSystemWatcher();
configWatcher.Path = profileConfigPath;
configWatcher.Filter = "config.json";
configWatcher.NotifyFilter = NotifyFilters.LastWrite;
configWatcher.EnableRaisingEvents = true;
configWatcher.Changed += (sender, e) =>
{
if (e.ChangeType == WatcherChangeTypes.Changed)
{
session.LogicSettings = new LogicSettings(GlobalSettings.Load(subPath));
configWatcher.EnableRaisingEvents = !configWatcher.EnableRaisingEvents;
configWatcher.EnableRaisingEvents = !configWatcher.EnableRaisingEvents;
Logger.Write(" ##### config.json ##### ", LogLevel.Info);
}
};
do
{
try
{
state = await state.Execute(session, cancellationToken);
}
catch (InvalidResponseException)
{
session.EventDispatcher.Send(new ErrorEvent
{
Message = "Niantic Servers unstable, throttling API Calls."
});
}
catch (OperationCanceledException)
{
session.EventDispatcher.Send(new ErrorEvent {Message = "Current Operation was canceled."});
state = _initialState;
}
catch (Exception ex)
{
session.EventDispatcher.Send(new ErrorEvent {Message = "Pokemon Servers might be offline / unstable. Trying again..."});
Thread.Sleep(1000);
session.EventDispatcher.Send(new ErrorEvent { Message = "Error: " + ex });
state = _initialState;
}
} while (state != null);
configWatcher.EnableRaisingEvents = false;
configWatcher.Dispose();
}
}
} | jjskuld/NecroBot | PoGo.NecroBot.Logic/State/StateMachine.cs | C# | gpl-3.0 | 3,212 |
module Genome
module Importers
module DSL
module WithDrugsAndGenes
attr_accessor :gene_claim, :drug_claim
def initialize(item_id, importer_instance, row_instance)
super(item_id, importer_instance, row_instance, 'interaction_claim')
end
def gene(column, opts = {}, &block)
opts = @defaults.merge opts
val = opts[:transform].call(@row.send(column))
if !opts[:unless].call(val)
@gene_claim_id = @importer.create_gene_claim(name: val, nomenclature: opts[:nomenclature])
node = GeneNode.new(@gene_claim_id, @importer, @row)
node.instance_eval(&block)
end
end
def drug(column, opts = {}, &block)
opts = @defaults.merge opts
val = opts[:transform].call(@row.send(column))
if !opts[:unless].call(val)
@drug_claim_id = @importer.create_drug_claim(name: val, nomenclature: opts[:nomenclature], primary_name: opts[:transform].call(@row.send(opts[:primary_name])))
node = DrugNode.new(@drug_claim_id, @importer, @row)
node.instance_eval(&block)
end
end
end
end
end
end
| genome/dgi-db | lib/genome/importers/dsl/with_drugs_and_genes.rb | Ruby | gpl-3.0 | 1,201 |
package buildcraftAdditions.ModIntegration.Buildcraft.Triggers;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.ForgeDirection;
import buildcraft.api.statements.IStatementContainer;
import buildcraft.api.statements.IStatementParameter;
import buildcraftAdditions.tileEntities.TileChargingStation;
/**
* Copyright (c) 2014, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Buildcraft Additions is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class TriggerDoneCharging extends BasicTrigger {
public TriggerDoneCharging() {
super("doneCharging", "TriggerDoneCharging");
}
@Override
public boolean isTriggerActive(TileEntity target, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) {
if (target instanceof TileChargingStation) {
TileChargingStation chargingStation = (TileChargingStation) target;
return chargingStation.getProgress() == 1;
}
return false;
}
}
| AEnterprise/Buildcraft-Additions | src/main/java/buildcraftAdditions/ModIntegration/Buildcraft/Triggers/TriggerDoneCharging.java | Java | gpl-3.0 | 1,093 |
/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
#include "AP_BattMonitor.h"
#include "AP_BattMonitor_Analog.h"
#include "AP_BattMonitor_SMBus.h"
#include "AP_BattMonitor_Bebop.h"
extern const AP_HAL::HAL& hal;
const AP_Param::GroupInfo AP_BattMonitor::var_info[] = {
// @Param: _MONITOR
// @DisplayName: Battery monitoring
// @Description: Controls enabling monitoring of the battery's voltage and current
// @Values: 0:Disabled,3:Analog Voltage Only,4:Analog Voltage and Current,5:SMBus,6:Bebop
// @User: Standard
AP_GROUPINFO("_MONITOR", 0, AP_BattMonitor, _monitoring[0], BattMonitor_TYPE_NONE),
// @Param: _VOLT_PIN
// @DisplayName: Battery Voltage sensing pin
// @Description: Setting this to 0 ~ 13 will enable battery voltage sensing on pins A0 ~ A13. For the 3DR power brick on APM2.5 it should be set to 13. On the PX4 it should be set to 100. On the Pixhawk powered from the PM connector it should be set to 2.
// @Values: -1:Disabled, 0:A0, 1:A1, 2:Pixhawk, 13:A13, 100:PX4
// @User: Standard
AP_GROUPINFO("_VOLT_PIN", 1, AP_BattMonitor, _volt_pin[0], AP_BATT_VOLT_PIN),
// @Param: _CURR_PIN
// @DisplayName: Battery Current sensing pin
// @Description: Setting this to 0 ~ 13 will enable battery current sensing on pins A0 ~ A13. For the 3DR power brick on APM2.5 it should be set to 12. On the PX4 it should be set to 101. On the Pixhawk powered from the PM connector it should be set to 3.
// @Values: -1:Disabled, 1:A1, 2:A2, 3:Pixhawk, 12:A12, 101:PX4
// @User: Standard
AP_GROUPINFO("_CURR_PIN", 2, AP_BattMonitor, _curr_pin[0], AP_BATT_CURR_PIN),
// @Param: _VOLT_MULT
// @DisplayName: Voltage Multiplier
// @Description: Used to convert the voltage of the voltage sensing pin (BATT_VOLT_PIN) to the actual battery's voltage (pin_voltage * VOLT_MULT). For the 3DR Power brick on APM2 or Pixhawk, this should be set to 10.1. For the Pixhawk with the 3DR 4in1 ESC this should be 12.02. For the PX4 using the PX4IO power supply this should be set to 1.
// @User: Advanced
AP_GROUPINFO("_VOLT_MULT", 3, AP_BattMonitor, _volt_multiplier[0], AP_BATT_VOLTDIVIDER_DEFAULT),
// @Param: _AMP_PERVOLT
// @DisplayName: Amps per volt
// @Description: Number of amps that a 1V reading on the current sensor corresponds to. On the APM2 or Pixhawk using the 3DR Power brick this should be set to 17. For the Pixhawk with the 3DR 4in1 ESC this should be 17.
// @Units: Amps/Volt
// @User: Standard
AP_GROUPINFO("_AMP_PERVOLT", 4, AP_BattMonitor, _curr_amp_per_volt[0], AP_BATT_CURR_AMP_PERVOLT_DEFAULT),
// @Param: _AMP_OFFSET
// @DisplayName: AMP offset
// @Description: Voltage offset at zero current on current sensor
// @Units: Volts
// @User: Standard
AP_GROUPINFO("_AMP_OFFSET", 5, AP_BattMonitor, _curr_amp_offset[0], 0),
// @Param: _CAPACITY
// @DisplayName: Battery capacity
// @Description: Capacity of the battery in mAh when full
// @Units: mAh
// @Increment: 50
// @User: Standard
AP_GROUPINFO("_CAPACITY", 6, AP_BattMonitor, _pack_capacity[0], AP_BATT_CAPACITY_DEFAULT),
// 7 & 8 were used for VOLT2_PIN and VOLT2_MULT
#if APM_BUILD_TYPE(APM_BUILD_ArduPlane)
// @Param: _WATT_MAX
// @DisplayName: Maximum allowed power (Watts)
// @Description: If battery wattage (voltage * current) exceeds this value then the system will reduce max throttle (THR_MAX, TKOFF_THR_MAX and THR_MIN for reverse thrust) to satisfy this limit. This helps limit high current to low C rated batteries regardless of battery voltage. The max throttle will slowly grow back to THR_MAX (or TKOFF_THR_MAX ) and THR_MIN if demanding the current max and under the watt max. Use 0 to disable.
// @Units: Watts
// @Increment: 1
// @User: Advanced
AP_GROUPINFO("_WATT_MAX", 9, AP_BattMonitor, _watt_max[0], AP_BATT_MAX_WATT_DEFAULT),
#endif
// 10 is left for future expansion
#if AP_BATT_MONITOR_MAX_INSTANCES > 1
// @Param: 2_MONITOR
// @DisplayName: Battery monitoring
// @Description: Controls enabling monitoring of the battery's voltage and current
// @Values: 0:Disabled,3:Analog Voltage Only,4:Analog Voltage and Current,5:SMBus,6:Bebop
// @User: Standard
AP_GROUPINFO("2_MONITOR", 11, AP_BattMonitor, _monitoring[1], BattMonitor_TYPE_NONE),
// @Param: 2_VOLT_PIN
// @DisplayName: Battery Voltage sensing pin
// @Description: Setting this to 0 ~ 13 will enable battery voltage sensing on pins A0 ~ A13. For the 3DR power brick on APM2.5 it should be set to 13. On the PX4 it should be set to 100. On the Pixhawk powered from the PM connector it should be set to 2.
// @Values: -1:Disabled, 0:A0, 1:A1, 2:Pixhawk, 13:A13, 100:PX4
// @User: Standard
AP_GROUPINFO("2_VOLT_PIN", 12, AP_BattMonitor, _volt_pin[1], AP_BATT_VOLT_PIN),
// @Param: 2_CURR_PIN
// @DisplayName: Battery Current sensing pin
// @Description: Setting this to 0 ~ 13 will enable battery current sensing on pins A0 ~ A13. For the 3DR power brick on APM2.5 it should be set to 12. On the PX4 it should be set to 101. On the Pixhawk powered from the PM connector it should be set to 3.
// @Values: -1:Disabled, 1:A1, 2:A2, 3:Pixhawk, 12:A12, 101:PX4
// @User: Standard
AP_GROUPINFO("2_CURR_PIN", 13, AP_BattMonitor, _curr_pin[1], AP_BATT_CURR_PIN),
// @Param: 2_VOLT_MULT
// @DisplayName: Voltage Multiplier
// @Description: Used to convert the voltage of the voltage sensing pin (BATT_VOLT_PIN) to the actual battery's voltage (pin_voltage * VOLT_MULT). For the 3DR Power brick on APM2 or Pixhawk, this should be set to 10.1. For the Pixhawk with the 3DR 4in1 ESC this should be 12.02. For the PX4 using the PX4IO power supply this should be set to 1.
// @User: Advanced
AP_GROUPINFO("2_VOLT_MULT", 14, AP_BattMonitor, _volt_multiplier[1], AP_BATT_VOLTDIVIDER_DEFAULT),
// @Param: 2_AMP_PERVOL
// @DisplayName: Amps per volt
// @Description: Number of amps that a 1V reading on the current sensor corresponds to. On the APM2 or Pixhawk using the 3DR Power brick this should be set to 17. For the Pixhawk with the 3DR 4in1 ESC this should be 17.
// @Units: Amps/Volt
// @User: Standard
AP_GROUPINFO("2_AMP_PERVOL", 15, AP_BattMonitor, _curr_amp_per_volt[1], AP_BATT_CURR_AMP_PERVOLT_DEFAULT),
// @Param: 2_AMP_OFFSET
// @DisplayName: AMP offset
// @Description: Voltage offset at zero current on current sensor
// @Units: Volts
// @User: Standard
AP_GROUPINFO("2_AMP_OFFSET", 16, AP_BattMonitor, _curr_amp_offset[1], 0),
// @Param: 2_CAPACITY
// @DisplayName: Battery capacity
// @Description: Capacity of the battery in mAh when full
// @Units: mAh
// @Increment: 50
// @User: Standard
AP_GROUPINFO("2_CAPACITY", 17, AP_BattMonitor, _pack_capacity[1], AP_BATT_CAPACITY_DEFAULT),
#if APM_BUILD_TYPE(APM_BUILD_ArduPlane)
// @Param: 2_WATT_MAX
// @DisplayName: Maximum allowed current
// @Description: If battery wattage (voltage * current) exceeds this value then the system will reduce max throttle (THR_MAX, TKOFF_THR_MAX and THR_MIN for reverse thrust) to satisfy this limit. This helps limit high current to low C rated batteries regardless of battery voltage. The max throttle will slowly grow back to THR_MAX (or TKOFF_THR_MAX ) and THR_MIN if demanding the current max and under the watt max. Use 0 to disable.
// @Units: Amps
// @Increment: 1
// @User: Advanced
AP_GROUPINFO("2_WATT_MAX", 18, AP_BattMonitor, _watt_max[1], AP_BATT_MAX_WATT_DEFAULT),
#endif
#endif // AP_BATT_MONITOR_MAX_INSTANCES > 1
AP_GROUPEND
};
// Default constructor.
// Note that the Vector/Matrix constructors already implicitly zero
// their values.
//
AP_BattMonitor::AP_BattMonitor(void) :
_num_instances(0)
{
AP_Param::setup_object_defaults(this, var_info);
}
// init - instantiate the battery monitors
void
AP_BattMonitor::init()
{
// check init has not been called before
if (_num_instances != 0) {
return;
}
#if CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_BEBOP || CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_DISCO
// force monitor for bebop
_monitoring[0] = BattMonitor_TYPE_BEBOP;
#endif
// create each instance
for (uint8_t instance=0; instance<AP_BATT_MONITOR_MAX_INSTANCES; instance++) {
uint8_t monitor_type = _monitoring[instance];
switch (monitor_type) {
case BattMonitor_TYPE_ANALOG_VOLTAGE_ONLY:
case BattMonitor_TYPE_ANALOG_VOLTAGE_AND_CURRENT:
state[instance].instance = instance;
drivers[instance] = new AP_BattMonitor_Analog(*this, instance, state[instance]);
_num_instances++;
break;
case BattMonitor_TYPE_SMBUS:
state[instance].instance = instance;
#if CONFIG_HAL_BOARD == HAL_BOARD_PX4
drivers[instance] = new AP_BattMonitor_SMBus_PX4(*this, instance, state[instance]);
#else
drivers[instance] = new AP_BattMonitor_SMBus_I2C(*this, instance, state[instance]);
#endif
_num_instances++;
break;
case BattMonitor_TYPE_BEBOP:
#if CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_BEBOP || CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_DISCO
state[instance].instance = instance;
drivers[instance] = new AP_BattMonitor_Bebop(*this, instance, state[instance]);
_num_instances++;
#endif
break;
}
// call init function for each backend
if (drivers[instance] != NULL) {
drivers[instance]->init();
}
}
}
// read - read the voltage and current for all instances
void
AP_BattMonitor::read()
{
for (uint8_t i=0; i<_num_instances; i++) {
if (drivers[i] != NULL && _monitoring[i] != BattMonitor_TYPE_NONE) {
drivers[i]->read();
}
}
}
// healthy - returns true if monitor is functioning
bool AP_BattMonitor::healthy(uint8_t instance) const {
return instance < _num_instances && _BattMonitor_STATE(instance).healthy;
}
bool AP_BattMonitor::is_powering_off(uint8_t instance) const {
return instance < _num_instances && _BattMonitor_STATE(instance).is_powering_off;
}
/// has_current - returns true if battery monitor instance provides current info
bool AP_BattMonitor::has_current(uint8_t instance) const
{
// check for analog voltage and current monitor or smbus monitor
if (instance < _num_instances && drivers[instance] != NULL) {
return (_monitoring[instance] == BattMonitor_TYPE_ANALOG_VOLTAGE_AND_CURRENT ||
_monitoring[instance] == BattMonitor_TYPE_SMBUS ||
_monitoring[instance] == BattMonitor_TYPE_BEBOP);
}
// not monitoring current
return false;
}
/// voltage - returns battery voltage in volts
float AP_BattMonitor::voltage(uint8_t instance) const
{
if (instance < _num_instances) {
return _BattMonitor_STATE(instance).voltage;
} else {
return 0.0f;
}
}
/// current_amps - returns the instantaneous current draw in amperes
float AP_BattMonitor::current_amps(uint8_t instance) const {
if (instance < _num_instances) {
return _BattMonitor_STATE(instance).current_amps;
} else {
return 0.0f;
}
}
/// current_total_mah - returns total current drawn since start-up in amp-hours
float AP_BattMonitor::current_total_mah(uint8_t instance) const {
if (instance < _num_instances) {
return _BattMonitor_STATE(instance).current_total_mah;
} else {
return 0.0f;
}
}
/// capacity_remaining_pct - returns the % battery capacity remaining (0 ~ 100)
uint8_t AP_BattMonitor::capacity_remaining_pct(uint8_t instance) const
{
if (instance < _num_instances && drivers[instance] != NULL) {
return drivers[instance]->capacity_remaining_pct();
} else {
return 0;
}
}
/// exhausted - returns true if the voltage remains below the low_voltage for 10 seconds or remaining capacity falls below min_capacity_mah
bool AP_BattMonitor::exhausted(uint8_t instance, float low_voltage, float min_capacity_mah)
{
// exit immediately if no monitors setup
if (_num_instances == 0 || instance >= _num_instances) {
return false;
}
// check voltage
if ((state[instance].voltage > 0) && (low_voltage > 0) && (state[instance].voltage < low_voltage)) {
// this is the first time our voltage has dropped below minimum so start timer
if (state[instance].low_voltage_start_ms == 0) {
state[instance].low_voltage_start_ms = AP_HAL::millis();
} else if (AP_HAL::millis() - state[instance].low_voltage_start_ms > AP_BATT_LOW_VOLT_TIMEOUT_MS) {
return true;
}
} else {
// acceptable voltage so reset timer
state[instance].low_voltage_start_ms = 0;
}
// check capacity if current monitoring is enabled
if (has_current(instance) && (min_capacity_mah > 0) && (_pack_capacity[instance] - state[instance].current_total_mah < min_capacity_mah)) {
return true;
}
// if we've gotten this far then battery is ok
return false;
}
#if APM_BUILD_TYPE(APM_BUILD_ArduPlane)
// return true if any battery is pushing too much power
bool AP_BattMonitor::overpower_detected() const
{
bool result = false;
for (int instance = 0; instance < _num_instances; instance++) {
result |= overpower_detected(instance);
}
return result;
}
bool AP_BattMonitor::overpower_detected(uint8_t instance) const
{
if (instance < _num_instances && _watt_max[instance] > 0) {
float power = _BattMonitor_STATE(instance).current_amps * _BattMonitor_STATE(instance).voltage;
return _BattMonitor_STATE(instance).healthy && (power > _watt_max[instance]);
}
return false;
}
#endif
| Boyang--Li/ardupilot | libraries/AP_BattMonitor/AP_BattMonitor.cpp | C++ | gpl-3.0 | 14,002 |
using uint8_t = System.Byte;
using uint16_t = System.UInt16;
using uint32_t = System.UInt32;
using uint64_t = System.UInt64;
using int8_t = System.SByte;
using int16_t = System.Int16;
using int32_t = System.Int32;
using int64_t = System.Int64;
using float32 = System.Single;
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Collections.Generic;
namespace DroneCAN
{
public partial class DroneCAN {
static void encode_uavcan_protocol_debug_LogLevel(uavcan_protocol_debug_LogLevel msg, dronecan_serializer_chunk_cb_ptr_t chunk_cb, object ctx) {
uint8_t[] buffer = new uint8_t[8];
_encode_uavcan_protocol_debug_LogLevel(buffer, msg, chunk_cb, ctx, true);
}
static uint32_t decode_uavcan_protocol_debug_LogLevel(CanardRxTransfer transfer, uavcan_protocol_debug_LogLevel msg) {
uint32_t bit_ofs = 0;
_decode_uavcan_protocol_debug_LogLevel(transfer, ref bit_ofs, msg, true);
return (bit_ofs+7)/8;
}
static void _encode_uavcan_protocol_debug_LogLevel(uint8_t[] buffer, uavcan_protocol_debug_LogLevel msg, dronecan_serializer_chunk_cb_ptr_t chunk_cb, object ctx, bool tao) {
memset(buffer,0,8);
canardEncodeScalar(buffer, 0, 3, msg.value);
chunk_cb(buffer, 3, ctx);
}
static void _decode_uavcan_protocol_debug_LogLevel(CanardRxTransfer transfer,ref uint32_t bit_ofs, uavcan_protocol_debug_LogLevel msg, bool tao) {
canardDecodeScalar(transfer, bit_ofs, 3, false, ref msg.value);
bit_ofs += 3;
}
}
}
| ArduPilot/MissionPlanner | ExtLibs/DroneCAN/out/src/uavcan.protocol.debug.LogLevel.cs | C# | gpl-3.0 | 1,660 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014, Regents of the University of California,
* Arizona Board of Regents,
* Colorado State University,
* University Pierre & Marie Curie, Sorbonne University,
* Washington University in St. Louis,
* Beijing Institute of Technology,
* The University of Memphis
*
* This file is part of NFD (Named Data Networking Forwarding Daemon).
* See AUTHORS.md for complete list of NFD authors and contributors.
*
* NFD 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.
*
* NFD 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
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Jerald Paul Abraham <jeraldabraham@email.arizona.edu>
*/
#include "version.hpp"
#include <ndn-cxx/face.hpp>
#include <ndn-cxx/name.hpp>
#include <ndn-cxx/interest.hpp>
#include <ndn-cxx/encoding/buffer-stream.hpp>
#include <ndn-cxx/management/nfd-forwarder-status.hpp>
#include <ndn-cxx/management/nfd-channel-status.hpp>
#include <ndn-cxx/management/nfd-face-status.hpp>
#include <ndn-cxx/management/nfd-fib-entry.hpp>
#include <ndn-cxx/management/nfd-rib-entry.hpp>
#include <ndn-cxx/management/nfd-strategy-choice.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <list>
namespace ndn {
class NfdStatus
{
public:
explicit
NfdStatus(char* toolName)
: m_toolName(toolName)
, m_needVersionRetrieval(false)
, m_needChannelStatusRetrieval(false)
, m_needFaceStatusRetrieval(false)
, m_needFibEnumerationRetrieval(false)
, m_needRibStatusRetrieval(false)
, m_needStrategyChoiceRetrieval(false)
, m_isOutputXml(false)
{
}
void
usage()
{
std::cout << "Usage: \n " << m_toolName << " [options]\n\n"
"Show NFD version and status information\n\n"
"Options:\n"
" [-h] - print this help message\n"
" [-v] - retrieve version information\n"
" [-c] - retrieve channel status information\n"
" [-f] - retrieve face status information\n"
" [-b] - retrieve FIB information\n"
" [-r] - retrieve RIB information\n"
" [-s] - retrieve configured strategy choice for NDN namespaces\n"
" [-x] - output NFD status information in XML format\n"
"\n"
" [-V] - show version information of nfd-status and exit\n"
"\n"
"If no options are provided, all information is retrieved.\n"
"If -x is provided, other options(-v, -c, etc.) are ignored, and all information is printed in XML format.\n"
;
}
void
enableVersionRetrieval()
{
m_needVersionRetrieval = true;
}
void
enableChannelStatusRetrieval()
{
m_needChannelStatusRetrieval = true;
}
void
enableFaceStatusRetrieval()
{
m_needFaceStatusRetrieval = true;
}
void
enableFibEnumerationRetrieval()
{
m_needFibEnumerationRetrieval = true;
}
void
enableStrategyChoiceRetrieval()
{
m_needStrategyChoiceRetrieval = true;
}
void
enableRibStatusRetrieval()
{
m_needRibStatusRetrieval = true;
}
void
enableXmlOutput()
{
m_isOutputXml = true;
}
void
onTimeout()
{
std::cerr << "Request timed out" << std::endl;
runNextStep();
}
void
fetchSegments(const Data& data, void (NfdStatus::*onDone)())
{
m_buffer->write((const char*)data.getContent().value(),
data.getContent().value_size());
uint64_t currentSegment = data.getName().get(-1).toSegment();
const name::Component& finalBlockId = data.getMetaInfo().getFinalBlockId();
if (finalBlockId.empty() ||
finalBlockId.toSegment() > currentSegment)
{
m_face.expressInterest(data.getName().getPrefix(-1).appendSegment(currentSegment+1),
bind(&NfdStatus::fetchSegments, this, _2, onDone),
bind(&NfdStatus::onTimeout, this));
}
else
{
return (this->*onDone)();
}
}
void
escapeSpecialCharacters(std::string *data)
{
using boost::algorithm::replace_all;
replace_all(*data, "&", "&");
replace_all(*data, "\"", """);
replace_all(*data, "\'", "'");
replace_all(*data, "<", "<");
replace_all(*data, ">", ">");
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
void
fetchVersionInformation()
{
Interest interest("/localhost/nfd/status");
interest.setChildSelector(1);
interest.setMustBeFresh(true);
m_face.expressInterest(
interest,
bind(&NfdStatus::afterFetchedVersionInformation, this, _2),
bind(&NfdStatus::onTimeout, this));
}
void
afterFetchedVersionInformation(const Data& data)
{
nfd::ForwarderStatus status(data.getContent());
std::string nfdId;
if (data.getSignature().hasKeyLocator())
{
const ndn::KeyLocator& locator = data.getSignature().getKeyLocator();
if (locator.getType() == KeyLocator::KeyLocator_Name)
nfdId = locator.getName().toUri();
//todo: KeyDigest supporting
}
if (m_isOutputXml)
{
std::cout << "<generalStatus>";
std::cout << "<nfdId>"
<< nfdId << "</nfdId>";
std::cout << "<version>"
<< status.getNfdVersion() << "</version>";
std::cout << "<startTime>"
<< time::toString(status.getStartTimestamp(), "%Y-%m-%dT%H:%M:%S%F")
<< "</startTime>";
std::cout << "<currentTime>"
<< time::toString(status.getCurrentTimestamp(), "%Y-%m-%dT%H:%M:%S%F")
<< "</currentTime>";
std::cout << "<uptime>PT"
<< time::duration_cast<time::seconds>(status.getCurrentTimestamp()
- status.getStartTimestamp()).count()
<< "S</uptime>";
std::cout << "<nNameTreeEntries>" << status.getNNameTreeEntries()
<< "</nNameTreeEntries>";
std::cout << "<nFibEntries>" << status.getNFibEntries()
<< "</nFibEntries>";
std::cout << "<nPitEntries>" << status.getNPitEntries()
<< "</nPitEntries>";
std::cout << "<nMeasurementsEntries>" << status.getNMeasurementsEntries()
<< "</nMeasurementsEntries>";
std::cout << "<nCsEntries>" << status.getNCsEntries()
<< "</nCsEntries>";
std::cout << "<packetCounters>";
std::cout << "<incomingPackets>";
std::cout << "<nInterests>" << status.getNInInterests()
<< "</nInterests>";
std::cout << "<nDatas>" << status.getNInDatas()
<< "</nDatas>";
std::cout << "</incomingPackets>";
std::cout << "<outgoingPackets>";
std::cout << "<nInterests>" << status.getNOutInterests()
<< "</nInterests>";
std::cout << "<nDatas>" << status.getNOutDatas()
<< "</nDatas>";
std::cout << "</outgoingPackets>";
std::cout << "</packetCounters>";
std::cout << "</generalStatus>";
}
else
{
std::cout << "General NFD status:" << std::endl;
std::cout << " nfdId="
<< nfdId << std::endl;
std::cout << " version="
<< status.getNfdVersion() << std::endl;
std::cout << " startTime="
<< time::toIsoString(status.getStartTimestamp()) << std::endl;
std::cout << " currentTime="
<< time::toIsoString(status.getCurrentTimestamp()) << std::endl;
std::cout << " uptime="
<< time::duration_cast<time::seconds>(status.getCurrentTimestamp()
- status.getStartTimestamp()) << std::endl;
std::cout << " nNameTreeEntries=" << status.getNNameTreeEntries() << std::endl;
std::cout << " nFibEntries=" << status.getNFibEntries() << std::endl;
std::cout << " nPitEntries=" << status.getNPitEntries() << std::endl;
std::cout << " nMeasurementsEntries=" << status.getNMeasurementsEntries() << std::endl;
std::cout << " nCsEntries=" << status.getNCsEntries() << std::endl;
std::cout << " nInInterests=" << status.getNInInterests() << std::endl;
std::cout << " nOutInterests=" << status.getNOutInterests() << std::endl;
std::cout << " nInDatas=" << status.getNInDatas() << std::endl;
std::cout << " nOutDatas=" << status.getNOutDatas() << std::endl;
}
runNextStep();
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
void
fetchChannelStatusInformation()
{
m_buffer = make_shared<OBufferStream>();
Interest interest("/localhost/nfd/faces/channels");
interest.setChildSelector(1);
interest.setMustBeFresh(true);
m_face.expressInterest(interest,
bind(&NfdStatus::fetchSegments, this, _2,
&NfdStatus::afterFetchedChannelStatusInformation),
bind(&NfdStatus::onTimeout, this));
}
void
afterFetchedChannelStatusInformation()
{
ConstBufferPtr buf = m_buffer->buf();
if (m_isOutputXml)
{
std::cout << "<channels>";
Block block;
size_t offset = 0;
while (offset < buf->size())
{
bool ok = Block::fromBuffer(buf, offset, block);
if (!ok)
{
std::cerr << "ERROR: cannot decode ChannelStatus TLV" << std::endl;
break;
}
offset += block.size();
nfd::ChannelStatus channelStatus(block);
std::cout << "<channel>";
std::string localUri(channelStatus.getLocalUri());
escapeSpecialCharacters(&localUri);
std::cout << "<localUri>" << localUri << "</localUri>";
std::cout << "</channel>";
}
std::cout << "</channels>";
}
else
{
std::cout << "Channels:" << std::endl;
Block block;
size_t offset = 0;
while (offset < buf->size())
{
bool ok = Block::fromBuffer(buf, offset, block);
if (!ok)
{
std::cerr << "ERROR: cannot decode ChannelStatus TLV" << std::endl;
break;
}
offset += block.size();
nfd::ChannelStatus channelStatus(block);
std::cout << " " << channelStatus.getLocalUri() << std::endl;
}
}
runNextStep();
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
void
fetchFaceStatusInformation()
{
m_buffer = make_shared<OBufferStream>();
Interest interest("/localhost/nfd/faces/list");
interest.setChildSelector(1);
interest.setMustBeFresh(true);
m_face.expressInterest(interest,
bind(&NfdStatus::fetchSegments, this, _2,
&NfdStatus::afterFetchedFaceStatusInformation),
bind(&NfdStatus::onTimeout, this));
}
void
afterFetchedFaceStatusInformation()
{
ConstBufferPtr buf = m_buffer->buf();
if (m_isOutputXml)
{
std::cout << "<faces>";
Block block;
size_t offset = 0;
while (offset < buf->size())
{
bool ok = Block::fromBuffer(buf, offset, block);
if (!ok)
{
std::cerr << "ERROR: cannot decode FaceStatus TLV" << std::endl;
break;
}
offset += block.size();
nfd::FaceStatus faceStatus(block);
std::cout << "<face>";
std::cout << "<faceId>" << faceStatus.getFaceId() << "</faceId>";
std::string remoteUri(faceStatus.getRemoteUri());
escapeSpecialCharacters(&remoteUri);
std::cout << "<remoteUri>" << remoteUri << "</remoteUri>";
std::string localUri(faceStatus.getLocalUri());
escapeSpecialCharacters(&localUri);
std::cout << "<localUri>" << localUri << "</localUri>";
if (faceStatus.hasExpirationPeriod()) {
std::cout << "<expirationPeriod>PT"
<< time::duration_cast<time::seconds>(faceStatus.getExpirationPeriod())
.count() << "S"
<< "</expirationPeriod>";
}
std::cout << "<packetCounters>";
std::cout << "<incomingPackets>";
std::cout << "<nInterests>" << faceStatus.getNInInterests()
<< "</nInterests>";
std::cout << "<nDatas>" << faceStatus.getNInDatas()
<< "</nDatas>";
std::cout << "</incomingPackets>";
std::cout << "<outgoingPackets>";
std::cout << "<nInterests>" << faceStatus.getNOutInterests()
<< "</nInterests>";
std::cout << "<nDatas>" << faceStatus.getNOutDatas()
<< "</nDatas>";
std::cout << "</outgoingPackets>";
std::cout << "</packetCounters>";
std::cout << "<byteCounters>";
std::cout << "<incomingBytes>" << faceStatus.getNInBytes()
<< "</incomingBytes>";
std::cout << "<outgoingBytes>" << faceStatus.getNOutBytes()
<< "</outgoingBytes>";
std::cout << "</byteCounters>";
if (faceStatus.getFlags() != 0) {
std::cout << "<flags>";
if (faceStatus.isLocal()) {
std::cout << "<local/>";
}
if (faceStatus.isOnDemand()) {
std::cout << "<on-demand/>";
}
std::cout << "</flags>";
}
std::cout << "</face>";
}
std::cout << "</faces>";
}
else
{
std::cout << "Faces:" << std::endl;
Block block;
size_t offset = 0;
while (offset < buf->size())
{
bool ok = Block::fromBuffer(buf, offset, block);
if (!ok)
{
std::cerr << "ERROR: cannot decode FaceStatus TLV" << std::endl;
break;
}
offset += block.size();
nfd::FaceStatus faceStatus(block);
std::cout << " faceid=" << faceStatus.getFaceId()
<< " remote=" << faceStatus.getRemoteUri()
<< " local=" << faceStatus.getLocalUri();
if (faceStatus.hasExpirationPeriod()) {
std::cout << " expires="
<< time::duration_cast<time::seconds>(faceStatus.getExpirationPeriod())
.count() << "s";
}
std::cout << " counters={"
<< "in={" << faceStatus.getNInInterests() << "i "
<< faceStatus.getNInDatas() << "d "
<< faceStatus.getNInBytes() << "B}"
<< " out={" << faceStatus.getNOutInterests() << "i "
<< faceStatus.getNOutDatas() << "d "
<< faceStatus.getNOutBytes() << "B}"
<< "}";
if (faceStatus.isLocal())
std::cout << " local";
if (faceStatus.isOnDemand())
std::cout << " on-demand";
std::cout << std::endl;
}
}
runNextStep();
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
void
fetchFibEnumerationInformation()
{
m_buffer = make_shared<OBufferStream>();
Interest interest("/localhost/nfd/fib/list");
interest.setChildSelector(1);
interest.setMustBeFresh(true);
m_face.expressInterest(interest,
bind(&NfdStatus::fetchSegments, this, _2,
&NfdStatus::afterFetchedFibEnumerationInformation),
bind(&NfdStatus::onTimeout, this));
}
void
afterFetchedFibEnumerationInformation()
{
ConstBufferPtr buf = m_buffer->buf();
if (m_isOutputXml)
{
std::cout << "<fib>";
Block block;
size_t offset = 0;
while (offset < buf->size())
{
bool ok = Block::fromBuffer(buf, offset, block);
if (!ok)
{
std::cerr << "ERROR: cannot decode FibEntry TLV";
break;
}
offset += block.size();
nfd::FibEntry fibEntry(block);
std::cout << "<fibEntry>";
std::string prefix(fibEntry.getPrefix().toUri());
escapeSpecialCharacters(&prefix);
std::cout << "<prefix>" << prefix << "</prefix>";
std::cout << "<nextHops>";
for (std::list<nfd::NextHopRecord>::const_iterator
nextHop = fibEntry.getNextHopRecords().begin();
nextHop != fibEntry.getNextHopRecords().end();
++nextHop)
{
std::cout << "<nextHop>" ;
std::cout << "<faceId>" << nextHop->getFaceId() << "</faceId>";
std::cout << "<cost>" << nextHop->getCost() << "</cost>";
std::cout << "</nextHop>";
}
std::cout << "</nextHops>";
std::cout << "</fibEntry>";
}
std::cout << "</fib>";
}
else
{
std::cout << "FIB:" << std::endl;
Block block;
size_t offset = 0;
while (offset < buf->size())
{
bool ok = Block::fromBuffer(buf, offset, block);
if (!ok)
{
std::cerr << "ERROR: cannot decode FibEntry TLV" << std::endl;
break;
}
offset += block.size();
nfd::FibEntry fibEntry(block);
std::cout << " " << fibEntry.getPrefix() << " nexthops={";
for (std::list<nfd::NextHopRecord>::const_iterator
nextHop = fibEntry.getNextHopRecords().begin();
nextHop != fibEntry.getNextHopRecords().end();
++nextHop)
{
if (nextHop != fibEntry.getNextHopRecords().begin())
std::cout << ", ";
std::cout << "faceid=" << nextHop->getFaceId()
<< " (cost=" << nextHop->getCost() << ")";
}
std::cout << "}" << std::endl;
}
}
runNextStep();
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
void
fetchStrategyChoiceInformation()
{
m_buffer = make_shared<OBufferStream>();
Interest interest("/localhost/nfd/strategy-choice/list");
interest.setChildSelector(1);
interest.setMustBeFresh(true);
m_face.expressInterest(interest,
bind(&NfdStatus::fetchSegments, this, _2,
&NfdStatus::afterFetchedStrategyChoiceInformationInformation),
bind(&NfdStatus::onTimeout, this));
}
void
afterFetchedStrategyChoiceInformationInformation()
{
ConstBufferPtr buf = m_buffer->buf();
if (m_isOutputXml)
{
std::cout << "<strategyChoices>";
Block block;
size_t offset = 0;
while (offset < buf->size())
{
bool ok = Block::fromBuffer(buf, offset, block);
if (!ok)
{
std::cerr << "ERROR: cannot decode StrategyChoice TLV";
break;
}
offset += block.size();
nfd::StrategyChoice strategyChoice(block);
std::cout << "<strategyChoice>";
std::string name(strategyChoice.getName().toUri());
escapeSpecialCharacters(&name);
std::cout << "<namespace>" << name << "</namespace>";
std::cout << "<strategy>";
std::string strategy(strategyChoice.getStrategy().toUri());
escapeSpecialCharacters(&strategy);
std::cout << "<name>" << strategy << "</name>";
std::cout << "</strategy>";
std::cout << "</strategyChoice>";
}
std::cout << "</strategyChoices>";
}
else
{
std::cout << "Strategy choices:" << std::endl;
Block block;
size_t offset = 0;
while (offset < buf->size())
{
bool ok = Block::fromBuffer(buf, offset, block);
if (!ok)
{
std::cerr << "ERROR: cannot decode StrategyChoice TLV" << std::endl;
break;
}
offset += block.size();
nfd::StrategyChoice strategyChoice(block);
std::cout << " " << strategyChoice.getName()
<< " strategy=" << strategyChoice.getStrategy() << std::endl;
}
}
runNextStep();
}
void
fetchRibStatusInformation()
{
m_buffer = make_shared<OBufferStream>();
Interest interest("/localhost/nfd/rib/list");
interest.setChildSelector(1);
interest.setMustBeFresh(true);
m_face.expressInterest(interest,
bind(&NfdStatus::fetchSegments, this, _2,
&NfdStatus::afterFetchedRibStatusInformation),
bind(&NfdStatus::onTimeout, this));
}
void
afterFetchedRibStatusInformation()
{
ConstBufferPtr buf = m_buffer->buf();
if (m_isOutputXml)
{
std::cout << "<rib>";
Block block;
size_t offset = 0;
while (offset < buf->size())
{
bool ok = Block::fromBuffer(buf, offset, block);
if (!ok)
{
std::cerr << "ERROR: cannot decode RibEntry TLV";
break;
}
offset += block.size();
nfd::RibEntry ribEntry(block);
std::cout << "<ribEntry>";
std::string prefix(ribEntry.getName().toUri());
escapeSpecialCharacters(&prefix);
std::cout << "<prefix>" << prefix << "</prefix>";
std::cout << "<routes>";
for (std::list<nfd::Route>::const_iterator
nextRoute = ribEntry.begin();
nextRoute != ribEntry.end();
++nextRoute)
{
std::cout << "<route>" ;
std::cout << "<faceId>" << nextRoute->getFaceId() << "</faceId>";
std::cout << "<origin>" << nextRoute->getOrigin() << "</origin>";
std::cout << "<cost>" << nextRoute->getCost() << "</cost>";
std::cout << "<flags>";
if (nextRoute->isChildInherit())
std::cout << "<childInherit/>";
if (nextRoute->isRibCapture())
std::cout << "<ribCapture/>";
std::cout << "</flags>";
if (!nextRoute->hasInfiniteExpirationPeriod()) {
std::cout << "<expirationPeriod>PT"
<< time::duration_cast<time::seconds>(nextRoute->getExpirationPeriod())
.count() << "S"
<< "</expirationPeriod>";
}
std::cout << "</route>";
}
std::cout << "</routes>";
std::cout << "</ribEntry>";
}
std::cout << "</rib>";
}
else
{
std::cout << "Rib:" << std::endl;
Block block;
size_t offset = 0;
while (offset < buf->size())
{
bool ok = Block::fromBuffer(buf, offset, block);
if (!ok)
{
std::cerr << "ERROR: cannot decode RibEntry TLV" << std::endl;
break;
}
offset += block.size();
nfd::RibEntry ribEntry(block);
std::cout << " " << ribEntry.getName().toUri() << " route={";
for (std::list<nfd::Route>::const_iterator
nextRoute = ribEntry.begin();
nextRoute != ribEntry.end();
++nextRoute)
{
if (nextRoute != ribEntry.begin())
std::cout << ", ";
std::cout << "faceid=" << nextRoute->getFaceId()
<< " (origin=" << nextRoute->getOrigin()
<< " cost=" << nextRoute->getCost();
if (!nextRoute->hasInfiniteExpirationPeriod()) {
std::cout << " expires="
<< time::duration_cast<time::seconds>(nextRoute->getExpirationPeriod())
.count() << "s";
}
if (nextRoute->isChildInherit())
std::cout << " ChildInherit";
if (nextRoute->isRibCapture())
std::cout << " RibCapture";
std::cout << ")";
}
std::cout << "}" << std::endl;
}
}
runNextStep();
}
void
fetchInformation()
{
if (m_isOutputXml ||
(!m_needVersionRetrieval &&
!m_needChannelStatusRetrieval &&
!m_needFaceStatusRetrieval &&
!m_needFibEnumerationRetrieval &&
!m_needRibStatusRetrieval &&
!m_needStrategyChoiceRetrieval))
{
enableVersionRetrieval();
enableChannelStatusRetrieval();
enableFaceStatusRetrieval();
enableFibEnumerationRetrieval();
enableRibStatusRetrieval();
enableStrategyChoiceRetrieval();
}
if (m_isOutputXml)
m_fetchSteps.push_back(bind(&NfdStatus::printXmlHeader, this));
if (m_needVersionRetrieval)
m_fetchSteps.push_back(bind(&NfdStatus::fetchVersionInformation, this));
if (m_needChannelStatusRetrieval)
m_fetchSteps.push_back(bind(&NfdStatus::fetchChannelStatusInformation, this));
if (m_needFaceStatusRetrieval)
m_fetchSteps.push_back(bind(&NfdStatus::fetchFaceStatusInformation, this));
if (m_needFibEnumerationRetrieval)
m_fetchSteps.push_back(bind(&NfdStatus::fetchFibEnumerationInformation, this));
if (m_needRibStatusRetrieval)
m_fetchSteps.push_back(bind(&NfdStatus::fetchRibStatusInformation, this));
if (m_needStrategyChoiceRetrieval)
m_fetchSteps.push_back(bind(&NfdStatus::fetchStrategyChoiceInformation, this));
if (m_isOutputXml)
m_fetchSteps.push_back(bind(&NfdStatus::printXmlFooter, this));
runNextStep();
m_face.processEvents();
}
private:
void
printXmlHeader()
{
std::cout << "<?xml version=\"1.0\"?>";
std::cout << "<nfdStatus xmlns=\"ndn:/localhost/nfd/status/1\">";
runNextStep();
}
void
printXmlFooter()
{
std::cout << "</nfdStatus>";
runNextStep();
}
void
runNextStep()
{
if (m_fetchSteps.empty())
return;
function<void()> nextStep = m_fetchSteps.front();
m_fetchSteps.pop_front();
nextStep();
}
private:
std::string m_toolName;
bool m_needVersionRetrieval;
bool m_needChannelStatusRetrieval;
bool m_needFaceStatusRetrieval;
bool m_needFibEnumerationRetrieval;
bool m_needRibStatusRetrieval;
bool m_needStrategyChoiceRetrieval;
bool m_isOutputXml;
Face m_face;
shared_ptr<OBufferStream> m_buffer;
std::deque<function<void()> > m_fetchSteps;
};
}
int main(int argc, char* argv[])
{
int option;
ndn::NfdStatus nfdStatus(argv[0]);
while ((option = getopt(argc, argv, "hvcfbrsxV")) != -1) {
switch (option) {
case 'h':
nfdStatus.usage();
return 0;
case 'v':
nfdStatus.enableVersionRetrieval();
break;
case 'c':
nfdStatus.enableChannelStatusRetrieval();
break;
case 'f':
nfdStatus.enableFaceStatusRetrieval();
break;
case 'b':
nfdStatus.enableFibEnumerationRetrieval();
break;
case 'r':
nfdStatus.enableRibStatusRetrieval();
break;
case 's':
nfdStatus.enableStrategyChoiceRetrieval();
break;
case 'x':
nfdStatus.enableXmlOutput();
break;
case 'V':
std::cout << NFD_VERSION_BUILD_STRING << std::endl;
return 0;
default:
nfdStatus.usage();
return 1;
}
}
try {
nfdStatus.fetchInformation();
}
catch (std::exception& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
return 2;
}
return 0;
}
| dibenede/NFD-NDNcomm2014 | tools/nfd-status.cpp | C++ | gpl-3.0 | 29,976 |
#include "MantidAPI/WorkspaceProperty.h"
#include "MantidAPI/WorkspaceFactory.h"
#include "MantidAPI/WorkspaceGroup.h"
#include "MantidSINQ/PoldiFitPeaks1D.h"
#include "MantidDataObjects/Workspace2D.h"
#include "MantidDataObjects/TableWorkspace.h"
#include "MantidAPI/FunctionFactory.h"
#include "MantidKernel/BoundedValidator.h"
#include "MantidKernel/ListValidator.h"
#include "MantidAPI/TableRow.h"
#include "MantidSINQ/PoldiUtilities/UncertainValue.h"
#include "MantidSINQ/PoldiUtilities/UncertainValueIO.h"
#include "MantidAPI/CompositeFunction.h"
namespace Mantid {
namespace Poldi {
using namespace Kernel;
using namespace API;
using namespace DataObjects;
using namespace CurveFitting;
// Register the algorithm into the AlgorithmFactory
DECLARE_ALGORITHM(PoldiFitPeaks1D)
/// Algorithm's name for identification. @see Algorithm::name
const std::string PoldiFitPeaks1D::name() const { return "PoldiFitPeaks1D"; }
/// Algorithm's version for identification. @see Algorithm::version
int PoldiFitPeaks1D::version() const { return 1; }
/// Algorithm's category for identification. @see Algorithm::category
const std::string PoldiFitPeaks1D::category() const { return "SINQ\\Poldi"; }
void PoldiFitPeaks1D::init() {
declareProperty(
make_unique<WorkspaceProperty<Workspace2D>>("InputWorkspace", "",
Direction::Input),
"An input workspace containing a POLDI auto-correlation spectrum.");
boost::shared_ptr<BoundedValidator<double>> minFwhmPerDirection =
boost::make_shared<BoundedValidator<double>>();
minFwhmPerDirection->setLower(2.0);
declareProperty(
"FwhmMultiples", 2.0, minFwhmPerDirection,
"Each peak will be fitted using x times FWHM data in each direction.",
Direction::Input);
std::vector<std::string> peakFunctions =
FunctionFactory::Instance().getFunctionNames<IPeakFunction>();
auto peakFunctionNames =
boost::make_shared<ListValidator<std::string>>(peakFunctions);
declareProperty("PeakFunction", "Gaussian", peakFunctionNames,
"Peak function that will be fitted to all peaks.",
Direction::Input);
declareProperty(make_unique<WorkspaceProperty<TableWorkspace>>(
"PoldiPeakTable", "", Direction::Input),
"A table workspace containing POLDI peak data.");
declareProperty(make_unique<WorkspaceProperty<TableWorkspace>>(
"OutputWorkspace", "RefinedPeakTable", Direction::Output),
"Output workspace with refined peak data.");
declareProperty(make_unique<WorkspaceProperty<Workspace>>(
"FitPlotsWorkspace", "FitPlots", Direction::Output),
"Plots of all peak fits.");
m_backgroundTemplate = FunctionFactory::Instance().createInitialized(
"name=UserFunction, Formula=A0 + A1*(x - x0)^2");
m_profileTies = "f1.x0 = f0.PeakCentre";
}
void PoldiFitPeaks1D::setPeakFunction(const std::string &peakFunction) {
m_profileTemplate = peakFunction;
}
PoldiPeakCollection_sptr PoldiFitPeaks1D::getInitializedPeakCollection(
const DataObjects::TableWorkspace_sptr &peakTable) const {
auto peakCollection = boost::make_shared<PoldiPeakCollection>(peakTable);
peakCollection->setProfileFunctionName(m_profileTemplate);
return peakCollection;
}
IFunction_sptr
PoldiFitPeaks1D::getPeakProfile(const PoldiPeak_sptr &poldiPeak) const {
IPeakFunction_sptr clonedProfile = boost::dynamic_pointer_cast<IPeakFunction>(
FunctionFactory::Instance().createFunction(m_profileTemplate));
clonedProfile->setCentre(poldiPeak->q());
clonedProfile->setFwhm(poldiPeak->fwhm(PoldiPeak::AbsoluteQ));
clonedProfile->setHeight(poldiPeak->intensity());
IFunction_sptr clonedBackground = m_backgroundTemplate->clone();
auto totalProfile = boost::make_shared<CompositeFunction>();
totalProfile->initialize();
totalProfile->addFunction(clonedProfile);
totalProfile->addFunction(clonedBackground);
if (!m_profileTies.empty()) {
totalProfile->addTies(m_profileTies);
}
return totalProfile;
}
void PoldiFitPeaks1D::setValuesFromProfileFunction(
PoldiPeak_sptr poldiPeak, const IFunction_sptr &fittedFunction) const {
CompositeFunction_sptr totalFunction =
boost::dynamic_pointer_cast<CompositeFunction>(fittedFunction);
if (totalFunction) {
IPeakFunction_sptr peakFunction =
boost::dynamic_pointer_cast<IPeakFunction>(
totalFunction->getFunction(0));
if (peakFunction) {
poldiPeak->setIntensity(
UncertainValue(peakFunction->height(), peakFunction->getError(0)));
poldiPeak->setQ(
UncertainValue(peakFunction->centre(), peakFunction->getError(1)));
poldiPeak->setFwhm(UncertainValue(peakFunction->fwhm(),
getFwhmWidthRelation(peakFunction) *
peakFunction->getError(2)));
}
}
}
double
PoldiFitPeaks1D::getFwhmWidthRelation(IPeakFunction_sptr peakFunction) const {
return peakFunction->fwhm() / peakFunction->getParameter(2);
}
void PoldiFitPeaks1D::exec() {
setPeakFunction(getProperty("PeakFunction"));
// Number of points around the peak center to use for the fit
m_fwhmMultiples = getProperty("FwhmMultiples");
// try to construct PoldiPeakCollection from provided TableWorkspace
TableWorkspace_sptr poldiPeakTable = getProperty("PoldiPeakTable");
m_peaks = getInitializedPeakCollection(poldiPeakTable);
g_log.information() << "Peaks to fit: " << m_peaks->peakCount() << '\n';
Workspace2D_sptr dataWorkspace = getProperty("InputWorkspace");
auto fitPlotGroup = boost::make_shared<WorkspaceGroup>();
for (size_t i = 0; i < m_peaks->peakCount(); ++i) {
PoldiPeak_sptr currentPeak = m_peaks->peak(i);
IFunction_sptr currentProfile = getPeakProfile(currentPeak);
IAlgorithm_sptr fit =
getFitAlgorithm(dataWorkspace, currentPeak, currentProfile);
bool fitSuccess = fit->execute();
if (fitSuccess) {
setValuesFromProfileFunction(currentPeak, fit->getProperty("Function"));
MatrixWorkspace_sptr fpg = fit->getProperty("OutputWorkspace");
fitPlotGroup->addWorkspace(fpg);
}
}
setProperty("OutputWorkspace", m_peaks->asTableWorkspace());
setProperty("FitPlotsWorkspace", fitPlotGroup);
}
IAlgorithm_sptr
PoldiFitPeaks1D::getFitAlgorithm(const Workspace2D_sptr &dataWorkspace,
const PoldiPeak_sptr &peak,
const IFunction_sptr &profile) {
double width = peak->fwhm();
double extent = std::min(0.05, std::max(0.002, width)) * m_fwhmMultiples;
std::pair<double, double> xBorders(peak->q() - extent, peak->q() + extent);
IAlgorithm_sptr fitAlgorithm = createChildAlgorithm("Fit", -1, -1, false);
fitAlgorithm->setProperty("CreateOutput", true);
fitAlgorithm->setProperty("Output", "FitPeaks1D");
fitAlgorithm->setProperty("CalcErrors", true);
fitAlgorithm->setProperty("Function", profile);
fitAlgorithm->setProperty("InputWorkspace", dataWorkspace);
fitAlgorithm->setProperty("WorkspaceIndex", 0);
fitAlgorithm->setProperty("StartX", xBorders.first);
fitAlgorithm->setProperty("EndX", xBorders.second);
return fitAlgorithm;
}
} // namespace Poldi
} // namespace Mantid
| dymkowsk/mantid | Framework/SINQ/src/PoldiFitPeaks1D.cpp | C++ | gpl-3.0 | 7,337 |
<?php
/*
**************************************************************************************************************************
** CORAL Organizations Module v. 1.0
**
** 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 ExternalLogin extends DatabaseObject {
protected function defineRelationships() {}
protected function overridePrimaryKeyName() {}
}
?> | NathanAhlstrom/CORAL | usage/old/admin/classes/domain/ExternalLogin.php | PHP | gpl-3.0 | 1,138 |
using System;
using System.Collections.Generic;
using System.Linq;
using Challenger_Series.Utils;
using LeagueSharp;
using LeagueSharp.SDK;
using SharpDX;
using Color = System.Drawing.Color;
using Challenger_Series.Utils;
using System.Windows.Forms;
using LeagueSharp.Data.Enumerations;
using LeagueSharp.SDK.Enumerations;
using LeagueSharp.SDK.UI;
using LeagueSharp.SDK.Utils;
using Menu = LeagueSharp.SDK.UI.Menu;
using EloBuddy;
using LeagueSharp.SDK;
namespace Challenger_Series.Plugins
{
public class Teemo : CSPlugin
{
public Teemo()
{
Q = new Spell(SpellSlot.Q, 680);
W = new Spell(SpellSlot.W);
E = new Spell(SpellSlot.E);
R = new Spell(SpellSlot.R, 300);
Q.SetTargetted(0.5f, 1500f);
R.SetSkillshot(0.5f, 120f, 1000f, false, SkillshotType.SkillshotCircle);
InitMenu();
Orbwalker.OnAction += OnAction;
DelayedOnUpdate += OnUpdate;
Drawing.OnDraw += OnDraw;
Obj_AI_Base.OnProcessSpellCast += OnProcessSpellCast;
Events.OnGapCloser += OnGapCloser;
Events.OnInterruptableTarget += OnInterruptableTarget;
}
public override void OnUpdate(EventArgs args)
{
if (Q.IsReady()) this.QLogic();
if (W.IsReady()) this.WLogic();
if (R.IsReady()) this.RLogic();
}
private void OnGapCloser(object oSender, Events.GapCloserEventArgs args)
{
/*var sender = args.Sender;
if (UseEAntiGapclose)
{
if (args.IsDirectedToPlayer && args.Sender.Distance(ObjectManager.Player) < 750)
{
if (E.IsReady())
{
E.Cast(sender.ServerPosition);
}
}
}*/
}
private void OnInterruptableTarget(object oSender, Events.InterruptableTargetEventArgs args)
{
/*var sender = args.Sender;
if (!GameObjects.AllyMinions.Any(m => !m.IsDead && m.CharData.BaseSkinName.Contains("trap") && m.Distance(sender.ServerPosition) < 100) && ObjectManager.Player.Distance(sender) < 550)
{
W.Cast(sender.ServerPosition);
}*/
}
private void OnProcessSpellCast(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args)
{
base.OnProcessSpellCast(sender, args);
/*if (sender is AIHeroClient && sender.IsEnemy)
{
if (args.SData.Name == "summonerflash" && args.End.Distance(ObjectManager.Player.ServerPosition) < 650)
{
var pred = Prediction.GetPrediction((AIHeroClient)args.Target, E);
if (!pred.Item3.Any(o => o.IsMinion && !o.IsDead && !o.IsAlly))
{
E.Cast(args.End);
}
}
}*/
}
public override void OnDraw(EventArgs args)
{
var drawRange = DrawRange.Value;
if (drawRange > 0)
{
Render.Circle.DrawCircle(ObjectManager.Player.Position, drawRange, Color.Gold);
}
}
private void OnAction(object sender, OrbwalkingActionArgs orbwalkingActionArgs)
{
if (orbwalkingActionArgs.Type == OrbwalkingType.BeforeAttack)
{
/*if (orbwalkingActionArgs.Target is Obj_AI_Minion && HasPassive && FocusOnHeadShotting &&
Orbwalker.ActiveMode == OrbwalkingMode.LaneClear)
{
var target = orbwalkingActionArgs.Target as Obj_AI_Minion;
if (target != null && !target.CharData.BaseSkinName.Contains("MinionSiege") && target.Health > 60)
{
var tg = (AIHeroClient)TargetSelector.GetTarget(715, DamageType.Physical);
if (tg != null && tg.IsHPBarRendered)
{
Orbwalker.ForceTarget = tg;
orbwalkingActionArgs.Process = false;
}
}
}*/
}
if (orbwalkingActionArgs.Type == OrbwalkingType.AfterAttack)
{
Orbwalker.ForceTarget = null;
if (E.IsReady() && this.UseECombo)
{
if (!OnlyUseEOnMelees)
{
var eTarget = TargetSelector.GetTarget(UseEOnEnemiesCloserThanSlider.Value, DamageType.Physical);
if (eTarget != null)
{
var pred = Prediction.GetPrediction(eTarget, E);
if (pred.Item3.Count == 0 && (int)pred.Item1 >= (int)HitChance.High)
{
E.Cast(pred.Item2);
}
}
}
else
{
var eTarget =
ValidTargets.FirstOrDefault(
e =>
e.IsMelee && e.Distance(ObjectManager.Player) < UseEOnEnemiesCloserThanSlider.Value
&& !e.IsZombie);
var pred = Prediction.GetPrediction(eTarget, E);
if (pred.Item3.Count == 0 && (int)pred.Item1 > (int)HitChance.Medium)
{
E.Cast(pred.Item2);
}
}
}
}
}
private Menu ComboMenu;
private MenuBool UseQCombo;
private MenuBool UseWChase;
private MenuBool UseECombo;
private MenuKeyBind UseRCombo;
private MenuBool AlwaysQAfterE;
private MenuBool FocusOnHeadShotting;
private MenuList<string> QHarassMode;
private MenuBool UseWInterrupt;
private Menu AutoRConfig;
private MenuSlider UseEOnEnemiesCloserThanSlider;
private MenuBool OnlyUseEOnMelees;
private MenuBool UseEAntiGapclose;
private MenuSlider DrawRange;
public void InitMenu()
{
ComboMenu = MainMenu.Add(new Menu("teemocombomenu", "Combo Settings: "));
UseQCombo = ComboMenu.Add(new MenuBool("teemoqcombo", "Use Q", true));
UseWChase = ComboMenu.Add(new MenuBool("usewchase", "Use W when chasing"));
UseECombo = ComboMenu.Add(new MenuBool("teemorcombo", "Use R", true));
AutoRConfig = MainMenu.Add(new Menu("teemoautor", "R Settings: "));
new Utils.Logic.PositionSaver(AutoRConfig, R);
MainMenu.Attach();
}
#region Logic
void QLogic()
{
if (Orbwalker.ActiveMode == OrbwalkingMode.Combo)
{
if (UseQCombo && Q.IsReady() && ObjectManager.Player.CountEnemyHeroesInRange(800) == 0
&& ObjectManager.Player.CountEnemyHeroesInRange(1100) > 0)
{
Q.CastIfWillHit(TargetSelector.GetTarget(900, DamageType.Physical), 2);
var goodQTarget =
ValidTargets.FirstOrDefault(
t =>
t.Distance(ObjectManager.Player) < 950 && t.Health < Q.GetDamage(t)
|| SquishyTargets.Contains(t.CharData.BaseSkinName));
if (goodQTarget != null)
{
var pred = Prediction.GetPrediction(goodQTarget, Q);
if ((int)pred.Item1 > (int)HitChance.Medium)
{
Q.Cast(pred.Item2);
}
}
}
}
if (Orbwalker.ActiveMode != OrbwalkingMode.None && Orbwalker.ActiveMode != OrbwalkingMode.Combo
&& ObjectManager.Player.CountEnemyHeroesInRange(850) == 0)
{
var qHarassMode = QHarassMode.SelectedValue;
if (qHarassMode != "DISABLED")
{
var qTarget = TargetSelector.GetTarget(1100, DamageType.Physical);
if (qTarget != null)
{
var pred = Prediction.GetPrediction(qTarget, Q);
if ((int)pred.Item1 > (int)HitChance.Medium)
{
if (qHarassMode == "ALLOWMINIONS")
{
Q.Cast(pred.Item2);
}
else if (pred.Item3.Count == 0)
{
Q.Cast(pred.Item2);
}
}
}
}
}
}
void WLogic()
{
var goodTarget =
ValidTargets.FirstOrDefault(
e =>
!e.IsDead && e.HasBuffOfType(BuffType.Knockup) || e.HasBuffOfType(BuffType.Snare)
|| e.HasBuffOfType(BuffType.Stun) || e.HasBuffOfType(BuffType.Suppression) || e.IsCharmed
|| e.IsCastingInterruptableSpell() || !e.CanMove);
if (goodTarget != null)
{
var pos = goodTarget.ServerPosition;
if (!GameObjects.AllyMinions.Any(m => !m.IsDead && m.CharData.BaseSkinName.Contains("trap") && m.Distance(goodTarget.ServerPosition) < 100) && pos.Distance(ObjectManager.Player.ServerPosition) < 820)
{
W.Cast(goodTarget.ServerPosition);
}
}
foreach (var enemyMinion in
ObjectManager.Get<Obj_AI_Base>()
.Where(
m =>
m.IsEnemy && m.ServerPosition.Distance(ObjectManager.Player.ServerPosition) < W.Range
&& m.HasBuff("teleport_target")))
{
W.Cast(enemyMinion.ServerPosition);
}
foreach (var hero in GameObjects.EnemyHeroes.Where(h => h.Distance(ObjectManager.Player) < W.Range))
{
var pred = Prediction.GetPrediction(hero, W);
if (!GameObjects.AllyMinions.Any(m => !m.IsDead && m.CharData.BaseSkinName.Contains("trap") && m.Distance(pred.Item2) < 100) && (int)pred.Item1 > (int)HitChance.Medium)
{
W.Cast(pred.Item2);
}
}
}
void RLogic()
{
if (UseRCombo.Active && R.IsReady() && ObjectManager.Player.CountEnemyHeroesInRange(900) == 0)
{
foreach (var rTarget in
ValidTargets.Where(
e =>
SquishyTargets.Contains(e.CharData.BaseSkinName) && R.GetDamage(e) > 0.1 * e.MaxHealth
|| R.GetDamage(e) > e.Health))
{
if (rTarget.Distance(ObjectManager.Player) > 1400)
{
var pred = Prediction.GetPrediction(rTarget, R);
if (!pred.Item3.Any(obj => obj is AIHeroClient))
{
R.CastOnUnit(rTarget);
}
break;
}
R.CastOnUnit(rTarget);
}
}
}
#endregion
private bool HasPassive => ObjectManager.Player.HasBuff("caitlynheadshot");
private string[] SquishyTargets =
{
"Ahri", "Anivia", "Annie", "Ashe", "Azir", "Brand", "Caitlyn", "Cassiopeia",
"Corki", "Draven", "Ezreal", "Graves", "Jinx", "Kalista", "Karma", "Karthus",
"Katarina", "Kennen", "KogMaw", "Kindred", "Leblanc", "Lucian", "Lux",
"MissFortune", "Orianna", "Quinn", "Sivir", "Syndra", "Talon", "Teemo",
"Tristana", "TwistedFate", "Twitch", "Varus", "Vayne", "Veigar", "Velkoz",
"Viktor", "Xerath", "Zed", "Ziggs", "Jhin", "Soraka"
};
}
} | saophaisau/port | Core/SDK Ports/ChallengerSeriesAIO/Plugins/Teemo.cs | C# | gpl-3.0 | 12,392 |
package ca.pfv.spmf.test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.AlgoSPAM_AGP;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.creators.AbstractionCreator;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.creators.AbstractionCreator_Qualitative;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.database.SequenceDatabase;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.idLists.creators.IdListCreator;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.idLists.creators.IdListCreator_FatBitmap;
/**
* Example of how to use the algorithm SPAM, saving the results in the
* main memory
*
* @author agomariz
*/
public class MainTestSPAM_AGP_FatBitMap_saveToMemory {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// Load a sequence database
double support = 0.5;
boolean keepPatterns = true;
boolean verbose = false;
// if you set the following parameter to true, the sequence ids of the sequences where
// each pattern appears will be shown in the result
boolean outputSequenceIdentifiers = false;
AbstractionCreator abstractionCreator = AbstractionCreator_Qualitative.getInstance();
IdListCreator idListCreator = IdListCreator_FatBitmap.getInstance();
SequenceDatabase sequenceDatabase = new SequenceDatabase(abstractionCreator, idListCreator);
sequenceDatabase.loadFile(fileToPath("contextPrefixSpan.txt"), support);
System.out.println(sequenceDatabase.toString());
AlgoSPAM_AGP algorithm = new AlgoSPAM_AGP(support);
algorithm.runAlgorithm(sequenceDatabase, keepPatterns, verbose, null,outputSequenceIdentifiers);
System.out.println("Minimum support (relative) = "+support);
System.out.println(algorithm.getNumberOfFrequentPatterns() + " frequent patterns.");
System.out.println(algorithm.printStatistics());
}
public static String fileToPath(String filename) throws UnsupportedEncodingException {
URL url = MainTestSPADE_AGP_FatBitMap_saveToFile.class.getResource(filename);
return java.net.URLDecoder.decode(url.getPath(), "UTF-8");
}
}
| ArneBinder/LanguageAnalyzer | src/main/java/ca/pfv/spmf/test/MainTestSPAM_AGP_FatBitMap_saveToMemory.java | Java | gpl-3.0 | 2,453 |
<?php
/* Copyright (C) 2017 Alexandre Spangaro <aspangaro@zendsi.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/>.
* or see http://www.gnu.org/
*/
/**
* \file htdocs/compta/bank/various_payment/document.php
* \ingroup banque
* \brief Page of linked files onto various_payment
*/
require '../../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php';
$langs->load("other");
$langs->load("bank");
$langs->load("companies");
$id = GETPOST('id','int');
$ref = GETPOST('ref', 'alpha');
$action = GETPOST('action','alpha');
$confirm = GETPOST('confirm','alpha');
// Security check
if ($user->societe_id) $socid=$user->societe_id;
$result = restrictedArea($user, 'salaries', $id, '');
// Get parameters
$sortfield = GETPOST('sortfield','alpha');
$sortorder = GETPOST('sortorder','alpha');
$page = GETPOST('page','int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1
$offset = $conf->liste_limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
if (! $sortorder) $sortorder="ASC";
if (! $sortfield) $sortfield="name";
$object = new PaymentVarious($db);
$object->fetch($id, $ref);
$upload_dir = $conf->banque->dir_output.'/'.dol_sanitizeFileName($object->id);
$modulepart='banque';
/*
* Actions
*/
include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php';
/*
* View
*/
$form = new Form($db);
llxHeader("",$langs->trans("VariousPayment"));
if ($object->id)
{
$head=various_payment_prepare_head($object);
dol_fiche_head($head, 'documents', $langs->trans("VariousPayment"), 0, 'payment');
// Construit liste des fichiers
$filearray=dol_dir_list($upload_dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
$totalsize=0;
foreach($filearray as $key => $file)
{
$totalsize+=$file['size'];
}
print '<table class="border" width="100%">';
$linkback = '<a href="'.DOL_URL_ROOT.'/compta/bank/various_payment/index.php'.(! empty($socid)?'?socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
// Ref
print '<tr><td class="titlefield">'.$langs->trans("Ref").'</td><td>';
print $form->showrefnav($object, 'id', $linkback, 1, 'rowid', 'ref', '');
print '</td></tr>';
// Societe
//print "<tr><td>".$langs->trans("Company")."</td><td>".$object->client->getNomUrl(1)."</td></tr>";
print '<tr><td>'.$langs->trans("NbOfAttachedFiles").'</td><td colspan="3">'.count($filearray).'</td></tr>';
print '<tr><td>'.$langs->trans("TotalSizeOfAttachedFiles").'</td><td colspan="3">'.$totalsize.' '.$langs->trans("bytes").'</td></tr>';
print '</table>';
print '</div>';
$modulepart = 'banque';
$permission = $user->rights->banque->modifier;
$param = '&id=' . $object->id;
include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php';
}
else
{
print $langs->trans("ErrorUnknown");
}
llxFooter();
$db->close();
| guerrierk/dolibarr | htdocs/compta/bank/various_payment/document.php | PHP | gpl-3.0 | 3,783 |
<?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/>.
/**
* Unit tests for user/lib.php.
*
* @package core_user
* @category phpunit
* @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot.'/user/lib.php');
/**
* Unit tests for user lib api.
*
* @package core_user
* @category phpunit
* @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class core_userliblib_testcase extends advanced_testcase {
/**
* Test user_get_user_details_courses
*/
public function test_user_get_user_details_courses() {
global $DB;
$this->resetAfterTest();
// Create user and modify user profile.
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
$course1 = $this->getDataGenerator()->create_course();
$coursecontext = context_course::instance($course1->id);
$teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
$this->getDataGenerator()->enrol_user($user1->id, $course1->id);
$this->getDataGenerator()->enrol_user($user2->id, $course1->id);
role_assign($teacherrole->id, $user1->id, $coursecontext->id);
role_assign($teacherrole->id, $user2->id, $coursecontext->id);
accesslib_clear_all_caches_for_unit_testing();
// Get user2 details as a user with super system capabilities.
$result = user_get_user_details_courses($user2);
$this->assertEquals($user2->id, $result['id']);
$this->assertEquals(fullname($user2), $result['fullname']);
$this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']);
$this->setUser($user1);
// Get user2 details as a user who can only see this user in a course.
$result = user_get_user_details_courses($user2);
$this->assertEquals($user2->id, $result['id']);
$this->assertEquals(fullname($user2), $result['fullname']);
$this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']);
}
/**
* Test user_update_user.
*/
public function test_user_update_user() {
global $DB;
$this->resetAfterTest();
// Create user and modify user profile.
$user = $this->getDataGenerator()->create_user();
$user->firstname = 'Test';
$user->password = 'M00dLe@T';
// Update user and capture event.
$sink = $this->redirectEvents();
user_update_user($user);
$events = $sink->get_events();
$sink->close();
$event = array_pop($events);
// Test updated value.
$dbuser = $DB->get_record('user', array('id' => $user->id));
$this->assertSame($user->firstname, $dbuser->firstname);
$this->assertNotSame('M00dLe@T', $dbuser->password);
// Test event.
$this->assertInstanceOf('\core\event\user_updated', $event);
$this->assertSame($user->id, $event->objectid);
$this->assertSame('user_updated', $event->get_legacy_eventname());
$this->assertEventLegacyData($dbuser, $event);
$this->assertEquals(context_user::instance($user->id), $event->get_context());
$expectedlogdata = array(SITEID, 'user', 'update', 'view.php?id='.$user->id, '');
$this->assertEventLegacyLogData($expectedlogdata, $event);
// Update user with no password update.
$password = $user->password = hash_internal_user_password('M00dLe@T');
user_update_user($user, false);
$dbuser = $DB->get_record('user', array('id' => $user->id));
$this->assertSame($password, $dbuser->password);
// Verify event is not triggred by user_update_user when needed.
$sink = $this->redirectEvents();
user_update_user($user, false, false);
$events = $sink->get_events();
$sink->close();
$this->assertCount(0, $events);
// With password, there should be 1 event.
$sink = $this->redirectEvents();
user_update_user($user, true, false);
$events = $sink->get_events();
$sink->close();
$this->assertCount(1, $events);
$event = array_pop($events);
$this->assertInstanceOf('\core\event\user_password_updated', $event);
// Test user data validation.
$user->username = 'johndoe123';
$user->auth = 'shibolth';
$user->country = 'WW';
$user->lang = 'xy';
$user->theme = 'somewrongthemename';
$user->timezone = '30.5';
$user->url = 'wwww.somewrong@#$url.com.aus';
$debugmessages = $this->getDebuggingMessages();
user_update_user($user, true, false);
$this->assertDebuggingCalledCount(6, $debugmessages);
// Now, with valid user data.
$user->username = 'johndoe321';
$user->auth = 'shibboleth';
$user->country = 'AU';
$user->lang = 'en';
$user->theme = 'clean';
$user->timezone = 'Australia/Perth';
$user->url = 'www.moodle.org';
user_update_user($user, true, false);
$this->assertDebuggingNotCalled();
}
/**
* Test create_users.
*/
public function test_create_users() {
global $DB;
$this->resetAfterTest();
$user = array(
'username' => 'usernametest1',
'password' => 'Moodle2012!',
'idnumber' => 'idnumbertest1',
'firstname' => 'First Name User Test 1',
'lastname' => 'Last Name User Test 1',
'middlename' => 'Middle Name User Test 1',
'lastnamephonetic' => '最後のお名前のテスト一号',
'firstnamephonetic' => 'お名前のテスト一号',
'alternatename' => 'Alternate Name User Test 1',
'email' => 'usertest1@example.com',
'description' => 'This is a description for user 1',
'city' => 'Perth',
'country' => 'AU'
);
// Create user and capture event.
$sink = $this->redirectEvents();
$user['id'] = user_create_user($user);
$events = $sink->get_events();
$sink->close();
$event = array_pop($events);
// Test user info in DB.
$dbuser = $DB->get_record('user', array('id' => $user['id']));
$this->assertEquals($dbuser->username, $user['username']);
$this->assertEquals($dbuser->idnumber, $user['idnumber']);
$this->assertEquals($dbuser->firstname, $user['firstname']);
$this->assertEquals($dbuser->lastname, $user['lastname']);
$this->assertEquals($dbuser->email, $user['email']);
$this->assertEquals($dbuser->description, $user['description']);
$this->assertEquals($dbuser->city, $user['city']);
$this->assertEquals($dbuser->country, $user['country']);
// Test event.
$this->assertInstanceOf('\core\event\user_created', $event);
$this->assertEquals($user['id'], $event->objectid);
$this->assertEquals('user_created', $event->get_legacy_eventname());
$this->assertEquals(context_user::instance($user['id']), $event->get_context());
$this->assertEventLegacyData($dbuser, $event);
$expectedlogdata = array(SITEID, 'user', 'add', '/view.php?id='.$event->objectid, fullname($dbuser));
$this->assertEventLegacyLogData($expectedlogdata, $event);
// Verify event is not triggred by user_create_user when needed.
$user = array('username' => 'usernametest2'); // Create another user.
$sink = $this->redirectEvents();
user_create_user($user, true, false);
$events = $sink->get_events();
$sink->close();
$this->assertCount(0, $events);
// Test user data validation, first some invalid data.
$user['username'] = 'johndoe123';
$user['auth'] = 'shibolth';
$user['country'] = 'WW';
$user['lang'] = 'xy';
$user['theme'] = 'somewrongthemename';
$user['timezone'] = '-30.5';
$user['url'] = 'wwww.somewrong@#$url.com.aus';
$debugmessages = $this->getDebuggingMessages();
$user['id'] = user_create_user($user, true, false);
$this->assertDebuggingCalledCount(6, $debugmessages);
$dbuser = $DB->get_record('user', array('id' => $user['id']));
$this->assertEquals($dbuser->country, 0);
$this->assertEquals($dbuser->lang, 'en');
$this->assertEquals($dbuser->timezone, '');
// Now, with valid user data.
$user['username'] = 'johndoe321';
$user['auth'] = 'shibboleth';
$user['country'] = 'AU';
$user['lang'] = 'en';
$user['theme'] = 'clean';
$user['timezone'] = 'Australia/Perth';
$user['url'] = 'www.moodle.org';
user_create_user($user, true, false);
$this->assertDebuggingNotCalled();
}
/**
* Test function user_count_login_failures().
*/
public function test_user_count_login_failures() {
$this->resetAfterTest();
$user = $this->getDataGenerator()->create_user();
$this->assertEquals(0, get_user_preferences('login_failed_count_since_success', 0, $user));
for ($i = 0; $i < 10; $i++) {
login_attempt_failed($user);
}
$this->assertEquals(10, get_user_preferences('login_failed_count_since_success', 0, $user));
$count = user_count_login_failures($user); // Reset count.
$this->assertEquals(10, $count);
$this->assertEquals(0, get_user_preferences('login_failed_count_since_success', 0, $user));
for ($i = 0; $i < 10; $i++) {
login_attempt_failed($user);
}
$this->assertEquals(10, get_user_preferences('login_failed_count_since_success', 0, $user));
$count = user_count_login_failures($user, false); // Do not reset count.
$this->assertEquals(10, $count);
$this->assertEquals(10, get_user_preferences('login_failed_count_since_success', 0, $user));
}
/**
* Test function user_add_password_history().
*/
public function test_user_add_password_history() {
global $DB;
$this->resetAfterTest();
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
$user3 = $this->getDataGenerator()->create_user();
$DB->delete_records('user_password_history', array());
set_config('passwordreuselimit', 0);
user_add_password_history($user1->id, 'pokus');
$this->assertEquals(0, $DB->count_records('user_password_history'));
// Test adding and discarding of old.
set_config('passwordreuselimit', 3);
user_add_password_history($user1->id, 'pokus');
$this->assertEquals(1, $DB->count_records('user_password_history'));
$this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user1->id)));
user_add_password_history($user1->id, 'pokus2');
user_add_password_history($user1->id, 'pokus3');
user_add_password_history($user1->id, 'pokus4');
$this->assertEquals(3, $DB->count_records('user_password_history'));
$this->assertEquals(3, $DB->count_records('user_password_history', array('userid' => $user1->id)));
user_add_password_history($user2->id, 'pokus1');
$this->assertEquals(4, $DB->count_records('user_password_history'));
$this->assertEquals(3, $DB->count_records('user_password_history', array('userid' => $user1->id)));
$this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user2->id)));
user_add_password_history($user2->id, 'pokus2');
user_add_password_history($user2->id, 'pokus3');
$this->assertEquals(3, $DB->count_records('user_password_history', array('userid' => $user2->id)));
$ids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
user_add_password_history($user2->id, 'pokus4');
$this->assertEquals(3, $DB->count_records('user_password_history', array('userid' => $user2->id)));
$newids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
$removed = array_shift($ids);
$added = array_pop($newids);
$this->assertSame($ids, $newids);
$this->assertGreaterThan($removed, $added);
// Test disabling prevents changes.
set_config('passwordreuselimit', 0);
$this->assertEquals(6, $DB->count_records('user_password_history'));
$ids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
user_add_password_history($user2->id, 'pokus5');
user_add_password_history($user3->id, 'pokus1');
$newids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
$this->assertSame($ids, $newids);
$this->assertEquals(6, $DB->count_records('user_password_history'));
set_config('passwordreuselimit', -1);
$ids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
user_add_password_history($user2->id, 'pokus6');
user_add_password_history($user3->id, 'pokus6');
$newids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC'));
$this->assertSame($ids, $newids);
$this->assertEquals(6, $DB->count_records('user_password_history'));
}
/**
* Test function user_add_password_history().
*/
public function test_user_is_previously_used_password() {
global $DB;
$this->resetAfterTest();
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
$DB->delete_records('user_password_history', array());
set_config('passwordreuselimit', 0);
user_add_password_history($user1->id, 'pokus');
$this->assertFalse(user_is_previously_used_password($user1->id, 'pokus'));
set_config('passwordreuselimit', 3);
user_add_password_history($user2->id, 'pokus1');
user_add_password_history($user2->id, 'pokus2');
user_add_password_history($user1->id, 'pokus1');
$this->assertTrue(user_is_previously_used_password($user1->id, 'pokus1'));
$this->assertFalse(user_is_previously_used_password($user1->id, 'pokus2'));
$this->assertFalse(user_is_previously_used_password($user1->id, 'pokus3'));
$this->assertFalse(user_is_previously_used_password($user1->id, 'pokus4'));
user_add_password_history($user1->id, 'pokus2');
$this->assertTrue(user_is_previously_used_password($user1->id, 'pokus1'));
$this->assertTrue(user_is_previously_used_password($user1->id, 'pokus2'));
$this->assertFalse(user_is_previously_used_password($user1->id, 'pokus3'));
$this->assertFalse(user_is_previously_used_password($user1->id, 'pokus4'));
user_add_password_history($user1->id, 'pokus3');
$this->assertTrue(user_is_previously_used_password($user1->id, 'pokus1'));
$this->assertTrue(user_is_previously_used_password($user1->id, 'pokus2'));
$this->assertTrue(user_is_previously_used_password($user1->id, 'pokus3'));
$this->assertFalse(user_is_previously_used_password($user1->id, 'pokus4'));
user_add_password_history($user1->id, 'pokus4');
$this->assertFalse(user_is_previously_used_password($user1->id, 'pokus1'));
$this->assertTrue(user_is_previously_used_password($user1->id, 'pokus2'));
$this->assertTrue(user_is_previously_used_password($user1->id, 'pokus3'));
$this->assertTrue(user_is_previously_used_password($user1->id, 'pokus4'));
set_config('passwordreuselimit', 2);
$this->assertFalse(user_is_previously_used_password($user1->id, 'pokus1'));
$this->assertFalse(user_is_previously_used_password($user1->id, 'pokus2'));
$this->assertTrue(user_is_previously_used_password($user1->id, 'pokus3'));
$this->assertTrue(user_is_previously_used_password($user1->id, 'pokus4'));
set_config('passwordreuselimit', 3);
$this->assertFalse(user_is_previously_used_password($user1->id, 'pokus1'));
$this->assertFalse(user_is_previously_used_password($user1->id, 'pokus2'));
$this->assertTrue(user_is_previously_used_password($user1->id, 'pokus3'));
$this->assertTrue(user_is_previously_used_password($user1->id, 'pokus4'));
set_config('passwordreuselimit', 0);
$this->assertFalse(user_is_previously_used_password($user1->id, 'pokus1'));
$this->assertFalse(user_is_previously_used_password($user1->id, 'pokus2'));
$this->assertFalse(user_is_previously_used_password($user1->id, 'pokus3'));
$this->assertFalse(user_is_previously_used_password($user1->id, 'pokus4'));
}
/**
* Test that password history is deleted together with user.
*/
public function test_delete_of_hashes_on_user_delete() {
global $DB;
$this->resetAfterTest();
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
$DB->delete_records('user_password_history', array());
set_config('passwordreuselimit', 3);
user_add_password_history($user1->id, 'pokus');
user_add_password_history($user2->id, 'pokus1');
user_add_password_history($user2->id, 'pokus2');
$this->assertEquals(3, $DB->count_records('user_password_history'));
$this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user1->id)));
$this->assertEquals(2, $DB->count_records('user_password_history', array('userid' => $user2->id)));
delete_user($user2);
$this->assertEquals(1, $DB->count_records('user_password_history'));
$this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user1->id)));
$this->assertEquals(0, $DB->count_records('user_password_history', array('userid' => $user2->id)));
}
/**
* Test user_list_view function
*/
public function test_user_list_view() {
$this->resetAfterTest();
// Course without sections.
$course = $this->getDataGenerator()->create_course();
$context = context_course::instance($course->id);
$this->setAdminUser();
// Redirect events to the sink, so we can recover them later.
$sink = $this->redirectEvents();
user_list_view($course, $context);
$events = $sink->get_events();
$this->assertCount(1, $events);
$event = reset($events);
// Check the event details are correct.
$this->assertInstanceOf('\core\event\user_list_viewed', $event);
$this->assertEquals($context, $event->get_context());
$this->assertEquals($course->shortname, $event->other['courseshortname']);
$this->assertEquals($course->fullname, $event->other['coursefullname']);
}
/**
* Test setting the user menu avatar size.
*/
public function test_user_menu_custom_avatar_size() {
global $PAGE;
$this->resetAfterTest(true);
$testsize = 100;
$PAGE->set_url('/');
$user = $this->getDataGenerator()->create_user();
$opts = user_get_user_navigation_info($user, $PAGE, array('avatarsize' => $testsize));
$avatarhtml = $opts->metadata['useravatar'];
$matches = [];
preg_match('/(?:.*width=")(\d*)(?:" height=")(\d*)(?:".*\/>)/', $avatarhtml, $matches);
$this->assertCount(3, $matches);
$this->assertEquals(intval($matches[1]), $testsize);
$this->assertEquals(intval($matches[2]), $testsize);
}
/**
* Test user_can_view_profile
*/
public function test_user_can_view_profile() {
global $DB, $CFG;
$this->resetAfterTest();
// Create five users.
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
$user3 = $this->getDataGenerator()->create_user();
$user4 = $this->getDataGenerator()->create_user();
$user5 = $this->getDataGenerator()->create_user();
$user6 = $this->getDataGenerator()->create_user(array('deleted' => 1));
$user7 = $this->getDataGenerator()->create_user();
$user8 = $this->getDataGenerator()->create_user();
$user8->id = 0; // Visitor.
$studentrole = $DB->get_record('role', array('shortname' => 'student'));
// Add the course creator role to the course contact and assign a user to that role.
$CFG->coursecontact = '2';
$coursecreatorrole = $DB->get_record('role', array('shortname' => 'coursecreator'));
$this->getDataGenerator()->role_assign($coursecreatorrole->id, $user7->id);
// Create two courses.
$course1 = $this->getDataGenerator()->create_course();
$course2 = $this->getDataGenerator()->create_course();
$coursecontext = context_course::instance($course2->id);
// Prepare another course with separate groups and groupmodeforce set to true.
$record = new stdClass();
$record->groupmode = 1;
$record->groupmodeforce = 1;
$course3 = $this->getDataGenerator()->create_course($record);
// Enrol users 1 and 2 in first course.
$this->getDataGenerator()->enrol_user($user1->id, $course1->id);
$this->getDataGenerator()->enrol_user($user2->id, $course1->id);
// Enrol users 2 and 3 in second course.
$this->getDataGenerator()->enrol_user($user2->id, $course2->id);
$this->getDataGenerator()->enrol_user($user3->id, $course2->id);
// Enrol users 1, 4, and 5 into course 3.
$this->getDataGenerator()->enrol_user($user1->id, $course3->id);
$this->getDataGenerator()->enrol_user($user4->id, $course3->id);
$this->getDataGenerator()->enrol_user($user5->id, $course3->id);
// User 3 should not be able to see user 1, either by passing their own course (course 2) or user 1's course (course 1).
$this->setUser($user3);
$this->assertFalse(user_can_view_profile($user1, $course2));
$this->assertFalse(user_can_view_profile($user1, $course1));
// Remove capability moodle/user:viewdetails in course 2.
assign_capability('moodle/user:viewdetails', CAP_PROHIBIT, $studentrole->id, $coursecontext);
$coursecontext->mark_dirty();
// Set current user to user 1.
$this->setUser($user1);
// User 1 can see User 1's profile.
$this->assertTrue(user_can_view_profile($user1));
$tempcfg = $CFG->forceloginforprofiles;
$CFG->forceloginforprofiles = 0;
// Not forced to log in to view profiles, should be able to see all profiles besides user 6.
$users = array($user1, $user2, $user3, $user4, $user5, $user7);
foreach ($users as $user) {
$this->assertTrue(user_can_view_profile($user));
}
// Restore setting.
$CFG->forceloginforprofiles = $tempcfg;
// User 1 can not see user 6 as they have been deleted.
$this->assertFalse(user_can_view_profile($user6));
// User 1 can see User 7 as they are a course contact.
$this->assertTrue(user_can_view_profile($user7));
// User 1 is in a course with user 2 and has the right capability - return true.
$this->assertTrue(user_can_view_profile($user2));
// User 1 is not in a course with user 3 - return false.
$this->assertFalse(user_can_view_profile($user3));
// Set current user to user 2.
$this->setUser($user2);
// User 2 is in a course with user 3 but does not have the right capability - return false.
$this->assertFalse(user_can_view_profile($user3));
// Set user 1 in one group and users 4 and 5 in another group.
$group1 = $this->getDataGenerator()->create_group(array('courseid' => $course3->id));
$group2 = $this->getDataGenerator()->create_group(array('courseid' => $course3->id));
groups_add_member($group1->id, $user1->id);
groups_add_member($group2->id, $user4->id);
groups_add_member($group2->id, $user5->id);
$this->setUser($user1);
// Check that user 1 can not see user 4.
$this->assertFalse(user_can_view_profile($user4));
// Check that user 5 can see user 4.
$this->setUser($user5);
$this->assertTrue(user_can_view_profile($user4));
// Test the user:viewalldetails cap check using the course creator role which, by default, can't see student profiles.
$this->setUser($user7);
$this->assertFalse(user_can_view_profile($user4));
assign_capability('moodle/user:viewalldetails', CAP_ALLOW, $coursecreatorrole->id, context_system::instance()->id, true);
reload_all_capabilities();
$this->assertTrue(user_can_view_profile($user4));
unassign_capability('moodle/user:viewalldetails', $coursecreatorrole->id, $coursecontext->id);
reload_all_capabilities();
$CFG->coursecontact = null;
// Visitor (Not a guest user, userid=0).
$CFG->forceloginforprofiles = 1;
$this->setUser($user8);
$this->assertFalse(user_can_view_profile($user1));
$allroles = $DB->get_records_menu('role', array(), 'id', 'archetype, id');
// Let us test with guest user.
$this->setGuestUser();
$CFG->forceloginforprofiles = 1;
foreach ($users as $user) {
$this->assertFalse(user_can_view_profile($user));
}
// Even with cap, still guests should not be allowed in.
$guestrole = $DB->get_records_menu('role', array('shortname' => 'guest'), 'id', 'archetype, id');
assign_capability('moodle/user:viewdetails', CAP_ALLOW, $guestrole['guest'], context_system::instance()->id, true);
reload_all_capabilities();
foreach ($users as $user) {
$this->assertFalse(user_can_view_profile($user));
}
$CFG->forceloginforprofiles = 0;
foreach ($users as $user) {
$this->assertTrue(user_can_view_profile($user));
}
// Let us test with Visitor user.
$this->setUser($user8);
$CFG->forceloginforprofiles = 1;
foreach ($users as $user) {
$this->assertFalse(user_can_view_profile($user));
}
$CFG->forceloginforprofiles = 0;
foreach ($users as $user) {
$this->assertTrue(user_can_view_profile($user));
}
// Testing non-shared courses where capabilities are met, using system role overrides.
$CFG->forceloginforprofiles = $tempcfg;
$course4 = $this->getDataGenerator()->create_course();
$this->getDataGenerator()->enrol_user($user1->id, $course4->id);
// Assign a manager role at the system context.
$managerrole = $DB->get_record('role', array('shortname' => 'manager'));
$user9 = $this->getDataGenerator()->create_user();
$this->getDataGenerator()->role_assign($managerrole->id, $user9->id);
// Make sure viewalldetails and viewdetails are overridden to 'prevent' (i.e. can be overridden at a lower context).
$systemcontext = context_system::instance();
assign_capability('moodle/user:viewdetails', CAP_PREVENT, $managerrole->id, $systemcontext, true);
assign_capability('moodle/user:viewalldetails', CAP_PREVENT, $managerrole->id, $systemcontext, true);
$systemcontext->mark_dirty();
// And override these to 'Allow' in a specific course.
$course4context = context_course::instance($course4->id);
assign_capability('moodle/user:viewalldetails', CAP_ALLOW, $managerrole->id, $course4context, true);
assign_capability('moodle/user:viewdetails', CAP_ALLOW, $managerrole->id, $course4context, true);
$course4context->mark_dirty();
// The manager now shouldn't have viewdetails in the system or user context.
$this->setUser($user9);
$user1context = context_user::instance($user1->id);
$this->assertFalse(has_capability('moodle/user:viewdetails', $systemcontext));
$this->assertFalse(has_capability('moodle/user:viewdetails', $user1context));
// Confirm that user_can_view_profile() returns true for $user1 when called without $course param. It should find $course1.
$this->assertTrue(user_can_view_profile($user1));
// Confirm this also works when restricting scope to just that course.
$this->assertTrue(user_can_view_profile($user1, $course4));
}
/**
* Test user_get_user_details
*/
public function test_user_get_user_details() {
global $DB;
$this->resetAfterTest();
// Create user and modify user profile.
$teacher = $this->getDataGenerator()->create_user();
$student = $this->getDataGenerator()->create_user();
$studentfullname = fullname($student);
$course1 = $this->getDataGenerator()->create_course();
$coursecontext = context_course::instance($course1->id);
$teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
$studentrole = $DB->get_record('role', array('shortname' => 'student'));
$this->getDataGenerator()->enrol_user($teacher->id, $course1->id);
$this->getDataGenerator()->enrol_user($student->id, $course1->id);
role_assign($teacherrole->id, $teacher->id, $coursecontext->id);
role_assign($studentrole->id, $student->id, $coursecontext->id);
accesslib_clear_all_caches_for_unit_testing();
// Get student details as a user with super system capabilities.
$result = user_get_user_details($student, $course1);
$this->assertEquals($student->id, $result['id']);
$this->assertEquals($studentfullname, $result['fullname']);
$this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']);
$this->setUser($teacher);
// Get student details as a user who can only see this user in a course.
$result = user_get_user_details($student, $course1);
$this->assertEquals($student->id, $result['id']);
$this->assertEquals($studentfullname, $result['fullname']);
$this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']);
// Get student details with required fields.
$result = user_get_user_details($student, $course1, array('id', 'fullname'));
$this->assertCount(2, $result);
$this->assertEquals($student->id, $result['id']);
$this->assertEquals($studentfullname, $result['fullname']);
// Get exception for invalid required fields.
$this->expectException('moodle_exception');
$result = user_get_user_details($student, $course1, array('wrongrequiredfield'));
}
/**
* Regression test for MDL-57840.
*
* Ensure the fields "auth, confirmed, idnumber, lang, theme, timezone and mailformat" are present when
* calling user_get_user_details() function.
*/
public function test_user_get_user_details_missing_fields() {
$this->resetAfterTest(true);
$this->setAdminUser(); // We need capabilities to view the data.
$user = self::getDataGenerator()->create_user([
'auth' => 'auth_something',
'confirmed' => '0',
'idnumber' => 'someidnumber',
'lang' => 'en_ar',
'theme' => 'mytheme',
'timezone' => '50',
'mailformat' => '0',
]);
// Fields that should get by default.
$got = user_get_user_details($user);
self::assertSame('auth_something', $got['auth']);
self::assertSame('0', $got['confirmed']);
self::assertSame('someidnumber', $got['idnumber']);
self::assertSame('en_ar', $got['lang']);
self::assertSame('mytheme', $got['theme']);
self::assertSame('50', $got['timezone']);
self::assertSame('0', $got['mailformat']);
}
/**
* Test returning the total number of participants.
*/
public function test_user_get_total_participants() {
global $DB;
$this->resetAfterTest();
// Create a course.
$course = self::getDataGenerator()->create_course();
// Create a teacher.
$teacher = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
// Create a bunch of students.
$student1 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
$student2 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
$student3 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
// Create a group.
$group = self::getDataGenerator()->create_group(array('courseid' => $course->id));
// Enrol the students.
self::getDataGenerator()->enrol_user($student1->id, $course->id);
self::getDataGenerator()->enrol_user($student2->id, $course->id);
self::getDataGenerator()->enrol_user($student3->id, $course->id);
// Enrol the teacher.
$roleids = $DB->get_records_menu('role', null, '', 'shortname, id');
self::getDataGenerator()->enrol_user($teacher->id, $course->id, $roleids['editingteacher']);
// Add the teacher and two of the students to the group.
groups_add_member($group->id, $teacher->id);
groups_add_member($group->id, $student1->id);
groups_add_member($group->id, $student2->id);
// Set it so the teacher and two of the students have accessed the courses within the last day,
// but only one of the students is in the group.
$accesssince = time() - DAYSECS;
$lastaccess = new stdClass();
$lastaccess->userid = $teacher->id;
$lastaccess->courseid = $course->id;
$lastaccess->timeaccess = time() - DAYSECS;
$DB->insert_record('user_lastaccess', $lastaccess);
$lastaccess->userid = $student1->id;
$DB->insert_record('user_lastaccess', $lastaccess);
$lastaccess->userid = $student3->id;
$DB->insert_record('user_lastaccess', $lastaccess);
// Now, when we perform the following search we should only return 1 user. A student who belongs to
// the group and has the name 'searchforthis' and has also accessed the course in the last day.
$count = user_get_total_participants($course->id, $group->id, $accesssince + 1, $roleids['student'], 0, -1,
'searchforthis');
$this->assertEquals(1, $count);
}
/**
* Test returning the number of participants on the front page.
*/
public function test_user_get_total_participants_on_front_page() {
$this->resetAfterTest();
// Set it so that only 3 users have accessed the site within the last day.
$accesssince = time() - DAYSECS;
// Create a bunch of users.
$user1 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]);
$user2 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]);
$user3 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
$user4 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]);
// Create a group.
$group = self::getDataGenerator()->create_group(array('courseid' => SITEID));
// Add 3 of the users to a group.
groups_add_member($group->id, $user1->id);
groups_add_member($group->id, $user2->id);
groups_add_member($group->id, $user3->id);
// Now, when we perform the following search we should only return 2 users. Users who belong to
// the group and have the name 'searchforthis' and have also accessed the site in the last day.
$count = user_get_total_participants(SITEID, $group->id, $accesssince + 1, 0, 0, -1, 'searchforthis');
$this->assertEquals(2, $count);
}
/**
* Test returning the participants.
*/
public function test_user_get_participants() {
global $DB;
$this->resetAfterTest();
// Create a course.
$course = self::getDataGenerator()->create_course();
// Create a teacher.
$teacher = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
// Create a bunch of students.
$student1 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
$student2 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
$student3 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
// Create a group.
$group = self::getDataGenerator()->create_group(array('courseid' => $course->id));
// Enrol the students.
self::getDataGenerator()->enrol_user($student1->id, $course->id);
self::getDataGenerator()->enrol_user($student2->id, $course->id);
self::getDataGenerator()->enrol_user($student3->id, $course->id);
// Enrol the teacher.
$roleids = $DB->get_records_menu('role', null, '', 'shortname, id');
self::getDataGenerator()->enrol_user($teacher->id, $course->id, $roleids['editingteacher']);
// Add the teacher and two of the students to the group.
groups_add_member($group->id, $teacher->id);
groups_add_member($group->id, $student1->id);
groups_add_member($group->id, $student2->id);
// Set it so the teacher and two of the students have accessed the course within the last day, but only one of
// the students is in the group.
$accesssince = time() - DAYSECS;
$lastaccess = new stdClass();
$lastaccess->userid = $teacher->id;
$lastaccess->courseid = $course->id;
$lastaccess->timeaccess = time() - DAYSECS;
$DB->insert_record('user_lastaccess', $lastaccess);
$lastaccess->userid = $student1->id;
$DB->insert_record('user_lastaccess', $lastaccess);
$lastaccess->userid = $student3->id;
$DB->insert_record('user_lastaccess', $lastaccess);
// Now, when we perform the following search we should only return 1 user. A student who belongs to
// the group and has the name 'searchforthis' and has also accessed the course in the last day.
$userset = user_get_participants($course->id, $group->id, $accesssince + 1, $roleids['student'], 0, -1, 'searchforthis');
$this->assertEquals($student1->id, $userset->current()->id);
$this->assertEquals(1, iterator_count($userset));
}
/**
* Test returning the participants on the front page.
*/
public function test_user_get_participants_on_front_page() {
$this->resetAfterTest();
// Set it so that only 3 users have accessed the site within the last day.
$accesssince = time() - DAYSECS;
// Create a bunch of users.
$user1 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]);
$user2 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]);
$user3 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']);
$user4 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]);
// Create a group.
$group = self::getDataGenerator()->create_group(array('courseid' => SITEID));
// Add 3 of the users to a group.
groups_add_member($group->id, $user1->id);
groups_add_member($group->id, $user2->id);
groups_add_member($group->id, $user3->id);
// Now, when we perform the following search we should only return 2 users. Users who belong to
// the group and have the name 'searchforthis' and have also accessed the site in the last day.
$userset = user_get_participants(SITEID, $group->id, $accesssince + 1, 0, 0, -1, 'searchforthis', '', array(),
'ORDER BY id ASC');
$this->assertEquals($user1->id, $userset->current()->id);
$userset->next();
$this->assertEquals($user2->id, $userset->current()->id);
}
}
| jayuqar/moodle | user/tests/userlib_test.php | PHP | gpl-3.0 | 41,890 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WiimoteLib;
namespace WiiApi {
/// <summary>
/// Klasa koriscena za prikaz polozaja i orijentacije glave u prostoru. Sadrzi samo metode za dobavljanje informacija.
/// </summary>
public class PolozajGlave {
/// <summary>
/// Plozaj glave u milimetrima, vrednost je validna za pracenje 2 i 3 izvora.
/// </summary>
private Point3F polozaj;
/// <summary>
/// Vektor koji pokazuje na gore. Odredjuje rotaciju oko z ose. Vrednost je validna samo ako se prate 3 izvora.
/// </summary>
private Point3F goreVektor;
/// <summary>
/// Pravac pogleda. Odredjuje rotaciju oko x i y osa. Vrednost je validna samo ako se prate 3 izvora.
/// </summary>
private Point3F pogledVektor;
/// <summary>
/// Indikacija da li su uspesno locirani svi izvori prilikom obrade poslednjeg dogadjaja. Ako je vrednost false podaci nisu validni.
/// </summary>
private bool uspesno;
/// <summary>
/// Konstruktor koji se koristi za postavljanje vrednosti prilikom pracenja 2 izvora
/// </summary>
/// <param name="uspesno">Indikacija da li su uspesno locirani svi izvori prilikom obrade poslednjeg dogadjaja.</param>
/// <param name="polozaj">Polozaj glave u milimetrima. </param>
public PolozajGlave(bool uspesno, Point3F polozaj)
{
this.uspesno = uspesno;
this.polozaj = polozaj;
}
/// <summary>
/// Konstruktor koji se koristi za postavljanje vrednosti prilikom pracenja 3 izvora
/// </summary>
/// <param name="uspesno">Indikacija da li su uspesno locirani svi izvori prilikom obrade poslednjeg dogadjaja.</param>
/// <param name="polozaj">Polozaj glave u milimetrima. </param>
/// <param name="goreVektor">Vektor na gore. </param>
/// /// <param name="pogledVektor">Pravac pogleda. </param>
public PolozajGlave(bool uspesno, Point3F polozaj, Point3F goreVektor, Point3F pogledVektor)
{
this.uspesno = uspesno;
this.polozaj = polozaj;
this.goreVektor = goreVektor;
this.pogledVektor = pogledVektor;
}
/// <summary>
/// Indikacija da li su uspesno locirani svi izvori prilikom obrade poslednjeg dogadjaja. Ako je vrednost false podaci nisu validni.
/// </summary>
public bool Uspesno
{
get
{
return uspesno;
}
}
/// <summary>
/// Plozaj glave u milimetrima, vrednost je validna za pracenje 2 i 3 izvora.
/// </summary>
public Point3F Polozaj
{
get
{
return polozaj;
}
}
/// <summary>
/// Vektor koji pokazuje na gore. Odredjuje rotaciju oko z ose. Vrednost je validna samo ako se prate 3 izvora.
/// </summary>
public Point3F GoreVektor
{
get
{
return goreVektor;
}
}
/// <summary>
/// Pravac pogleda. Odredjuje rotaciju oko x i y osa. Vrednost je validna samo ako se prate 3 izvora.
/// </summary>
public Point3F PogledVektor
{
get
{
return pogledVektor;
}
}
}
}
| ljsimin/gimii | WiiApi/WiiApi/PolozajGlave.cs | C# | gpl-3.0 | 3,610 |
var UniteSettingsRev = new function(){
var arrControls = {};
var colorPicker;
var t=this;
this.getSettingsObject = function(formID){
var obj = new Object();
var form = document.getElementById(formID);
var name,value,type,flagUpdate;
//enabling all form items connected to mx
var len = form.elements.length;
for(var i=0; i<len; i++){
var element = form.elements[i];
if(element.name == "##NAME##[]") continue; //ignore dummy from multi text
name = element.name;
value = element.value;
type = element.type;
if(jQuery(element).hasClass("wp-editor-area"))
type = "editor";
//trace(name + " " + type);
flagUpdate = true;
switch(type){
case "checkbox":
value = form.elements[i].checked;
break;
case "radio":
if(form.elements[i].checked == false)
flagUpdate = false;
break;
case "editor":
value = tinyMCE.get(name).getContent();
break;
case "select-multiple":
value = jQuery(element).val();
if(value)
value = value.toString();
break;
}
if(flagUpdate == true && name != undefined){
if(name.indexOf('[]') > -1){
name = name.replace('[]', '');
if(typeof obj[name] !== 'object') obj[name] = [];
obj[name][Object.keys(obj[name]).length] = value;
}else{
obj[name] = value;
}
}
}
return(obj);
}
this.getsdsformvalue = function(formID){
var obj = new Object();
var form = document.getElementById(formID);
var name,value,type,flagUpdate;
//enabling all form items connected to mx
var len = form.elements.length;
for(var i=0; i<len; i++){
var element = form.elements[i];
if(element.name == "##NAME##[]") continue; //ignore dummy from multi text
name = element.name;
value = element.value;
type = element.type;
if(jQuery(element).hasClass("wp-editor-area"))
type = "editor";
//trace(name + " " + type);
flagUpdate = true;
switch(type){
case "checkbox":
value = form.elements[i].checked;
break;
case "radio":
if(form.elements[i].checked == false)
flagUpdate = false;
break;
case "editor":
value = tinyMCE.get(name).getContent();
break;
case "select-multiple":
value = jQuery(element).val();
if(value)
value = value.toString();
break;
}
if(flagUpdate == true && name != undefined){
if(name.indexOf('[]') > -1){
name = name.replace('[]', '');
if(typeof obj[name] !== 'object') obj[name] = [];
obj[name][Object.keys(obj[name]).length] = value;
}else{
obj[name] = value;
}
}
}
return(obj);
}
/**
* on selects change - impiment the hide/show, enabled/disables functionality
*/
var onSettingChange = function(){
var controlValue = this.value.toLowerCase();
var controlName = this.name;
if(!arrControls[this.name]) return(false);
jQuery(arrControls[this.name]).each(function(){
var childInput = document.getElementById(this.name);
var childRow = document.getElementById(this.name + "_row");
var value = this.value.toLowerCase();
var isChildRadio = (childInput && childInput.tagName == "SPAN" && jQuery(childInput).hasClass("radio_wrapper"));
switch(this.type){
case "enable":
case "disable":
if(childInput){ //disable
if(this.type == "enable" && controlValue != this.value || this.type == "disable" && controlValue == this.value){
childRow.className = "disabled";
if(childInput){
childInput.disabled = true;
childInput.style.color = "";
}
if(isChildRadio)
jQuery(childInput).children("input").prop("disabled","disabled").addClass("disabled");
}
else{ //enable
childRow.className = "";
if(childInput)
childInput.disabled = false;
if(isChildRadio)
jQuery(childInput).children("input").prop("disabled","").removeClass("disabled");
//color the input again
if(jQuery(childInput).hasClass("inputColorPicker")) g_picker.linkTo(childInput);
}
}
break;
case "show":
if(controlValue == this.value) jQuery(childRow).show();
else jQuery(childRow).hide();
break;
case "hide":
if(controlValue == this.value) jQuery(childRow).hide();
else jQuery(childRow).show();
break;
}
});
}
/**
* combine controls to one object, and init control events.
*/
var initControls = function(){
//combine controls
for(key in g_settingsObj){
var obj = g_settingsObj[key];
for(controlKey in obj.controls){
arrControls[controlKey] = obj.controls[controlKey];
}
}
//init events
jQuery(".settings_wrapper select").change(onSettingChange);
jQuery(".settings_wrapper input[type='radio']").change(onSettingChange);
}
//init color picker
var initColorPicker = function(){
var colorPickerWrapper = jQuery('#divColorPicker');
colorPicker = jQuery.farbtastic('#divColorPicker');
jQuery(".inputColorPicker").focus(function(){
colorPicker.linkTo(this);
colorPickerWrapper.show();
var input = jQuery(this);
var offset = input.offset();
var offsetView = jQuery("#viewWrapper").offset();
colorPickerWrapper.css({
"left":offset.left + input.width()+20-offsetView.left,
"top":offset.top - colorPickerWrapper.height() + 100-offsetView.top
});
if (jQuery(input.data('linkto'))) {
var oldval = jQuery(this).val();
jQuery(this).data('int',setInterval(function() {
if(input.val() != oldval){
oldval = input.val();
jQuery('#css_preview').css(input.data('linkto'), oldval);
jQuery('input[name="css_'+input.data('linkto')+'"]').val(oldval);
}
} ,200));
}
}).blur(function() {
clearInterval(jQuery(this).data('int'));
}).click(function(){
return(false); //prevent body click
}).change(function(){
colorPicker.linkTo(this);
colorPicker.setColor(jQuery(this).val());
});
colorPickerWrapper.click(function(){
return(false); //prevent body click
});
jQuery("body").click(function(){
colorPickerWrapper.hide();
});
}
/**
* close all accordion items
*/
var closeAllAccordionItems = function(formID){
jQuery("#"+formID+" .unite-postbox .inside").slideUp("fast");
jQuery("#"+formID+" .unite-postbox h3").addClass("box_closed");
}
/**
* init side settings accordion - started from php
*/
t.initAccordion = function(formID){
var classClosed = "box_closed";
jQuery("#"+formID+" .unite-postbox h3").click(function(){
var handle = jQuery(this);
//open
if(handle.hasClass(classClosed)){
closeAllAccordionItems(formID);
handle.removeClass(classClosed).siblings(".inside").slideDown("fast");
}else{ //close
handle.addClass(classClosed).siblings(".inside").slideUp("fast");
}
});
}
/**
* image search
*/
var initImageSearch = function(){
jQuery(".button-image-select").click(function(){
var settingID = this.id.replace("_button","");
UniteAdminRev.openAddImageDialog("Choose Image",function(urlImage, imageID){
//update input:
jQuery("#"+settingID).val(urlImage);
//update preview image:
var urlShowImage = UniteAdminRev.getUrlShowImage(imageID,100,70,true);
jQuery("#" + settingID + "_button_preview").html('<div style="width:100px;height:70px;background:url(\''+urlShowImage+'\'); background-position:center center; background-size:cover;"></div>');
});
});
jQuery(".button-image-remove").click(function(){
var settingID = this.id.replace("_button_remove","");
jQuery("#"+settingID).val('');
jQuery("#" + settingID + "_button_preview").html('');
});
jQuery(".button-image-select-video").click(function(){
UniteAdminRev.openAddImageDialog("Choose Image",function(urlImage, imageID){
//update input:
jQuery("#input_video_preview").val(urlImage);
//update preview image:
var urlShowImage = UniteAdminRev.getUrlShowImage(imageID,200,150,true);
jQuery("#video-thumbnail-preview").attr('src', urlShowImage);
});
});
jQuery(".button-image-remove-video").click(function(){
jQuery("#input_video_preview").val('');
if(jQuery('#video_block_vimeo').css('display') != 'none')
jQuery("#button_vimeo_search").trigger("click");
if(jQuery('#video_block_youtube').css('display') != 'none')
jQuery("#button_youtube_search").trigger("click");
});
}
/**
* init the settings function, set the tootips on sidebars.
*/
var init = function(){
//init tipsy
jQuery(".list_settings li .setting_text").tipsy({
gravity:"e",
delayIn: 70
});
jQuery(".tipsy_enabled_top").tipsy({
gravity:"s",
delayIn: 70
});
jQuery(".button-primary").tipsy({
gravity:"s",
delayIn: 70
});
//init controls
initControls();
initColorPicker();
initImageSearch();
//init checklist
jQuery(".settings_wrapper .input_checklist").each(function(){
var select = jQuery(this);
var ominWidth = select.data("minwidth");
if (ominWidth==undefined) ominWidth="none"
select.dropdownchecklist({
zIndex:1000,
minWidth:ominWidth,
onItemClick: function(checkbox,selector) {
for (var i=0;i<20;i++)
if (checkbox.val()=="notselectable"+i) {
//console.log(checkbox.val());
checkbox.attr("checked",false);
}
}
});
select.parent().find('input').each(function() {
var option = jQuery(this);
for (var i=0;i<20;i++)
if (option.val()=="notselectable"+i) option.parent().addClass("dropdowntitleoption");
})
});
}
//call "constructor"
jQuery(document).ready(function(){
init();
});
} // UniteSettings class end
| fwahyudi17/ofiskita | system/configa/revslider/js/settings.js | JavaScript | gpl-3.0 | 9,972 |
package cloudstack
import (
"fmt"
"io/ioutil"
"regexp"
"github.com/hashicorp/packer/packer"
"github.com/mitchellh/multistep"
"github.com/xanzy/go-cloudstack/cloudstack"
)
type stepPrepareConfig struct{}
func (s *stepPrepareConfig) Run(state multistep.StateBag) multistep.StepAction {
client := state.Get("client").(*cloudstack.CloudStackClient)
config := state.Get("config").(*Config)
ui := state.Get("ui").(packer.Ui)
ui.Say("Preparing config...")
var err error
var errs *packer.MultiError
// First get the project and zone UUID's so we can use them in other calls when needed.
if config.Project != "" && !isUUID(config.Project) {
config.Project, _, err = client.Project.GetProjectID(config.Project)
if err != nil {
errs = packer.MultiErrorAppend(errs, &retrieveErr{"project", config.Project, err})
}
}
if config.UserDataFile != "" {
userdata, err := ioutil.ReadFile(config.UserDataFile)
if err != nil {
errs = packer.MultiErrorAppend(errs, fmt.Errorf("problem reading user data file: %s", err))
}
config.UserData = string(userdata)
}
if !isUUID(config.Zone) {
config.Zone, _, err = client.Zone.GetZoneID(config.Zone)
if err != nil {
errs = packer.MultiErrorAppend(errs, &retrieveErr{"zone", config.Zone, err})
}
}
// Then try to get the remaining UUID's.
if config.DiskOffering != "" && !isUUID(config.DiskOffering) {
config.DiskOffering, _, err = client.DiskOffering.GetDiskOfferingID(config.DiskOffering)
if err != nil {
errs = packer.MultiErrorAppend(errs, &retrieveErr{"disk offering", config.DiskOffering, err})
}
}
if config.PublicIPAddress != "" && !isUUID(config.PublicIPAddress) {
// Save the public IP address before replacing it with it's UUID.
config.hostAddress = config.PublicIPAddress
p := client.Address.NewListPublicIpAddressesParams()
p.SetIpaddress(config.PublicIPAddress)
if config.Project != "" {
p.SetProjectid(config.Project)
}
ipAddrs, err := client.Address.ListPublicIpAddresses(p)
if err != nil {
errs = packer.MultiErrorAppend(errs, &retrieveErr{"IP address", config.PublicIPAddress, err})
}
if err == nil && ipAddrs.Count != 1 {
errs = packer.MultiErrorAppend(errs, &retrieveErr{"IP address", config.PublicIPAddress, ipAddrs})
}
if err == nil && ipAddrs.Count == 1 {
config.PublicIPAddress = ipAddrs.PublicIpAddresses[0].Id
}
}
if !isUUID(config.Network) {
config.Network, _, err = client.Network.GetNetworkID(config.Network, cloudstack.WithProject(config.Project))
if err != nil {
errs = packer.MultiErrorAppend(errs, &retrieveErr{"network", config.Network, err})
}
}
if !isUUID(config.ServiceOffering) {
config.ServiceOffering, _, err = client.ServiceOffering.GetServiceOfferingID(config.ServiceOffering)
if err != nil {
errs = packer.MultiErrorAppend(errs, &retrieveErr{"service offering", config.ServiceOffering, err})
}
}
if config.SourceISO != "" {
if isUUID(config.SourceISO) {
config.instanceSource = config.SourceISO
} else {
config.instanceSource, _, err = client.ISO.GetIsoID(config.SourceISO, "executable", config.Zone)
if err != nil {
errs = packer.MultiErrorAppend(errs, &retrieveErr{"ISO", config.SourceISO, err})
}
}
}
if config.SourceTemplate != "" {
if isUUID(config.SourceTemplate) {
config.instanceSource = config.SourceTemplate
} else {
config.instanceSource, _, err = client.Template.GetTemplateID(config.SourceTemplate, "executable", config.Zone)
if err != nil {
errs = packer.MultiErrorAppend(errs, &retrieveErr{"template", config.SourceTemplate, err})
}
}
}
if !isUUID(config.TemplateOS) {
p := client.GuestOS.NewListOsTypesParams()
p.SetDescription(config.TemplateOS)
types, err := client.GuestOS.ListOsTypes(p)
if err != nil {
errs = packer.MultiErrorAppend(errs, &retrieveErr{"OS type", config.TemplateOS, err})
}
if err == nil && types.Count != 1 {
errs = packer.MultiErrorAppend(errs, &retrieveErr{"OS type", config.TemplateOS, types})
}
if err == nil && types.Count == 1 {
config.TemplateOS = types.OsTypes[0].Id
}
}
// This is needed because nil is not always nil. When returning *packer.MultiError(nil)
// as an error interface, that interface will no longer be equal to nil but it will be
// an interface with type *packer.MultiError and value nil which is different then a
// nil interface.
if errs != nil && len(errs.Errors) > 0 {
ui.Error(errs.Error())
return multistep.ActionHalt
}
ui.Message("Config has been prepared!")
return multistep.ActionContinue
}
func (s *stepPrepareConfig) Cleanup(state multistep.StateBag) {
// Nothing to cleanup for this step.
}
type retrieveErr struct {
name string
value string
result interface{}
}
func (e *retrieveErr) Error() string {
if err, ok := e.result.(error); ok {
e.result = err.Error()
}
return fmt.Sprintf("Error retrieving UUID of %s %s: %v", e.name, e.value, e.result)
}
var uuidRegex = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
func isUUID(uuid string) bool {
return uuidRegex.MatchString(uuid)
}
| dayglojesus/packer | builder/cloudstack/step_prepare_config.go | GO | mpl-2.0 | 5,108 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace Hatfield.EnviroData.DataAcquisition.XML
{
public class XMLDataSourceLocation: IDataSourceLocation
{
public string _elementName;
public string _attributeName;
public int _index = 0;
public XMLDataSourceLocation(string elementName, string attributeName)
{
_elementName = elementName;
_attributeName = attributeName;
}
public XMLDataSourceLocation(string elementName, string attributeName, int index)
{
_elementName = elementName;
_attributeName = attributeName;
_index = index;
}
public string AttributeName
{
get
{
return _attributeName;
}
}
public string ElementName
{
get
{
return _elementName;
}
}
public int Index
{
get
{
return _index;
}
}
public override string ToString()
{
return string.Format("Node: {0}, {1}", _elementName, _attributeName);
}
}
}
| HatfieldConsultants/Hatfield.EnviroData.DataAcquisition | Source/Hatfield.EnviroData.DataAcquisition.XML/XMLDataSourceLocation.cs | C# | mpl-2.0 | 1,295 |
package cabf_br
/*
* ZLint Copyright 2021 Regents of the University of Michigan
*
* 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.
*/
import (
"github.com/zmap/zcrypto/x509"
"github.com/zmap/zlint/v3/lint"
"github.com/zmap/zlint/v3/util"
)
type subCertAiaMissing struct{}
/**************************************************************************************************
BRs: 7.1.2.3
authorityInformationAccess
With the exception of stapling, which is noted below, this extension MUST be present. It MUST NOT be
marked critical, and it MUST contain the HTTP URL of the Issuing CA’s OCSP responder (accessMethod
= 1.3.6.1.5.5.7.48.1). It SHOULD also contain the HTTP URL of the Issuing CA’s certificate
(accessMethod = 1.3.6.1.5.5.7.48.2). See Section 13.2.1 for details.
***************************************************************************************************/
func init() {
lint.RegisterLint(&lint.Lint{
Name: "e_sub_cert_aia_missing",
Description: "Subscriber Certificate: authorityInformationAccess MUST be present.",
Citation: "BRs: 7.1.2.3",
Source: lint.CABFBaselineRequirements,
EffectiveDate: util.CABEffectiveDate,
Lint: NewSubCertAiaMissing,
})
}
func NewSubCertAiaMissing() lint.LintInterface {
return &subCertAiaMissing{}
}
func (l *subCertAiaMissing) CheckApplies(c *x509.Certificate) bool {
return !util.IsCACert(c)
}
func (l *subCertAiaMissing) Execute(c *x509.Certificate) *lint.LintResult {
if util.IsExtInCert(c, util.AiaOID) {
return &lint.LintResult{Status: lint.Pass}
} else {
return &lint.LintResult{Status: lint.Error}
}
}
| jcjones/boulder | vendor/github.com/zmap/zlint/v3/lints/cabf_br/lint_sub_cert_aia_missing.go | GO | mpl-2.0 | 2,127 |
/**
* This file is part of mycollab-mobile.
*
* mycollab-mobile 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.
*
* mycollab-mobile 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 mycollab-mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.esofthead.mycollab.mobile.module.project.view;
import com.esofthead.mycollab.mobile.mvp.AbstractPresenter;
import com.esofthead.mycollab.vaadin.mvp.ScreenData;
import com.vaadin.addon.touchkit.ui.NavigationManager;
import com.vaadin.ui.ComponentContainer;
/**
* @author MyCollab Ltd.
*
* @since 4.4.0
*
*/
public class ProjectLoginPresenter extends AbstractPresenter<ProjectLoginView> {
private static final long serialVersionUID = -750325026975907368L;
public ProjectLoginPresenter() {
super(ProjectLoginView.class);
}
@Override
protected void onGo(ComponentContainer navigationManager, ScreenData<?> data) {
((NavigationManager) navigationManager).navigateTo(view.getWidget());
}
}
| maduhu/mycollab | mycollab-mobile/src/main/java/com/esofthead/mycollab/mobile/module/project/view/ProjectLoginPresenter.java | Java | agpl-3.0 | 1,424 |
using System;
namespace ACE.Server.Network.GameAction.Actions
{
public static class GameActionUseItem
{
[GameAction(GameActionType.Use)]
public static void Handle(ClientMessage message, Session session)
{
uint itemGuid = message.Payload.ReadUInt32();
//Console.WriteLine($"{session.Player.Name}.GameAction 0x36 - Use({itemGuid:X8})");
session.Player.HandleActionUseItem(itemGuid);
}
}
}
| LtRipley36706/ACE | Source/ACE.Server/Network/GameAction/Actions/GameActionUseItem.cs | C# | agpl-3.0 | 470 |
<?php
/**
* class.reportTables.php
*
* @package workflow.engine.ProcessMaker
*
* ProcessMaker Open Source Edition
* Copyright (C) 2004 - 2011 Colosa Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, contact Colosa Inc, 2566 Le Jeune Rd.,
* Coral Gables, FL, 33134, USA, or email info@colosa.com.
*
*/
G::LoadClass( 'case' );
/**
* ReportTables - Report tables class
*
* @package workflow.engine.ProcessMaker
* @author Julio Cesar Laura Avenda�o
* @copyright 2007 COLOSA
*/
class ReportTables
{
private $aDef = array ('mysql' => array ('number' => 'DOUBLE','char' => 'VARCHAR(255)','text' => 'TEXT','date' => 'DATETIME'
),'pgsql' => array ('number' => 'DOUBLE','char' => 'VARCHAR(255)','text' => 'TEXT','date' => 'DATETIME'
),'mssql' => array ('number' => 'FLOAT','char' => 'NVARCHAR(255)','text' => 'TEXT','date' => 'CHAR(19)'
) /* Changed DATETIME CHAR(19) for compatibility issues. */ );
//private $sPrefix = 'REP_';
private $sPrefix = '';
/**
* Function deleteAllReportVars
* This function delete all reports
*
* @access public
* @param string $$sRepTabUid
* @return void
*/
public function deleteAllReportVars ($sRepTabUid = '')
{
try {
$oCriteria = new Criteria( 'workflow' );
$oCriteria->add( ReportVarPeer::REP_TAB_UID, $sRepTabUid );
ReportVarPeer::doDelete( $oCriteria );
} catch (Exception $oError) {
throw ($oError);
}
}
/**
* Function prepareQuery
* This function removes the table
*
* @access public
* @param string $sTableName Table name
* @param string $sConnection Conexion
* @return void
*/
public function dropTable ($sTableName, $sConnection = 'report')
{
$sTableName = $this->sPrefix . $sTableName;
//we have to do the propel connection
$PropelDatabase = $this->chooseDB( $sConnection );
$con = Propel::getConnection( $PropelDatabase );
$stmt = $con->createStatement();
try {
switch (DB_ADAPTER) {
case 'mysql':
$rs = $stmt->executeQuery( 'DROP TABLE IF EXISTS `' . $sTableName . '`' );
break;
case 'mssql':
$rs = $stmt->executeQuery( "IF OBJECT_ID (N'" . $sTableName . "', N'U') IS NOT NULL
DROP TABLE [" . $sTableName . "]" );
break;
}
} catch (Exception $oError) {
throw ($oError);
}
}
/**
* Function createTable
* This Function creates the table
*
* @access public
* @param string $sTableName Table name
* @param string $sConnection Connection name
* @param string $sType
* @param array $aFields
* @param string $bDefaultFields
* @return void
*/
public function createTable ($sTableName, $sConnection = 'report', $sType = 'NORMAL', $aFields = array(), $bDefaultFields = true)
{
$sTableName = $this->sPrefix . $sTableName;
//we have to do the propel connection
$PropelDatabase = $this->chooseDB( $sConnection );
$con = Propel::getConnection( $PropelDatabase );
$stmt = $con->createStatement();
try {
switch (DB_ADAPTER) {
case 'mysql':
$sQuery = 'CREATE TABLE IF NOT EXISTS `' . $sTableName . '` (';
if ($bDefaultFields) {
$sQuery .= "`APP_UID` VARCHAR(32) NOT NULL DEFAULT '',`APP_NUMBER` INT NOT NULL,";
if ($sType == 'GRID') {
$sQuery .= "`ROW` INT NOT NULL,";
}
}
foreach ($aFields as $aField) {
switch ($aField['sType']) {
case 'number':
$sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NOT NULL DEFAULT '0',";
break;
case 'char':
$sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NOT NULL DEFAULT '',";
break;
case 'text':
$sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " ,";
break;
case 'date':
$sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NULL,";
break;
}
}
if ($bDefaultFields) {
$sQuery .= 'PRIMARY KEY (APP_UID' . ($sType == 'GRID' ? ',ROW' : '') . ')) ';
}
$sQuery .= ' DEFAULT CHARSET=utf8;';
$rs = $stmt->executeQuery( $sQuery );
break;
case 'mssql':
$sQuery = 'CREATE TABLE [' . $sTableName . '] (';
if ($bDefaultFields) {
$sQuery .= "[APP_UID] VARCHAR(32) NOT NULL DEFAULT '', [APP_NUMBER] INT NOT NULL,";
if ($sType == 'GRID') {
$sQuery .= "[ROW] INT NOT NULL,";
}
}
foreach ($aFields as $aField) {
switch ($aField['sType']) {
case 'number':
$sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NOT NULL DEFAULT '0',";
break;
case 'char':
$sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NOT NULL DEFAULT '',";
break;
case 'text':
$sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NOT NULL DEFAULT '',";
break;
case 'date':
$sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NULL,";
break;
}
}
if ($bDefaultFields) {
$sQuery .= 'PRIMARY KEY (APP_UID' . ($sType == 'GRID' ? ',ROW' : '') . ')) ';
} else {
$sQuery .= ' ';
}
$rs = $stmt->executeQuery( $sQuery );
break;
}
} catch (Exception $oError) {
throw ($oError);
}
}
/**
* Function populateTable
* This Function fills the table
*
* @access public
* @param string $sTableName Table name
* @param string $sConnection Connection name
* @param string $sType
* @param array $aFields
* @param string $sProcessUid
* @param string $sGrid
* @return void
*/
public function populateTable ($sTableName, $sConnection = 'report', $sType = 'NORMAL', $aFields = array(), $sProcessUid = '', $sGrid = '')
{
$sTableName = $this->sPrefix . $sTableName;
//we have to do the propel connection
$PropelDatabase = $this->chooseDB( $sConnection );
$con = Propel::getConnection( $PropelDatabase );
$stmt = $con->createStatement();
if ($sType == 'GRID') {
$aAux = explode( '-', $sGrid );
$sGrid = $aAux[0];
}
try {
switch (DB_ADAPTER) {
case 'mysql':
//select cases for this Process, ordered by APP_NUMBER
$oCriteria = new Criteria( 'workflow' );
$oCriteria->add( ApplicationPeer::PRO_UID, $sProcessUid );
$oCriteria->addAscendingOrderByColumn( ApplicationPeer::APP_NUMBER );
$oDataset = ApplicationPeer::doSelectRS( $oCriteria );
$oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC );
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$aData = unserialize( $aRow['APP_DATA'] );
//delete previous record from this report table ( previous records in case this is a grid )
$deleteSql = 'DELETE FROM `' . $sTableName . "` WHERE APP_UID = '" . $aRow['APP_UID'] . "'";
$rsDel = $stmt->executeQuery( $deleteSql );
if ($sType == 'NORMAL') {
$sQuery = 'INSERT INTO `' . $sTableName . '` (';
$sQuery .= '`APP_UID`,`APP_NUMBER`';
foreach ($aFields as $aField) {
$sQuery .= ',`' . $aField['sFieldName'] . '`';
}
$sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER'];
foreach ($aFields as $aField) {
switch ($aField['sType']) {
case 'number':
$sQuery .= ',' . (isset( $aData[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aData[$aField['sFieldName']] ) : '0');
break;
case 'char':
case 'text':
if (! isset( $aData[$aField['sFieldName']] )) {
$aData[$aField['sFieldName']] = '';
}
$sQuery .= ",'" . (isset( $aData[$aField['sFieldName']] ) ? @mysql_real_escape_string( $aData[$aField['sFieldName']] ) : '') . "'";
break;
case 'date':
$value = (isset( $aData[$aField['sFieldName']] ) && trim( $aData[$aField['sFieldName']] )) != '' ? "'" . $aData[$aField['sFieldName']] . "'" : 'NULL';
$sQuery .= "," . $value;
break;
}
}
$sQuery .= ')';
$rs = $stmt->executeQuery( $sQuery );
} else {
if (isset( $aData[$sGrid] )) {
foreach ($aData[$sGrid] as $iRow => $aGridRow) {
$sQuery = 'INSERT INTO `' . $sTableName . '` (';
$sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`';
foreach ($aFields as $aField) {
$sQuery .= ',`' . $aField['sFieldName'] . '`';
}
$sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER'] . ',' . $iRow;
foreach ($aFields as $aField) {
switch ($aField['sType']) {
case 'number':
$sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0');
break;
case 'char':
case 'text':
if (! isset( $aGridRow[$aField['sFieldName']] )) {
$aGridRow[$aField['sFieldName']] = '';
}
$sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'";
break;
case 'date':
$value = (isset( $aGridRow[$aField['sFieldName']] ) && trim( $aGridRow[$aField['sFieldName']] )) != '' ? "'" . $aGridRow[$aField['sFieldName']] . "'" : 'NULL';
$sQuery .= "," . $value;
break;
}
}
$sQuery .= ')';
$rs = $stmt->executeQuery( $sQuery );
}
}
}
$oDataset->next();
}
break;
/**
* For SQLServer code
*/
case 'mssql':
$oCriteria = new Criteria( 'workflow' );
$oCriteria->add( ApplicationPeer::PRO_UID, $sProcessUid );
$oCriteria->addAscendingOrderByColumn( ApplicationPeer::APP_NUMBER );
$oDataset = ApplicationPeer::doSelectRS( $oCriteria );
$oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC );
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$aData = unserialize( $aRow['APP_DATA'] );
mysql_query( 'DELETE FROM [' . $sTableName . "] WHERE APP_UID = '" . $aRow['APP_UID'] . "'" );
if ($sType == 'NORMAL') {
$sQuery = 'INSERT INTO [' . $sTableName . '] (';
$sQuery .= '[APP_UID],[APP_NUMBER]';
foreach ($aFields as $aField) {
$sQuery .= ',[' . $aField['sFieldName'] . ']';
}
$sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER'];
foreach ($aFields as $aField) {
switch ($aField['sType']) {
case 'number':
$sQuery .= ',' . (isset( $aData[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aData[$aField['sFieldName']] ) : '0');
break;
case 'char':
case 'text':
if (! isset( $aData[$aField['sFieldName']] )) {
$aData[$aField['sFieldName']] = '';
}
$sQuery .= ",'" . (isset( $aData[$aField['sFieldName']] ) ? mysql_real_escape_string( $aData[$aField['sFieldName']] ) : '') . "'";
break;
case 'date':
$sQuery .= ",'" . (isset( $aData[$aField['sFieldName']] ) ? $aData[$aField['sFieldName']] : '') . "'";
break;
}
}
$sQuery .= ')';
$rs = $stmt->executeQuery( $sQuery );
} else {
if (isset( $aData[$sGrid] )) {
foreach ($aData[$sGrid] as $iRow => $aGridRow) {
$sQuery = 'INSERT INTO [' . $sTableName . '] (';
$sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`';
foreach ($aFields as $aField) {
$sQuery .= ',[' . $aField['sFieldName'] . ']';
}
$sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER'] . ',' . $iRow;
foreach ($aFields as $aField) {
switch ($aField['sType']) {
case 'number':
$sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0');
break;
case 'char':
case 'text':
if (! isset( $aGridRow[$aField['sFieldName']] )) {
$aGridRow[$aField['sFieldName']] = '';
}
$sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'";
break;
case 'date':
$sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? $aGridRow[$aField['sFieldName']] : '') . "'";
break;
}
}
$sQuery .= ')';
$rs = $stmt->executeQuery( $sQuery );
}
}
}
$oDataset->next();
}
break;
}
} catch (Exception $oError) {
throw ($oError);
}
}
/**
* Function getTableVars
*
* @access public
* @param string $sRepTabUid
* @param boolean $bWhitType
* @return void
*/
public function getTableVars ($sRepTabUid, $bWhitType = false)
{
try {
$oCriteria = new Criteria( 'workflow' );
$oCriteria->add( ReportVarPeer::REP_TAB_UID, $sRepTabUid );
$oDataset = ReportVarPeer::doSelectRS( $oCriteria );
$oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC );
$oDataset->next();
$aVars = array ();
$aImportedVars = array (); //This array will help to control if the variable already exist
while ($aRow = $oDataset->getRow()) {
if ($bWhitType) {
if (! in_array( $aRow['REP_VAR_NAME'], $aImportedVars )) {
$aImportedVars[] = $aRow['REP_VAR_NAME'];
$aVars[] = array ('sFieldName' => $aRow['REP_VAR_NAME'],'sType' => $aRow['REP_VAR_TYPE']
);
}
} else {
$aVars[] = $aRow['REP_VAR_NAME'];
}
$oDataset->next();
}
return $aVars;
} catch (Exception $oError) {
throw ($oError);
}
}
/**
* Function deleteReportTable
* This Function deletes report table
*
* @access public
* @param string $sRepTabUid
* @return void
*/
public function deleteReportTable ($sRepTabUid)
{
try {
$oReportTable = new ReportTable();
$aFields = $oReportTable->load( $sRepTabUid );
if (! (empty( $aFields ))) {
$this->dropTable( $aFields['REP_TAB_NAME'], $aFields['REP_TAB_CONNECTION'] );
$oCriteria = new Criteria( 'workflow' );
$oCriteria->add( ReportVarPeer::REP_TAB_UID, $sRepTabUid );
$oDataset = ReportVarPeer::doDelete( $oCriteria );
$oReportTable->remove( $sRepTabUid );
}
} catch (Exception $oError) {
throw ($oError);
}
}
/**
* Function getSplitDate
* This function gets the split date
*
* @access public
* @param date $date
* @param string $mask
* @return array
*/
public function getSplitDate ($date, $mask)
{
$sw1 = false;
for ($i = 0; $i < 3; $i ++) {
$item = substr( $mask, $i * 2, 1 );
switch ($item) {
case 'Y':
switch ($i) {
case 0:
$d1 = substr( $date, 0, 4 );
break;
case 1:
$d1 = substr( $date, 3, 4 );
break;
case 2:
$d1 = substr( $date, 6, 4 );
break;
}
$sw1 = true;
break;
case 'y':
switch ($i) {
case 0:
$d1 = substr( $date, 0, 2 );
break;
case 1:
$d1 = substr( $date, 3, 2 );
break;
case 2:
$d1 = substr( $date, 6, 2 );
break;
}
break;
case 'm':
switch ($i) {
case 0:
$d2 = substr( $date, 0, 2 );
break;
case 1:
$d2 = ($sw1) ? substr( $date, 5, 2 ) : substr( $date, 3, 2 );
break;
case 2:
$d2 = ($sw1) ? substr( $date, 8, 2 ) : substr( $date, 5, 2 );
break;
}
break;
case 'd':
switch ($i) {
case 0:
$d3 = substr( $date, 0, 2 );
break;
case 1:
$d3 = ($sw1) ? substr( $date, 5, 2 ) : substr( $date, 3, 2 );
break;
case 2:
$d3 = ($sw1) ? substr( $date, 8, 2 ) : substr( $date, 5, 2 );
break;
}
break;
}
}
return Array (isset( $d1 ) ? $d1 : '',isset( $d2 ) ? $d2 : '',isset( $d3 ) ? $d3 : ''
);
}
/**
* Function getFormatDate
* This function returns the date formated
*
* @access public
* @param date $sDate
* @param date $sMask
* @return date
*/
public function getFormatDate ($sDate, $sMask)
{
//print $sDate." *** ". $sMask."<BR>";
$dateTime = explode( " ", $sDate ); //To accept the Hour part
$aDate = explode( '-', str_replace( "/", "-", $dateTime[0] ) );
$bResult = true;
foreach ($aDate as $sDate) {
if (! is_numeric( $sDate )) {
$bResult = false;
break;
}
}
if ($sMask != '') {
$aDate = $this->getSplitDate( $dateTime[0], $sMask );
$aDate[0] = ($aDate[0] == '') ? date( 'Y' ) : $aDate[0];
$aDate[1] = ($aDate[1] == '') ? date( 'm' ) : $aDate[1];
$aDate[2] = ($aDate[2] == '') ? date( 'd' ) : $aDate[2];
if (checkdate( $aDate[1], $aDate[2], $aDate[0] )) {
} else {
return false;
}
}
$sDateC = '';
for ($i = 0; $i < count( $aDate ); $i ++) {
$sDateC .= (($i == 0) ? "" : "-") . $aDate[$i];
}
return ($sDateC);
}
/**
* Function updateTables
* This function updated the Report Tables
*
* @access public
* @param string $sProcessUid
* @param string $sApplicationUid
* @param string $iApplicationNumber
* @param string $aFields
* @return void
*/
public function updateTables ($sProcessUid, $sApplicationUid, $iApplicationNumber, $aFields)
{
try {
$c = new Criteria('workflow');
$c->addSelectColumn(BpmnProjectPeer::PRJ_UID);
$c->add(BpmnProjectPeer::PRJ_UID, $sProcessUid, Criteria::EQUAL);
$ds = ProcessPeer::doSelectRS($c);
$ds->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$ds->next();
$row = $ds->getRow();
$isBpmn = isset($row['PRJ_UID']);
if (!class_exists('ReportTablePeer')) {
require_once 'classes/model/ReportTablePeer.php';
}
//get all Active Report Tables
$oCriteria = new Criteria( 'workflow' );
$oCriteria->add( ReportTablePeer::PRO_UID, $sProcessUid );
$oCriteria->add( ReportTablePeer::REP_TAB_STATUS, 'ACTIVE' );
$oDataset = ReportTablePeer::doSelectRS( $oCriteria );
$oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC );
$oDataset->next();
$aVars = array ();
while ($aRow = $oDataset->getRow()) {
$aRow['REP_TAB_NAME'] = $this->sPrefix . $aRow['REP_TAB_NAME'];
$PropelDatabase = $this->chooseDB( $aRow['REP_TAB_CONNECTION'] );
$con = Propel::getConnection( $PropelDatabase );
$stmt = $con->createStatement();
switch (DB_ADAPTER) {
case 'mysql':
$aTableFields = $this->getTableVars( $aRow['REP_TAB_UID'], true );
if ($aRow['REP_TAB_TYPE'] == 'NORMAL') {
$sqlExists = "SELECT * FROM `" . $aRow['REP_TAB_NAME'] . "` WHERE APP_UID = '" . $sApplicationUid . "'";
$rsExists = $stmt->executeQuery( $sqlExists, ResultSet::FETCHMODE_ASSOC );
$rsExists->next();
$aRow2 = $rsExists->getRow();
if (is_array( $aRow2 )) {
$sQuery = 'UPDATE `' . $aRow['REP_TAB_NAME'] . '` SET ';
foreach ($aTableFields as $aField) {
$sQuery .= '`' . $aField['sFieldName'] . '` = ';
if(!$isBpmn && !isset($aFields[$aField['sFieldName']])){
foreach($aFields as $row){
if(is_array($row) && isset($row[count($row)])){
$aFields = $row[count($row)];
}
}
}
switch ($aField['sType']) {
case 'number':
$sQuery .= (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0') . ',';
break;
case 'char':
case 'text':
if (! isset( $aFields[$aField['sFieldName']] )) {
$aFields[$aField['sFieldName']] = '';
}
if (! isset( $aFields[$aField['sFieldName'] . '_label'] )) {
$aFields[$aField['sFieldName'] . '_label'] = '';
}
if(is_array($aFields[$aField['sFieldName']])){
$sQuery .= "'" . (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']][0] : '') . "',";
}else{
$sQuery .= '\'' . ((isset($aFields[$aField['sFieldName']]))? @mysql_real_escape_string($aFields[$aField['sFieldName']]) : '') . '\',';
}
break;
case 'date':
$mysqlDate = (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : '');
if ($mysqlDate != '') {
$mysqlDate = str_replace( '/', '-', $mysqlDate );
$mysqlDate = date( 'Y-m-d', strtotime( $mysqlDate ) );
}
$value = trim( $mysqlDate ) != '' ? "'" . $mysqlDate . "'" : 'NULL';
$sQuery .= $value . ",";
break;
}
}
$sQuery = substr( $sQuery, 0, - 1 );
$sQuery .= " WHERE APP_UID = '" . $sApplicationUid . "'";
} else {
$sQuery = 'INSERT INTO `' . $aRow['REP_TAB_NAME'] . '` (';
$sQuery .= '`APP_UID`,`APP_NUMBER`';
foreach ($aTableFields as $aField) {
$sQuery .= ',`' . $aField['sFieldName'] . '`';
}
$sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber;
foreach ($aTableFields as $aField) {
switch ($aField['sType']) {
case 'number':
$sQuery .= ',' . (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0');
break;
case 'char':
case 'text':
if (! isset( $aFields[$aField['sFieldName']] )) {
$aFields[$aField['sFieldName']] = '';
}
$sQuery .= ",'" . (isset( $aFields[$aField['sFieldName']] ) ? mysql_real_escape_string( $aFields[$aField['sFieldName']] ) : '') . "'";
break;
case 'date':
$mysqlDate = (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : '');
if ($mysqlDate != '') {
$mysqlDate = str_replace( '/', '-', $mysqlDate );
$mysqlDate = date( 'Y-m-d', strtotime( $mysqlDate ) );
}
$value = trim( $mysqlDate ) != '' ? "'" . $mysqlDate . "'" : 'NULL';
$sQuery .= "," . $value;
break;
}
}
$sQuery .= ')';
}
$rs = $stmt->executeQuery( $sQuery );
} else {
//remove old rows from database
$sqlDelete = 'DELETE FROM `' . $aRow['REP_TAB_NAME'] . "` WHERE APP_UID = '" . $sApplicationUid . "'";
$rsDelete = $stmt->executeQuery( $sqlDelete );
$aAux = explode( '-', $aRow['REP_TAB_GRID'] );
if (isset( $aFields[$aAux[0]] )) {
if (is_array($aFields[$aAux[0]])) {
foreach ($aFields[$aAux[0]] as $iRow => $aGridRow) {
$sQuery = 'INSERT INTO `' . $aRow['REP_TAB_NAME'] . '` (';
$sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`';
foreach ($aTableFields as $aField) {
$sQuery .= ',`' . $aField['sFieldName'] . '`';
}
$sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber . ',' . $iRow;
foreach ($aTableFields as $aField) {
switch ($aField['sType']) {
case 'number':
$sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0');
break;
case 'char':
case 'text':
if (! isset( $aGridRow[$aField['sFieldName']] )) {
$aGridRow[$aField['sFieldName']] = '';
}
$sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'";
break;
case 'date':
$sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? $aGridRow[$aField['sFieldName']] : '') . "'";
break;
}
}
$sQuery .= ')';
$rs = $stmt->executeQuery( $sQuery );
}
}
}
}
break;
/**
* For SQLServer code
*/
case 'mssql':
$aTableFields = $this->getTableVars( $aRow['REP_TAB_UID'], true );
if ($aRow['REP_TAB_TYPE'] == 'NORMAL') {
$oDataset2 = mssql_query( "SELECT * FROM [" . $aRow['REP_TAB_NAME'] . "] WHERE APP_UID = '" . $sApplicationUid . "'" );
if ($aRow2 = mssql_fetch_row( $oDataset2 )) {
$sQuery = 'UPDATE [' . $aRow['REP_TAB_NAME'] . '] SET ';
foreach ($aTableFields as $aField) {
$sQuery .= '[' . $aField['sFieldName'] . '] = ';
switch ($aField['sType']) {
case 'number':
$sQuery .= (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0') . ',';
break;
case 'char':
case 'text':
if (! isset( $aFields[$aField['sFieldName']] )) {
$aFields[$aField['sFieldName']] = '';
}
$sQuery .= "'" . (isset( $aFields[$aField['sFieldName']] ) ? mysql_real_escape_string( $aFields[$aField['sFieldName']] ) : '') . "',";
break;
case 'date':
$sQuery .= "'" . (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : '') . "',";
break;
}
}
$sQuery = substr( $sQuery, 0, - 1 );
$sQuery .= " WHERE APP_UID = '" . $sApplicationUid . "'";
} else {
$sQuery = 'INSERT INTO [' . $aRow['REP_TAB_NAME'] . '] (';
$sQuery .= '[APP_UID],[APP_NUMBER]';
foreach ($aTableFields as $aField) {
$sQuery .= ',[' . $aField['sFieldName'] . ']';
}
$sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber;
foreach ($aTableFields as $aField) {
switch ($aField['sType']) {
case 'number':
$sQuery .= ',' . (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0');
break;
case 'char':
case 'text':
if (! isset( $aFields[$aField['sFieldName']] )) {
$aFields[$aField['sFieldName']] = '';
}
$sQuery .= ",'" . (isset( $aFields[$aField['sFieldName']] ) ? mysql_real_escape_string( $aFields[$aField['sFieldName']] ) : '') . "'";
break;
case 'date':
$sQuery .= ",'" . (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : '') . "'";
break;
}
}
$sQuery .= ')';
}
$rs = $stmt->executeQuery( $sQuery );
} else {
mysql_query( 'DELETE FROM [' . $aRow['REP_TAB_NAME'] . "] WHERE APP_UID = '" . $sApplicationUid . "'" );
$aAux = explode( '-', $aRow['REP_TAB_GRID'] );
if (isset( $aFields[$aAux[0]] )) {
foreach ($aFields[$aAux[0]] as $iRow => $aGridRow) {
$sQuery = 'INSERT INTO [' . $aRow['REP_TAB_NAME'] . '] (';
$sQuery .= '[APP_UID],[APP_NUMBER],[ROW]';
foreach ($aTableFields as $aField) {
$sQuery .= ',[' . $aField['sFieldName'] . ']';
}
$sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber . ',' . $iRow;
foreach ($aTableFields as $aField) {
switch ($aField['sType']) {
case 'number':
$sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0');
break;
case 'char':
case 'text':
if (! isset( $aGridRow[$aField['sFieldName']] )) {
$aGridRow[$aField['sFieldName']] = '';
}
$sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'";
break;
case 'date':
$sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? $aGridRow[$aField['sFieldName']] : '') . "'";
break;
}
}
$sQuery .= ')';
$rs = $stmt->executeQuery( $sQuery );
}
}
}
break;
}
$oDataset->next();
}
} catch (Exception $oError) {
throw ($oError);
}
}
/**
* Function tableExist
* Check if table exists
*
* @access public
* @return boolean
*/
public function tableExist ()
{
/*
$bExists = true;
$oConnection = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME);
$oDataset = mysql_query('SELECT COUNT(*) FROM REPORT_TABLE') || ($bExists = false);
return $bExists;
*/
$bExists = true;
$sDataBase = 'database_' . strtolower( DB_ADAPTER );
if (G::LoadSystemExist( $sDataBase )) {
G::LoadSystem( $sDataBase );
$oDataBase = new database();
$bExists = $oDataBase->reportTableExist();
}
return $bExists;
}
/**
* Function chooseDB
* Choose the database to connect
*
* @access public
* @param string $TabConnectionk
* @return string
*/
public function chooseDB ($TabConnectionk)
{
$repTabConnection = trim( strtoupper( $TabConnectionk ) );
$PropelDatabase = 'rp';
if ($repTabConnection == '' || $repTabConnection == 'REPORT') {
$PropelDatabase = 'rp';
}
if ($repTabConnection == 'RBAC') {
$PropelDatabase = 'rbac';
}
if ($repTabConnection == 'WF') {
$PropelDatabase = 'workflow';
}
return ($PropelDatabase);
}
}
| BathnesDevelopment/processmaker-3.1.2.b2-community | workflow/engine/classes/class.reportTables.php | PHP | agpl-3.0 | 43,778 |
<?php
namespace League\OAuth2\Client\Provider;
use League\OAuth2\Client\Exception\HostedDomainException;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use League\OAuth2\Client\Token\AccessToken;
use League\OAuth2\Client\Tool\BearerAuthorizationTrait;
use Psr\Http\Message\ResponseInterface;
class Google extends AbstractProvider
{
use BearerAuthorizationTrait;
/**
* @var string If set, this will be sent to google as the "access_type" parameter.
* @link https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters
*/
protected $accessType;
/**
* @var string If set, this will be sent to google as the "hd" parameter.
* @link https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters
*/
protected $hostedDomain;
/**
* @var string If set, this will be sent to google as the "prompt" parameter.
* @link https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters
*/
protected $prompt;
/**
* @var array List of scopes that will be used for authentication.
* @link https://developers.google.com/identity/protocols/googlescopes
*/
protected $scopes = [];
public function getBaseAuthorizationUrl()
{
return 'https://accounts.google.com/o/oauth2/v2/auth';
}
public function getBaseAccessTokenUrl(array $params)
{
return 'https://oauth2.googleapis.com/token';
}
public function getResourceOwnerDetailsUrl(AccessToken $token)
{
return 'https://openidconnect.googleapis.com/v1/userinfo';
}
protected function getAuthorizationParameters(array $options)
{
if (empty($options['hd']) && $this->hostedDomain) {
$options['hd'] = $this->hostedDomain;
}
if (empty($options['access_type']) && $this->accessType) {
$options['access_type'] = $this->accessType;
}
if (empty($options['prompt']) && $this->prompt) {
$options['prompt'] = $this->prompt;
}
// Default scopes MUST be included for OpenID Connect.
// Additional scopes MAY be added by constructor or option.
$scopes = array_merge($this->getDefaultScopes(), $this->scopes);
if (!empty($options['scope'])) {
$scopes = array_merge($scopes, $options['scope']);
}
$options['scope'] = array_unique($scopes);
$options = parent::getAuthorizationParameters($options);
// The "approval_prompt" MUST be removed as it is not supported by Google, use "prompt" instead:
// https://developers.google.com/identity/protocols/oauth2/openid-connect#prompt
unset($options['approval_prompt']);
return $options;
}
protected function getDefaultScopes()
{
// "openid" MUST be the first scope in the list.
return [
'openid',
'email',
'profile',
];
}
protected function getScopeSeparator()
{
return ' ';
}
protected function checkResponse(ResponseInterface $response, $data)
{
// @codeCoverageIgnoreStart
if (empty($data['error'])) {
return;
}
// @codeCoverageIgnoreEnd
$code = 0;
$error = $data['error'];
if (is_array($error)) {
$code = $error['code'];
$error = $error['message'];
}
throw new IdentityProviderException($error, $code, $data);
}
protected function createResourceOwner(array $response, AccessToken $token)
{
$user = new GoogleUser($response);
$this->assertMatchingDomain($user->getHostedDomain());
return $user;
}
/**
* @throws HostedDomainException If the domain does not match the configured domain.
*/
protected function assertMatchingDomain($hostedDomain)
{
if ($this->hostedDomain === null) {
// No hosted domain configured.
return;
}
if ($this->hostedDomain === '*' && $hostedDomain) {
// Any hosted domain is allowed.
return;
}
if ($this->hostedDomain === $hostedDomain) {
// Hosted domain is correct.
return;
}
throw HostedDomainException::notMatchingDomain($this->hostedDomain);
}
}
| colosa/processmaker | vendor/league/oauth2-google/src/Provider/Google.php | PHP | agpl-3.0 | 4,424 |
define([
'database',
'backbone'
], function (DB, Backbone) {
var MessageModel = Backbone.Model.extend({
defaults: {
messageId: 0,
sender: '',
title: '',
content: '',
hasAttachment: false,
sendDate: new Date(),
url: ''
},
save: function (attributes) {
var deferred = $.Deferred();
var self = this;
var transaction = DB.conx.transaction([
DB.TABLE_MESSAGE
], 'readwrite');
var store = transaction.objectStore(DB.TABLE_MESSAGE);
var request;
if (!attributes) {
request = store.add(this.toJSON());
} else {
self.set(attributes);
request = store.put(this.toJSON(), this.cid);
}
request.onsuccess = function (e) {
if (!attributes) {
self.cid = e.target.result;
}
deferred.resolve();
};
request.onerror = function () {
deferred.reject();
};
return deferred.promise();
},
getData: function (cid) {
var self = this;
var deferred = $.Deferred();
var transaction = DB.conx.transaction([
DB.TABLE_MESSAGE
]);
var store = transaction.objectStore(DB.TABLE_MESSAGE);
var request = store.get(cid);
request.onsuccess = function (e) {
if (request.result) {
var data = request.result;
self.cid = cid;
self.set(data);
deferred.resolve();
} else {
deferred.reject();
}
};
request.onerror = function () {
deferred.reject();
};
return deferred.promise();
},
getNext: function (currentKey) {
var deferred = $.Deferred();
var range = IDBKeyRange.lowerBound(this.get('messageId'), true);
var transaction = DB.conx.transaction([
DB.TABLE_MESSAGE
], 'readonly');
var store = transaction.objectStore(DB.TABLE_MESSAGE);
var index = store.index('messageId');
var request = index.openCursor(range);
request.onsuccess = function (e) {
var nextMessage = null;
var cursor = e.target.result;
if (cursor) {
nextMessage = new MessageModel(cursor.value);
nextMessage.cid = cursor.primaryKey;
}
deferred.resolve(nextMessage);
};
request.onerror = function () {
deferred.reject();
};
return deferred.promise();
},
getPrevious: function () {
var deferred = $.Deferred();
var range = IDBKeyRange.upperBound(this.get('messageId'), true);
var transaction = DB.conx.transaction([
DB.TABLE_MESSAGE
], 'readonly');
var store = transaction.objectStore(DB.TABLE_MESSAGE);
var index = store.index('messageId');
var request = index.openCursor(range, 'prev');
request.onsuccess = function (e) {
var previousMessage = null;
var cursor = e.target.result;
if (cursor) {
previousMessage = new MessageModel(cursor.value);
previousMessage.cid = cursor.primaryKey;
}
deferred.resolve(previousMessage);
};
request.onerror = function () {
deferred.reject();
};
return deferred.promise();
},
delete: function () {
var deferred = $.Deferred();
var transaction = DB.conx.transaction([
DB.TABLE_MESSAGE
], 'readwrite');
var store = transaction.objectStore(DB.TABLE_MESSAGE);
var request = store.clear();
request.onsuccess = function () {
deferred.resolve();
};
request.onerror = function () {
deferred.reject();
};
return deferred.promise();
}
});
return MessageModel;
});
| sanyaade-teachings/mobile-messaging | www/js/models/message.js | JavaScript | agpl-3.0 | 4,522 |
/*
* sones GraphDB - Community Edition - http://www.sones.com
* Copyright (C) 2007-2011 sones GmbH
*
* This file is part of sones GraphDB Community Edition.
*
* sones GraphDB is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* sones GraphDB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with sones GraphDB. If not, see <http://www.gnu.org/licenses/>.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IdentityModel.Selectors;
using sones.GraphDSServer;
using System.IdentityModel.Tokens;
using System.Diagnostics;
using sones.GraphDB;
using sones.Library.VersionedPluginManager;
using sones.GraphDS.PluginManager;
using sones.Library.Commons.Security;
using System.Net;
using System.Threading;
using sones.GraphDB.Manager.Plugin;
using System.IO;
using System.Globalization;
using sones.Library.DiscordianDate;
using System.Security.AccessControl;
using sones.GraphDSServer.ErrorHandling;
using sones.GraphDS.GraphDSRemoteClient;
using sones.GraphDS.GraphDSRESTClient;
using sones.GraphDB.TypeSystem;
using sones.GraphDB.Request;
using sones.Library.PropertyHyperGraph;
using sones.GraphQL.Result;
using sones.Library.Network.HttpServer;
namespace TagExampleWithGraphMappingFramework
{
public class TagExampleWithGraphMappingFramework
{
#region sones GraphDB Startup
private bool quiet = false;
private bool shutdown = false;
private IGraphDSServer _dsServer;
private bool _ctrlCPressed;
private IGraphDSClient GraphDSClient;
private sones.Library.Commons.Security.SecurityToken SecToken;
private long TransToken;
public TagExampleWithGraphMappingFramework(String[] myArgs)
{
Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-us");
if (myArgs.Count() > 0)
{
foreach (String parameter in myArgs)
{
if (parameter.ToUpper() == "--Q")
quiet = true;
}
}
#region Start RemoteAPI, WebDAV and WebAdmin services, send GraphDS notification
IGraphDB GraphDB;
GraphDB = new SonesGraphDB(null, true, new CultureInfo("en-us"));
#region Configure PlugIns
// Plugins are loaded by the GraphDS with their according PluginDefinition and only if they are listed
// below - there is no auto-discovery for plugin types in GraphDS (!)
#region Query Languages
// the GQL Query Language Plugin needs the GraphDB instance as a parameter
List<PluginDefinition> QueryLanguages = new List<PluginDefinition>();
Dictionary<string, object> GQL_Parameters = new Dictionary<string, object>();
GQL_Parameters.Add("GraphDB", GraphDB);
QueryLanguages.Add(new PluginDefinition("sones.gql", GQL_Parameters));
#endregion
#region GraphDS Service Plugins
List<PluginDefinition> GraphDSServices = new List<PluginDefinition>();
#endregion
List<PluginDefinition> UsageDataCollector = new List<PluginDefinition>();
#endregion
GraphDSPlugins PluginsAndParameters = new GraphDSPlugins(QueryLanguages);
_dsServer = new GraphDS_Server(GraphDB, PluginsAndParameters);
#region Start GraphDS Services
#region Remote API Service
Dictionary<string, object> RemoteAPIParameter = new Dictionary<string, object>();
RemoteAPIParameter.Add("IPAddress", IPAddress.Parse("127.0.0.1"));
RemoteAPIParameter.Add("Port", (ushort)9970);
_dsServer.StartService("sones.RemoteAPIService", RemoteAPIParameter);
#endregion
#endregion
#endregion
#endregion
#region Some helping lines...
if (!quiet)
{
Console.WriteLine("This GraphDB Instance offers the following options:");
Console.WriteLine(" * If you want to suppress console output add --Q as a");
Console.WriteLine(" parameter.");
Console.WriteLine();
Console.WriteLine(" * the following GraphDS Service Plugins are initialized and started: ");
foreach (var Service in _dsServer.AvailableServices)
{
Console.WriteLine(" * " + Service.PluginName);
}
Console.WriteLine();
foreach (var Service in _dsServer.AvailableServices)
{
Console.WriteLine(Service.ServiceDescription);
Console.WriteLine();
}
Console.WriteLine("Enter 'shutdown' to initiate the shutdown of this instance.");
}
Run();
Console.CancelKeyPress += OnCancelKeyPress;
while (!shutdown)
{
String command = Console.ReadLine();
if (!_ctrlCPressed)
{
if (command != null)
{
if (command.ToUpper() == "SHUTDOWN")
shutdown = true;
}
}
}
Console.WriteLine("Shutting down GraphDS Server");
_dsServer.Shutdown(null);
Console.WriteLine("Shutdown complete");
#endregion
}
#region Cancel KeyPress
/// <summary>
/// Cancel KeyPress
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public virtual void OnCancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
e.Cancel = true; //do not abort Console here.
_ctrlCPressed = true;
Console.Write("Shutdown GraphDB (y/n)?");
string input;
do
{
input = Console.ReadLine();
} while (input == null);
switch (input.ToUpper())
{
case "Y":
shutdown = true;
return;
default:
shutdown = false;
return;
}
}//method
#endregion
#region the actual example
public void Run()
{
GraphDSClient = new GraphDS_RemoteClient(new Uri("http://localhost:9970/rpc"));
SecToken = GraphDSClient.LogOn(new RemoteUserPasswordCredentials("test", "test"));
TransToken = GraphDSClient.BeginTransaction(SecToken);
GraphDSClient.Clear<IRequestStatistics>(SecToken, TransToken, new RequestClear(), (Statistics, DeletedTypes) => Statistics);
#region create types, create instances and additional work using the GraphDB API
GraphDSClient.Clear<IRequestStatistics>(SecToken, TransToken, new RequestClear(), (Statistics, DeletedTypes) => Statistics);
Console.WriteLine("Press enter to start example");
Console.ReadLine();
GraphDBRequests();
#endregion
//clear the DB (delete all created types) to create them again using the QueryLanguage
GraphDSClient.Clear<IRequestStatistics>(SecToken, TransToken, new RequestClear(), (Statistics, DeletedTypes) => Statistics);
#region create some types and insert values using the SonesQueryLanguage
GraphQLQueries();
#endregion
#region make some SELECTS
SELECTS();
#endregion
Console.WriteLine();
Console.WriteLine("Finished Example. Type a key to finish!");
Console.ReadKey();
}
private void GraphDBRequests()
{
Console.WriteLine("performing DB requests...");
#region define type "Tag"
//create a VertexTypePredefinition
var Tag_VertexTypePredefinition = new VertexTypePredefinition("Tag");
//create property
var PropertyName = new PropertyPredefinition("Name", "String")
.SetComment("This is a property on type 'Tag' named 'Name' and is of type 'String'");
//add property
Tag_VertexTypePredefinition.AddProperty(PropertyName);
//create outgoing edge to "Website"
var OutgoingEdgesTaggedWebsites = new OutgoingEdgePredefinition("TaggedWebsites", "Website")
.SetMultiplicityAsMultiEdge()
.SetComment(@"This is an outgoing edge on type 'Tag' wich points to the type 'Website' (the AttributeType)
and is defined as 'MultiEdge', which means that this edge can contain multiple single edges");
//add outgoing edge
Tag_VertexTypePredefinition.AddOutgoingEdge(OutgoingEdgesTaggedWebsites);
#endregion
#region define type "Website"
//create a VertexTypePredefinition
var Website_VertexTypePredefinition = new VertexTypePredefinition("Website");
//create properties
PropertyName = new PropertyPredefinition("Name", "String")
.SetComment("This is a property on type 'Website' named 'Name' and is of type 'String'");
var PropertyUrl = new PropertyPredefinition("URL", "String")
.SetAsMandatory();
//add properties
Website_VertexTypePredefinition.AddProperty(PropertyName);
Website_VertexTypePredefinition.AddProperty(PropertyUrl);
#region create an index on type "Website" on property "Name"
//there are three ways to set an index on property "Name"
//Beware: Use just one of them!
//1. create an index definition and specifie the property- and type name
var MyIndex = new IndexPredefinition("MyIndex").SetIndexType("SonesIndex").AddProperty("Name").SetVertexType("Website");
//add index
Website_VertexTypePredefinition.AddIndex((IndexPredefinition)MyIndex);
//2. on creating the property definition of property "Name" call the SetAsIndexed() method, the GraphDB will create the index
//PropertyName = new PropertyPredefinition("Name")
// .SetAttributeType("String")
// .SetComment("This is a property on type 'Website' with name 'Name' and is of type 'String'")
// .SetAsIndexed();
//3. make a create index request, like creating a type
//BEWARE: This statement must be execute AFTER the type "Website" is created.
//var MyIndex = GraphDSServer.CreateIndex<IIndexDefinition>(SecToken,
// TransToken,
// new RequestCreateIndex(
// new IndexPredefinition("MyIndex")
// .SetIndexType("SonesIndex")
// .AddProperty("Name")
// .SetVertexType("Website")), (Statistics, Index) => Index);
#endregion
//add IncomingEdge "Tags", the related OutgoingEdge is "TaggedWebsites" on type "Tag"
Website_VertexTypePredefinition.AddIncomingEdge(new IncomingEdgePredefinition("Tags",
"Tag",
"TaggedWebsites"));
#endregion
#region create types by sending requests
//create the types "Tag" and "Website"
var DBTypes = GraphDSClient.CreateVertexTypes<IEnumerable<IVertexType>>(SecToken,
TransToken,
new RequestCreateVertexTypes(
new List<VertexTypePredefinition> { Tag_VertexTypePredefinition,
Website_VertexTypePredefinition }),
(Statistics, VertexTypes) => VertexTypes);
/*
* BEWARE: The following two operations won't work because the two types "Tag" and "Website" depending on each other,
* because one type has an incoming edge to the other and the other one has an incoming edge,
* so they cannot be created separate (by using create type),
* they have to be created at the same time (by using create types)
*
* //create the type "Website"
* var Website = GraphDSServer.CreateVertexType<IVertexType>(SecToken,
* TransToken,
* new RequestCreateVertexType(Website_VertexTypePredefinition),
* (Statistics, VertexType) => VertexType);
*
* //create the type "Tag"
* var Tag = GraphDSServer.CreateVertexType<IVertexType>(SecToken,
* TransToken,
* new RequestCreateVertexType(Tag_VertexTypePredefinition),
* (Statistics, VertexType) => VertexType);
*/
var Tag = DBTypes.Where(type => type.Name == "Tag").FirstOrDefault();
if (Tag != null)
Console.WriteLine("Vertex Type 'Tag' created");
var Website = DBTypes.Where(type => type.Name == "Website").FirstOrDefault();
if(Website != null)
Console.WriteLine("Vertex Type 'Website' created");
#endregion
#region insert some Websites by sending requests
var sones = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website")
.AddStructuredProperty("Name", "Sones")
.AddStructuredProperty("URL", "http://sones.com/"),
(Statistics, Result) => Result);
var cnn = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website")
.AddStructuredProperty("Name", "CNN")
.AddStructuredProperty("URL", "http://cnn.com/"),
(Statistics, Result) => Result);
var xkcd = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website")
.AddStructuredProperty("Name", "xkcd")
.AddStructuredProperty("URL", "http://xkcd.com/"),
(Statistics, Result) => Result);
var onion = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website")
.AddStructuredProperty("Name", "onion")
.AddStructuredProperty("URL", "http://theonion.com/"),
(Statistics, Result) => Result);
//adding an unknown property means the property isn't defined before
var test = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website")
.AddStructuredProperty("Name", "Test")
.AddStructuredProperty("URL", "")
.AddUnknownProperty("Unknown", "unknown property"),
(Statistics, Result) => Result);
if (sones != null)
Console.WriteLine("Website 'sones' successfully inserted");
if (cnn != null)
Console.WriteLine("Website 'cnn' successfully inserted");
if (xkcd != null)
Console.WriteLine("Website 'xkcd' successfully inserted");
if (onion != null)
Console.WriteLine("Website 'onion' successfully inserted");
if (test != null)
Console.WriteLine("Website 'test' successfully inserted");
#endregion
#region insert some Tags by sending requests
//insert a "Tag" with an OutgoingEdge to a "Website" include that the GraphDB creates an IncomingEdge on the given Website instances
//(because we created an IncomingEdge on type "Website") --> as a consequence we never have to set any IncomingEdge
var good = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Tag")
.AddStructuredProperty("Name", "good")
.AddEdge(new EdgePredefinition("TaggedWebsites")
.AddVertexID(Website.ID, cnn.VertexID)
.AddVertexID(Website.ID, xkcd.VertexID)),
(Statistics, Result) => Result);
var funny = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Tag")
.AddStructuredProperty("Name", "funny")
.AddEdge(new EdgePredefinition("TaggedWebsites")
.AddVertexID(Website.ID, xkcd.VertexID)
.AddVertexID(Website.ID, onion.VertexID)),
(Statistics, Result) => Result);
if (good != null)
Console.WriteLine("Tag 'good' successfully inserted");
if (funny != null)
Console.WriteLine("Tag 'funny' successfully inserted");
#endregion
#region how to get a type from the DB, properties of the type, instances of a specific type and read out property values
//how to get a type from the DB
var TagDBType = GraphDSClient.GetVertexType<IVertexType>(SecToken, TransToken, new RequestGetVertexType(Tag.Name), (Statistics, Type) => Type);
//how to get a type from the DB
var WebsiteDBType = GraphDSClient.GetVertexType<IVertexType>(SecToken, TransToken, new RequestGetVertexType(Website.Name), (Statistics, Type) => Type);
//read informations from type
var typeName = TagDBType.Name;
//are there other types wich extend the type "Tag"
var hasChildTypes = TagDBType.HasChildTypes;
var hasPropName = TagDBType.HasProperty("Name");
//get the definition of the property "Name"
var propName = TagDBType.GetPropertyDefinition("Name");
//how to get all instances of a type from the DB
var TagInstances = GraphDSClient.GetVertices(SecToken, TransToken, new RequestGetVertices(TagDBType.Name), (Statistics, Vertices) => Vertices);
foreach (var item in TagInstances)
{
//to get the value of a property of an instance, you need the property ID
//(that's why we fetched the type from DB an read out the property definition of property "Name")
var name = item.GetPropertyAsString(propName.ID);
}
Console.WriteLine("API operations finished...");
#endregion
}
#endregion
#region Graph Query Language
/// <summary>
/// Describes how to send queries using the GraphQL.
/// </summary>
private void GraphQLQueries()
{
#region create types
//create types at the same time, because of the circular dependencies (Tag has OutgoingEdge to Website, Website has IncomingEdge from Tag)
//like shown before, using the GraphQL there are also three different ways to create create an index on property "Name" of type "Website"
//1. create an index definition and specifie the property name and index type
var Types = GraphDSClient.Query(SecToken, TransToken, @"CREATE VERTEX TYPES Tag ATTRIBUTES (String Name, SET<Website> TaggedWebsites),
Website ATTRIBUTES (String Name, String URL) INCOMINGEDGES (Tag.TaggedWebsites Tags)
INDICES (MyIndex INDEXTYPE SonesIndex ON ATTRIBUTES Name)", "sones.gql");
//2. on creating the type with the property "Name", just define the property "Name" under INDICES
//var Types = GraphQL.Query(SecToken, TransToken, @"CREATE VERTEX TYPES Tag ATTRIBUTES (String Name, SET<Website> TaggedWebsites),
// Website ATTRIBUTES (String Name, String URL) INCOMINGEDGES (Tag.TaggedWebsites Tags) INDICES (Name)");
//3. make a create index query
//var Types = GraphQL.Query(SecToken, TransToken, @"CREATE VERTEX TYPES Tag ATTRIBUTES (String Name, SET<Website> TaggedWebsites),
// Website ATTRIBUTES (String Name, String URL) INCOMINGEDGES (Tag.TaggedWebsites Tags)");
//var MyIndex = GraphQL.Query(SecToken, TransToken, "CREATE INDEX MyIndex ON VERTEX TYPE Website (Name) INDEXTYPE SonesIndex");
CheckResult(Types);
#endregion
#region create instances of type "Website"
var cnnResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Website VALUES (Name = 'CNN', URL = 'http://cnn.com/')", "sones.gql");
CheckResult(cnnResult);
var xkcdResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Website VALUES (Name = 'xkcd', URL = 'http://xkcd.com/')", "sones.gql");
CheckResult(xkcdResult);
var onionResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Website VALUES (Name = 'onion', URL = 'http://theonion.com/')", "sones.gql");
CheckResult(onionResult);
//adding an unknown property ("Unknown") means the property isn't defined before
var unknown = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Website VALUES (Name = 'Test', URL = '', Unknown = 'unknown property')", "sones.gql");
CheckResult(onionResult);
#endregion
#region create instances of type "Tag"
var goodResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Tag VALUES (Name = 'good', TaggedWebsites = SETOF(Name = 'CNN', Name = 'xkcd'))", "sones.gql");
CheckResult(goodResult);
var funnyResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Tag VALUES (Name = 'funny', TaggedWebsites = SETOF(Name = 'xkcd', Name = 'onion'))", "sones.gql");
CheckResult(funnyResult);
#endregion
Console.WriteLine("GQL Queries finished...");
}
/// <summary>
/// Executes some select statements.
/// </summary>
private void SELECTS()
{
// find out which tags xkcd is tagged with
var _xkcdtags = GraphDSClient.Query(SecToken, TransToken, "FROM Website w SELECT w.Tags WHERE w.Name = 'xkcd' DEPTH 1", "sones.gql");
CheckResult(_xkcdtags);
foreach (var _tag in _xkcdtags.Vertices)
foreach (var edge in _tag.GetHyperEdge("Tags").GetAllEdges())
Console.WriteLine(edge.GetTargetVertex().GetPropertyAsString("Name"));
// List tagged sites names and the count of there tags
var _taggedsites = GraphDSClient.Query(SecToken, TransToken, "FROM Website w SELECT w.Name, w.Tags.Count() AS Counter", "sones.gql");
CheckResult(_taggedsites);
foreach (var _sites in _taggedsites.Vertices)
Console.WriteLine("{0} => {1}", _sites.GetPropertyAsString("Name"), _sites.GetPropertyAsString("Counter"));
// find out the URL's of the website of each Tag
var _urls = GraphDSClient.Query(SecToken, TransToken, "FROM Tag t SELECT t.Name, t.TaggedWebsites.URL", "sones.gql");
CheckResult(_urls);
foreach (var _tag in _urls.Vertices)
foreach (var edge in _tag.GetHyperEdge("TaggedWebsites").GetAllEdges())
Console.WriteLine(_tag.GetPropertyAsString("Name") + " - " + edge.GetTargetVertex().GetPropertyAsString("URL"));
Console.WriteLine("SELECT operations finished...");
}
/// <summary>
/// This private method analyses the QueryResult, shows the ResultType and Errors if existing.
/// </summary>
/// <param name="myQueryResult">The result of a query.</param>
private bool CheckResult(IQueryResult myQueryResult)
{
if (myQueryResult.Error != null)
{
if (myQueryResult.Error.InnerException != null)
Console.WriteLine(myQueryResult.Error.InnerException.Message);
else
Console.WriteLine(myQueryResult.Error.Message);
return false;
}
else
{
Console.WriteLine("Query " + myQueryResult.TypeOfResult);
return true;
}
}
#endregion
}
public class sonesGraphDBStarter
{
static void Main(string[] args)
{
bool quiet = false;
if (args.Count() > 0)
{
foreach (String parameter in args)
{
if (parameter.ToUpper() == "--Q")
quiet = true;
}
}
if (!quiet)
{
DiscordianDate ddate = new DiscordianDate();
Console.WriteLine("sones GraphDB version 2.0 - " + ddate.ToString());
Console.WriteLine("(C) sones GmbH 2007-2011 - http://www.sones.com");
Console.WriteLine("-----------------------------------------------");
Console.WriteLine();
Console.WriteLine("Starting up GraphDB...");
}
try
{
var sonesGraphDBStartup = new TagExampleWithGraphMappingFramework(args);
}
catch (ServiceException e)
{
if (!quiet)
{
Console.WriteLine(e.Message);
Console.WriteLine("InnerException: " + e.InnerException.ToString());
Console.WriteLine();
Console.WriteLine("Press <return> to exit.");
Console.ReadLine();
}
}
}
}
}
| sones/sones | Applications/TagExampleWithGraphMappingFramework/Example.cs | C# | agpl-3.0 | 29,686 |
/*
* Copyright (c) 1996 Sun Microsystems, Inc. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this software
* and its documentation for NON-COMMERCIAL purposes and without
* fee is hereby granted provided that this copyright notice
* appears in all copies. Please refer to the file "copyright.html"
* for further important copyright and licensing information.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
* THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*/
package javax.telephony;
import javax.telephony.capabilities.ConnectionCapabilities;
/**
* A <CODE>Connection</CODE> represents a link (i.e. an association) between
* a {@link Call} object and an {@link Address} object.
*
* <H4>Introduction</H4>
*
* The purpose of a Connection object is to describe
* the relationship between a Call object and an Address object. A Connection
* object exists if the Address is a part of the telephone call. Each
* Connection has a <EM>state</EM> which describes the particular stage of the
* relationship between the Call and Address. These states and their meanings
* are described below. Applications use the <CODE>Connection.getCall()</CODE>
* and <CODE>Connection.getAddress()</CODE> methods to obtain the Call and
* Address associated with this Connection, respectively.
* <p>
* From one perspective, an application may view a Call only in terms of the
* Address/Connection objects which are part of the Call. This is termed a
* <EM>logical</EM> view of the Call because it ignores the details provided
* by the Terminal and TerminalConnection objects which are also associated
* with a Call. In many instances, simple applications (such as an
* <EM>outcall</EM> program) may only need to concern itself with the logical
* view. In this logical view, a telephone call is views as two or more
* endpoint addresses in communication. The Connection object describes the
* state of each of these endpoint addresses with respect to the Call.
*
* <H4>Calls and Addresses</H4>
*
* Connection objects are immutable in terms of their Call and Address
* references. In other words, the Call and Address object references do
* not change throughout the lifetime of the Connection object instance. The
* same Connection object may not be used in another telephone call. The
* existence of a Connection implies that its Address is associated with its
* Call in the manner described by the Connection's state.
* <p>
* Although a Connection's Address and Call references remain valid throughout
* the lifetime of the Connection object, the same is not true for the Call
* and Address object's references to this Connection. Particularly, when a
* Connection moves into the Connection.DISCONNECTED state, it is no longer
* listed by the <CODE>Call.getConnections()</CODE> and
* <CODE>Address.getConnections()</CODE> methods. Typically, when a Connection
* moves into the <CODE>Connection.DISCONNECTED</CODE> state, the application
* loses its references to it to facilitate its garbage collection.
*
* <H4>TerminalConnections</H4>
*
* Connections objects are containers for zero or more TerminalConnection
* objects. Connection objects are containers for zero or more TerminalConnection
* objects. Connection objects represent the relationship between the Call and
* the Address, whereas TerminalConnection objects represent the relationship
* between the Connection and the Terminal. The relationship between the Call and
* the Address may be viewed as a logical view of the Call. The relationship
* between a Connection and a Terminal represents the physical view of the
* Call, i.e. at which Terminal the telephone calls terminates. The
* TerminalConnection object specification provides further information.
*
* <H4>Connection States</H4>
*
* Below is a description of each Connection state in real-world terms. These
* real-world descriptions have no bearing on the specifications of methods,
* they only serve to provide a more intuitive understanding of what is going
* on. Several methods in this specification state pre-conditions based upon
* the state of the Connection.
* <p>
* <TABLE CELLPADDING=2>
*
* <TR>
* <TD WIDTH="15%"><CODE>Connection.IDLE</CODE></TD>
* <TD WIDTH="85%">
* This state is the initial state for all new Connections. Connections which
* are in the <CODE>Connection.IDLE</CODE> state are not actively part of a
* telephone call, yet their references to the Call and Address objects are
* valid. Connections typically do not stay in the <CODE>Connection.IDLE</CODE>
* state for long, quickly transitioning to other states.
* </TD>
* </TR>
*
* <TR>
* <TD WIDTH="15%"><CODE>Connection.DISCONNECTED</CODE></TD>
* <TD WIDTH="85%">
* This state implies it is no longer part of the telephone call, although its
* references to Call and Address still remain valid. A Connection in this
* state is interpreted as once previously belonging to this telephone call.
* </TD>
* </TR>
*
* <TR>
* <TD WIDTH="15%"><CODE>Connection.INPROGRESS</CODE></TD>
* <TD WIDTH="85%">
* This state implies that the Connection, which represents the destination
* end of a telephone call, is in the process of contacting the destination
* side. Under certain circumstances, the Connection may not progress beyond
* this state. Extension packages elaborate further on this state in various
* situations.
* </TD>
* </TR>
*
* <TR>
* <TD WIDTH="15%"><CODE>Connection.ALERTING</CODE></TD>
* <TD WIDTH="85%">
* This state implies that the Address is being notified of an incoming call.
* </TD>
* </TR>
*
* <TR>
* <TD WIDTH="15%"><CODE>Connection.CONNECTED</CODE></TD>
* <TD WIDTH="85%">
* This state implies that a Connection and its Address is actively part of a
* telephone call. In common terms, two people talking to one another are
* represented by two Connections in the <CODE>Connection.CONNECTED</CODE>
* state.
* </TD>
* </TR>
*
* <TR>
* <TD WIDTH="15%"><CODE>Connection.UNKNOWN</CODE></TD>
* <TD WIDTH="85%">
* This state implies that the implementation is unable to determine the
* current state of the Connection. Typically, methods are invalid on
* Connections which are in this state. Connections may move in and out of the
* <CODE>Connection.UNKNOWN</CODE> state at any time.
* </TD>
* </TR>
*
* <TR>
* <TD WIDTH="15%"><CODE>Connection.FAILED</CODE></TD>
* <TD WIDTH="85%">
* This state indicates that a Connection to that end of the call has failed
* for some reason. One reason why a Connection would be in the
* <CODE>Connection.FAILED</CODE> state is because the party was busy.
* </TD>
* </TR>
* </TABLE>
*
* <H4>Connection State Transitions</H4>
*
* With these loose, real-world meanings in the back of one's mind, the
* Connection class defines a finite-state diagram which describes the
* allowable Connection state transitions. This finite-state diagram must be
* guaranteed by the implementation. Each method which causes a change in
* a Connection state must be consistent with this state diagram. This finite
* state diagram is below:
* <P>
* Note there is a general left-to-right progression of the state transitions.
* A Connection object may transition into and out of the
* <CODE>Connection.UNKNOWN</CODE> state at any time (hence, the asterisk
* qualifier next to its bidirectional transition arrow).
* <p>
* <IMG SRC="doc-files/core-connectionstates.gif" ALIGN="center">
* </P>
*
* <H4>The Connection.disconnect() Method</H4>
*
* The primary method supported on the core package's Connection interface is
* the <CODE>Connection.disconnect()</CODE> method. This method drops an entire
* Connection from a telephone call. The result of this method is to move the
* Connection object into the <CODE>Connection.DISCONNECTED</CODE> state. See
* the specification of the <CODE>Connection.disconnect()</CODE> method on
* this page for more detailed information.
*
* <H4>Listeners and Events</H4>
*
* All events pertaining to the Connection object are reported via the
* <CODE>CallListener</CODE> interface on the Call object associated with this
* Connection. In the core package, events are reported to a CallListener when
* a new Connection is created and whenever a Connection changes state.
* Listeners are added to Call objects via the <CODE>Call.addCallListener()</CODE>
* method and more indirectly via the <CODE>Address.addCallListener()</CODE>
* and <CODE>Terminal.addCallListener()</CODE> methods. See the specifications
* for the Call, Address, and Terminal interfaces for more information.
* <p>
* The following Connection-related events are defined in the core package.
* Each of these events extend the <CODE>ConnectionEvent</CODE> interface (which, in
* turn, extends the <CODE>CallEvent</CODE> interface).
* <p>
* <TABLE CELLPADDING=2>
* <TR>
* <TD WIDTH="20%"><CODE>ConnectionCreated</CODE></TD>
* <TD WIDTH="80%">
* Indicates a new Connection has been created on a Call.
* </TD>
*
* <TR>
* <TD WIDTH="20%"><CODE>ConnectionInProgress</CODE></TD>
* <TD WIDTH="80%">
* Indicates the Connection has moved into the
* <CODE>Connection.INPROGRESS</CODE> state.
* </TD>
* </TR>
*
* <TR>
* <TD WIDTH="20%"><CODE>ConnectionAlerting</CODE></TD>
* <TD WIDTH="80%">
* Indicates the Connection has moved into the <CODE>Connection.ALERTING</CODE>
* state.
* </TD>
* </TR>
*
* <TR>
* <TD WIDTH="20%"><CODE>ConnectionConnected</CODE></TD>
* <TD WIDTH="80%">
* Indicates the Connection has moved into the
* <CODE>Connection.CONNECTED</CODE> state.
* </TD>
* </TR>
*
* <TR>
* <TD WIDTH="20%"><CODE>ConnectionDisconnected</CODE></TD>
* <TD WIDTH="80%">
* Indicates the Connection has moved into the
* <CODE>Connection.DISCONNECTED</CODE> state.
* </TD>
* </TR>
*
* <TR>
* <TD WIDTH="20%"><CODE>ConnectionFailed</CODE></TD>
* <TD WIDTH="80%">
* Indicates the Connection has moved into the <CODE>Connection.FAILED</CODE>
* state.
* </TD>
* </TR>
*
* <TR>
* <TD WIDTH="20%"><CODE>ConnectionUnknown</CODE></TD>
* <TD WIDTH="80%">
* Indicates the Connection has moved into the <CODE>Connection.UNKNOWN</CODE>
* state.
* </TD>
* </TR>
* </TABLE>
* <p>
* @see javax.telephony.ConnectionEvent
* @see javax.telephony.ConnectionListener
* @version 04/05/99 1.48
*/
public interface Connection {
/**
* The <CODE>Connection.IDLE</CODE> state is the initial state for all new
* Connections. Connections which are in the Connection.IDLE state are not
* actively part of a telephone call, yet their references to the Call and
* Address objects are valid. Connections typically do not stay in the
* <CODE>Connection.IDLE</CODE> state for long, quickly transitioning to
* other states.
*/
public static final int IDLE = 0x30;
/**
* The <CODE>Connection.INPROGRESS</CODE> state implies that the Connection,
* which represents the destination end of a telephone call, is in the
* process of contacting the destination side. Under certain circumstances,
* the Connection may not progress beyond this state. Extension packages
* elaborate further on this state in various situations.
*/
public static final int INPROGRESS = 0x31;
/**
* The <CODE>Connection.ALERTING</CODE> state implies that the Address is
* being notified of an incoming call.
*/
public static final int ALERTING = 0x32;
/**
* The <CODE>Connection.CONNECTED</CODE> state implies that a Connection and
* its Address is actively part of a telephone call. In common terms, two
* people talking to one another are represented by two Connections in the
* <CODE>Connection.CONNECTED</CODE> state.
*/
public static final int CONNECTED = 0x33;
/**
* The <CODE>Connection.DISCONNECTED</CODE> state implies it is no longer
* part of the telephone call, although its references to Call and Address
* still remain valid. A Connection in the
* <CODE>Connection.DISCONNECTED</CODE> state is interpreted as once
* previously belonging to this telephone call.
*/
public static final int DISCONNECTED = 0x34;
/**
* The <CODE>Connection.FAILED</CODE> state indicates that a Connection to
* that end of the call has failed for some reason. One reason why a
* Connection would be in the <CODE>Connection.FAILED</CODE> state is
* because the party was busy.
*/
public static final int FAILED = 0x35;
/**
* The <CODE>Connection.UNKNOWN</CODE> state implies that the implementation
* is unable to determine the current state of the Connection. Typically,
* method are invalid on Connections which are in the
* <CODE>Connection.UNKNOWN</CODE> state. Connections may move in and out of
* this state at any time.
*/
public static final int UNKNOWN = 0x36;
/**
* Returns the current state of the Connection. The return value will
* be one of states defined above.
* <p>
* @return The current state of the Connection.
*/
public int getState();
/**
* Returns the Call object associated with this Connection. This Call
* reference remains valid throughout the lifetime of the Connection object,
* despite the state of the Connection object. This Call reference does not
* change once the Connection object has been created.
* <p>
* @return The call object associated with this Connection.
*/
public Call getCall();
/**
* Returns the Address object associated with this Connection. This Address
* object reference remains valid throughout the lifetime of the Connection
* object despite the state of the Connection object. This Address reference
* does not change once the Connection object has been created.
* <p>
* @return The Address associated with this Connection.
*/
public Address getAddress();
/**
* Returns an array of TerminalConnection objects associated with this
* Connection. TerminalConnection objects represent the relationship between
* a Connection and a specific Terminal endpoint. There may be zero
* TerminalConnections associated with this Connection. In that case, this
* method returns null. Connection objects lose their reference to a
* TerminalConnection once the TerminalConnection moves into the
* <CODE>TerminalConnection.DROPPED</CODE> state.
* <p>
* <B>Post-conditions:</B>
* <OL>
* <LI>Let TerminalConnection tc[] = this.getTerminalConnections()
* <LI>tc == null or tc.length >= 1
* <LI>For all i, tc[i].getState() != TerminalConnection.DROPPED
* </OL>
* @return An array of TerminalConnection objects associated with this
* Connection, null if there are no TerminalConnections.
*/
public TerminalConnection[] getTerminalConnections();
/**
* Drops a Connection from an active telephone call. The Connection's Address
* is no longer associated with the telephone call. This method does not
* necessarily drop the entire telephone call, only the particular
* Connection on the telephone call. This method provides the ability to
* disconnect a specific party from a telephone call, which is especially
* useful in telephone calls consisting of three or more parties. Invoking
* this method may result in the entire telephone call being dropped, which
* is a permitted outcome of this method. In that case, the appropriate
* events are delivered to the application, indicating that more than just
* a single Connection has been dropped from the telephone call.
*
* <H5>Allowable Connection States</H5>
*
* The Connection object must be in one of several states in order for
* this method to be successfully invoked. These allowable states are:
* <CODE>Connection.CONNECTED</CODE>, <CODE>Connection.ALERTING</CODE>,
* <CODE>Connection.INPROGRESS</CODE>, or <CODE>Connection.FAILED</CODE>. If
* the Connection is not in one of these allowable states when this method is
* invoked, this method throws InvalidStateException. Having the Connection
* in one of the allowable states does not guarantee a successful invocation
* of this method.
*
* <H5>Method Return Conditions</H5>
*
* This method returns successfully only after the Connection has been
* disconnected from the telephone call and has transitioned into the
* <CODE>Connection.DISCONNECTED</CODE>. This method may return
* unsuccessfully by throwing one of the exceptions listed below. Note that
* this method waits (i.e. the invocating thread blocks) until either the
* Connection is actually disconnected from the telephone call or an error
* is detected and an exception thrown. Also, all of the TerminalConnections
* associated with this Connection are moved into the
* <CODE>TerminalConnection.DROPPED</CODE> state. As a result, they are no
* longer reported via the Connection by the
* <CODE>Connection.getTerminalConnections()</CODE> method.
* <p>
* As a result of this method returning successfully, one or more events
* are delivered to the application. These events are listed below:
* <p>
* <OL>
* <LI>A ConnectionDisconnected event for this Connection.
* <LI>A TerminalConnectionDropped event for all TerminalConnections associated with
* this Connection.
* </OL>
*
* <H5>Dropping Additional Connections</H5>
*
* Additional Connections may be dropped indirectly as a result of this
* method. For example, dropping the destination Connection of a two-party
* Call may result in the entire telephone call being dropped. It is up to
* the implementation to determine which Connections are dropped as a result
* of this method. Implementations should not, however, drop additional
* Connections if it does not reflect the natural response of the underlying
* telephone hardware.
* <p>
* Dropping additional Connections implies that their TerminalConnections are
* dropped as well. Also, if all of the Connections on a telephone call are
* dropped as a result of this method, the Call will move into the
* <CODE>Call.INVALID</CODE> state. The following lists additional events
* which may be delivered to the application.
* <p>
* <OL>
* <LI>ConnectionDisconnected/TerminalConnectionDropped are delivered for all other
* Connections and TerminalConnections dropped indirectly as a result of
* this method.
* <LI>CallInvalid if all of the Connections are dropped indirectly as a
* result of this method.
* </OL>
* <p>
* <B>Pre-conditions:</B>
* <OL>
* <LI>((this.getCall()).getProvider()).getState() == Provider.IN_SERVICE
* <LI>this.getState() == Connection.CONNECTED or Connection.ALERTING
* or Connection.INPROGRESS or Connection.FAILED
* <LI>Let TerminalConnection tc[] = this.getTerminalConnections (see post-
* conditions)
* </OL>
* <B>Post-conditions:</B>
* <OL>
* <LI>((this.getCall()).getProvider()).getState() == Provider.IN_SERVICE
* <LI>this.getState() == Connection.DISCONNECTED
* <LI>For all i, tc[i].getState() == TerminalConnection.DROPPED
* <LI>this.getTerminalConnections() == null.
* <LI>this is not an element of (this.getCall()).getConnections()
* <LI>ConnectionDisconnected is delivered for this Connection.
* <LI>TerminalConnectionDropped is delivered for all TerminalConnections associated
* with this Connection.
* <LI>ConnectionDisconnected/TerminalConnectionDropped are delivered for all other
* Connections and TerminalConnections dropped indirectly as a result of
* this method.
* <LI>CallInvalid if all of the Connections are dropped indirectly as a
* result of this method.
* </OL>
* <p>
* @see javax.telephony.ConnectionListener
* @see javax.telephony.ConnectionEvent
* @exception PrivilegeViolationException The application does not have
* the authority or permission to disconnected the Connection. For example,
* the Address associated with this Connection may not be controllable in
* the Provider's domain.
* @exception ResourceUnavailableException An internal resource required
* to drop a connection is not available.
* @exception MethodNotSupportedException This method is not supported by
* the implementation.
* @exception InvalidStateException Some object required for the successful
* invocation of this method is not in the proper state as given by this
* method's pre-conditions. For example, the Provider may not be in the
* Provider.IN_SERVICE state or the Connection may not be in one of the
* allowable states.
*/
public void disconnect()
throws PrivilegeViolationException, ResourceUnavailableException,
MethodNotSupportedException, InvalidStateException;
/**
* Returns the dynamic capabilities for the instance of the Connection
* object. Dynamic capabilities tell the application which actions are
* possible at the time this method is invoked based upon the implementations
* knowledge of its ability to successfully perform the action. This
* determination may be based upon the current state of the call model
* or some implementation-specific knowledge. These indications do not
* guarantee that a particular method can be successfully invoked, however.
* <p>
* The dynamic Connection capabilities require no additional arguments.
* <p>
* @return The dynamic Connection capabilities.
*/
public ConnectionCapabilities getCapabilities();
/**
* Gets the ConnectionCapabilities object with respect to a Terminal and
* an Address. If null is passed as a Terminal parameter, the general/
* provider-wide Connection capabilities are returned.
* <p>
* <STRONG>Note:</STRONG> This method has been replaced in JTAPI v1.2. The
* <CODE>Connection.getCapabilities()</CODE> method returns the dynamic
* Connection capabilities. This method now should simply invoke the
* <CODE>Connection.getCapabilities()</CODE> method.
* <p>
* @deprecated Since JTAPI v1.2. This method has been replaced by the
* Connection.getCapabilities() method.
* @param terminal This argument is ignored in JTAPI v1.2 and later.
* @param address This argument is ignored in JTAPI v1.2 and later.
* @exception InvalidArgumentException This exception is never thrown in
* JTAPI v1.2 and later.
* @exception PlatformException A platform-specific exception occurred.
* @return The dynamic ConnectionCapabilities capabilities.
*/
public ConnectionCapabilities getConnectionCapabilities(Terminal terminal,
Address address)
throws InvalidArgumentException, PlatformException;
}
| kerr-huang/openss7 | src/java/javax/telephony/Connection.java | Java | agpl-3.0 | 22,953 |
/*
* Copyright (c) 2018. Wise Wild Web
*
* This File is part of Caipi and under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License
* Full license at https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode
*
* @author : Nathanael Braun
* @contact : caipilabs@gmail.com
*/
var cfg = require('$super'),
p = (APP_PORT != 80) ? (":" + APP_PORT) : "",
domain = (__LOCAL__ ? 'mamasound.fr.local' + p : 'mamasound.fr' + p),
url = cfg.wwwDomain ? 'www.' + domain : domain;
export default {
...require('$super'),
PROJECT_NAME : "www.mamasound.fr",
PUBLIC_URL : url,
ROOT_DOMAIN : domain,
API_URL : 'api.' + domain,
UPLOAD_URL : 'upload.' + domain,
STATIC_URL : 'static.' + domain,
STATIC_REDIRECT_URL: __LOCAL__ && 'static.mamasound.fr',
OSM_URL: "http://{s}.tile.osm.org/{z}/{x}/{y}.png",
DB_URL : "mongodb://localhost:27017/www_mamasound_fr",
UPLOAD_DIR : "./uploads/",
CACHE_TM : 1000 * 60 * 2,
SESSION_CHECK_TM: 1000 * 60 * 1,
defaultRootMenuId: "Menu.HyInIUM8.html",
htmlRefs: [
{
"type": "script",
"src" : "https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyA7XcGxipnIMdSSBJHn3tzeJe-fU3ilCak"
},
...(cfg.htmlRefs || [])
]
}; | nathb2b/mamasound.fr | App/config.js | JavaScript | agpl-3.0 | 1,324 |
## Note: you must install Levenshtein module
# pip install python-Levenshtein
# for this Microsoft Visual C++ 9.0 is required. Get it from http://aka.ms/vcpython27
# more info - see: http://stackoverflow.com/questions/18134437/where-can-the-documentation-for-python-levenshtein-be-found-online
from pymongo import MongoClient
import pymongo
import pprint
import bson
import pandas
import Levenshtein
EXPECTED_STREET_PATTERN = \
u"^.*(?<![Ss]tra\u00dfe)(?<![Ww]eg)(?<![Aa]llee)(?<![Rr]ing)(?<![Bb]erg)" + \
u"(?<![Pp]ark)(?<![Hh]\u00f6he)(?<![Pp]latz)(?<![Bb]r\u00fccke)(?<![Gg]rund)$"
def audit_streets(collection):
return list(collection.distinct("name", {
"type": "way",
"name": {"$regex": EXPECTED_STREET_PATTERN}
}))
def audit_buildings(db):
result = db.eval('''
db.osmnodes.ensureIndex({pos:"2dsphere"});
result = [];
db.osmnodes.find(
{"building": {"$exists": true}, "address.street": {"$exists": true}, "pos": {"$exists": true}},
{"address.street": "", "pos": ""}
).forEach(function(val, idx) {
val.nearby = db.osmnodes.distinct("address.street",
{"_id": {"$ne": val._id}, "pos": {"$near": {"$geometry": {"type": "Point", "coordinates": val.pos}, "$maxDistance": 50, "$minDistance": 0}}}
);
result.push(val);
})
return result;
''')
df_list = []
for row in result:
street_name = row["address"]["street"]
nb_best_dist = None
nb_best = ""
nb_worst_dist = None
nb_worst = ""
for nearby_street in row["nearby"]:
d = Levenshtein.distance(nearby_street, street_name)
if nb_best_dist == None or d < nb_best_dist:
nb_best_dist = d
nb_best = nearby_street
if nb_worst_dist == None or d > nb_worst_dist:
nb_worst_dist = d
nb_worst = nearby_street
df_list += [{
"_id": row["_id"],
"street_name": street_name,
"num_nearby": len(row["nearby"]),
"nb_best": nb_best,
"nb_worst": nb_worst,
"nb_best_dist": nb_best_dist,
"nb_worst_dist": nb_worst_dist
}]
return pandas.DataFrame(df_list, columns=["_id", "street_name", "num_nearby", "nb_best", "nb_best_dist", "nb_worst", "nb_worst_dist"])
def audit_phone_numbers(collection):
return list(collection.aggregate([
{"$match": {"$or": [
{"phone": {"$exists": True}},
{"mobile_phone": {"$exists": True}},
{"address.phone": {"$exists": True}}
]}},
{"$project": {
"_id": 1,
"phone": {"$ifNull": ["$phone", {"$ifNull": ["$mobile_phone", "$address.phone"]}]}
}}
]))
def audit_quality_map(mongoServer, mongoPort, csvFilePattern, csvEncoding):
client = MongoClient(mongoServer + ":" + mongoPort)
db = client.udacity
c = client.udacity.osmnodes
print
print "Auditing way descriptions..."
print "These are the 'unusual' street names"
r = audit_streets(c)
pprint.pprint(r)
print
print "Auditing streets close to buildings..."
r = audit_buildings(db)
r.to_csv(csvFilePattern.format("audit_buildings.csv"), encoding=csvEncoding)
pprint.pprint(r)
print
print "Auditing phone numbers..."
r = audit_phone_numbers(c)
pprint.pprint(r)
| benjaminsoellner/2015_Data_Analyst_Project_3 | Project/audit_quality_map.py | Python | agpl-3.0 | 3,625 |
<?php
class Cloudsponge_Integration {
var $enabled;
var $key;
/**
* PHP 5 Constructor
*
* @package Invite Anyone
* @since 0.8
*/
function __construct() {
if ( empty( $options ) )
$options = get_option( 'invite_anyone' );
$this->enabled = !empty( $options['cloudsponge_enabled'] ) ? $options['cloudsponge_enabled'] : false;
$this->key = !empty( $options['cloudsponge_key'] ) ? $options['cloudsponge_key'] : false;
if ( $this->enabled && $this->key ) {
define( 'INVITE_ANYONE_CS_ENABLED', true );
add_action( 'invite_anyone_after_addresses', array( $this, 'import_markup' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_script' ) );
}
}
/**
* Registers and loads CS JS.
*
* @package Invite Anyone
* @since 0.8.8
*/
function enqueue_script() {
wp_register_script( 'ia_cloudsponge_address_books', 'https://api.cloudsponge.com/address_books.js', array(), false, true );
wp_register_script( 'ia_cloudsponge', WP_PLUGIN_URL . '/invite-anyone/by-email/cloudsponge-js.js', array( 'ia_cloudsponge_address_books' ), false, true );
// The domain key must be printed as a javascript object so it's accessible to the
// script
$strings = array( 'domain_key' => $this->key );
if ( $locale = apply_filters( 'ia_cloudsponge_locale', '' ) ) {
$strings['locale'] = $locale;
}
if ( $stylesheet = apply_filters( 'ia_cloudsponge_stylesheet', '' ) ) {
$strings['stylesheet'] = $stylesheet;
}
wp_localize_script( 'ia_cloudsponge', 'ia_cloudsponge', $strings );
}
/**
* Inserts the Cloudsponge markup into the Send Invites front end page.
*
* Also responsible for enqueuing the necessary assets.
*
* @package Invite Anyone
* @since 0.8
*
* @param array $options Invite Anyone settings. Check em so we can bail if necessary
*/
function import_markup( $options = false ) {
wp_enqueue_script( 'ia_cloudsponge' );
?>
<input type="hidden" id="cloudsponge-emails" name="cloudsponge-emails" value="" />
<?php _e( 'You can also add email addresses <a class="cs_import">from your Address Book</a>.', 'invite-anyone' ) ?>
<?php
}
}
$cloudsponge_integration = new Cloudsponge_Integration;
| empirical-org/Empirical-Wordpress | wp-content/plugins/invite-anyone/by-email/cloudsponge-integration.php | PHP | agpl-3.0 | 2,189 |
package rocks.inspectit.ui.rcp.repository.service.cmr.proxy;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ReflectiveMethodInvocation;
import com.google.common.base.Defaults;
import rocks.inspectit.ui.rcp.repository.CmrRepositoryDefinition;
import rocks.inspectit.ui.rcp.repository.service.cmr.ICmrService;
/**
* Utilities that will be used in interceptors.
*
* @author Ivan Senic
*
*/
public final class InterceptorUtils {
/**
* Private constructor.
*/
private InterceptorUtils() {
}
/**
* Is service method.
*
* @param methodInvocation
* Method invocation.
* @return Return if it is service method.
*/
public static boolean isServiceMethod(MethodInvocation methodInvocation) {
return !methodInvocation.getMethod().getDeclaringClass().equals(ICmrService.class);
}
/**
* Checks if the method being executed is executed on the proxy containing {@link ICmrService}
* and service defines the default value on error value.
*
* @param methodInvocation
* Method invocation.
* @return <code>true</code> if {@link ICmrService} objects defines return default on error
*/
public static boolean isReturnDefaultReturnValue(MethodInvocation methodInvocation) {
ICmrService cmrService = getCmrService(methodInvocation);
return (null != cmrService) && cmrService.isDefaultValueOnError();
}
/**
* Tries to get the {@link CmrRepositoryDefinition} from the proxied {@link ICmrService} object.
*
* @param methodInvocation
* {@link MethodInvocation}.
* @return CMR invoked or null.
*/
public static CmrRepositoryDefinition getRepositoryDefinition(MethodInvocation methodInvocation) {
ICmrService cmrService = getCmrService(methodInvocation);
if (null != cmrService) {
CmrRepositoryDefinition cmrRepositoryDefinition = cmrService.getCmrRepositoryDefinition();
return cmrRepositoryDefinition;
}
return null;
}
/**
* Returns {@link ICmrService} object if one is bounded to the proxy being invoked in the given
* {@link MethodInvocation} or <code>null</code> if one can not be obtained.
*
* @param methodInvocation
* {@link MethodInvocation}.
* @return {@link ICmrService} bounded on proxy or <code>null</code>
*/
private static ICmrService getCmrService(MethodInvocation methodInvocation) {
if (methodInvocation instanceof ReflectiveMethodInvocation) {
ReflectiveMethodInvocation reflectiveMethodInvocation = (ReflectiveMethodInvocation) methodInvocation;
Object service = reflectiveMethodInvocation.getThis();
if (service instanceof ICmrService) {
return (ICmrService) service;
}
}
return null;
}
/**
* Checks if the return type of the {@link java.lang.reflect.Method} invoked by
* {@link MethodInvocation} is one of tree major collection types (List, Map, Set) and if it is
* returns the empty collection of correct type. Otherwise it returns null.
*
* @param paramMethodInvocation
* {@link MethodInvocation}
* @return If the method invoked by {@link MethodInvocation} is one of tree major collection
* types (List, Map, Set) method returns the empty collection of correct type. Otherwise
* it returns null.
*/
public static Object getDefaultReturnValue(MethodInvocation paramMethodInvocation) {
Class<?> returnType = paramMethodInvocation.getMethod().getReturnType();
if (returnType.isAssignableFrom(List.class)) {
return Collections.emptyList();
} else if (returnType.isAssignableFrom(Map.class)) {
return Collections.emptyMap();
} else if (returnType.isAssignableFrom(Set.class)) {
return Collections.emptySet();
} else if (returnType.isPrimitive()) {
try {
return Defaults.defaultValue(returnType);
} catch (Exception e) {
return null;
}
} else {
return null;
}
}
}
| inspectIT/inspectIT | inspectit.ui.rcp/src/main/java/rocks/inspectit/ui/rcp/repository/service/cmr/proxy/InterceptorUtils.java | Java | agpl-3.0 | 3,959 |
// Copyright (c) 2015 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package model
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"strconv"
"strings"
"time"
l4g "github.com/alecthomas/log4go"
)
const (
HEADER_REQUEST_ID = "X-Request-ID"
HEADER_VERSION_ID = "X-Version-ID"
HEADER_CLUSTER_ID = "X-Cluster-ID"
HEADER_ETAG_SERVER = "ETag"
HEADER_ETAG_CLIENT = "If-None-Match"
HEADER_FORWARDED = "X-Forwarded-For"
HEADER_REAL_IP = "X-Real-IP"
HEADER_FORWARDED_PROTO = "X-Forwarded-Proto"
HEADER_TOKEN = "token"
HEADER_BEARER = "BEARER"
HEADER_AUTH = "Authorization"
HEADER_REQUESTED_WITH = "X-Requested-With"
HEADER_REQUESTED_WITH_XML = "XMLHttpRequest"
STATUS = "status"
STATUS_OK = "OK"
STATUS_FAIL = "FAIL"
STATUS_REMOVE = "REMOVE"
CLIENT_DIR = "webapp/dist"
API_URL_SUFFIX_V1 = "/api/v1"
API_URL_SUFFIX_V3 = "/api/v3"
API_URL_SUFFIX_V4 = "/api/v4"
API_URL_SUFFIX = API_URL_SUFFIX_V4
)
type Result struct {
RequestId string
Etag string
Data interface{}
}
type ResponseMetadata struct {
StatusCode int
Error *AppError
RequestId string
Etag string
}
type Client struct {
Url string // The location of the server like "http://localhost:8065"
ApiUrl string // The api location of the server like "http://localhost:8065/api/v3"
HttpClient *http.Client // The http client
AuthToken string
AuthType string
TeamId string
RequestId string
Etag string
ServerVersion string
}
// NewClient constructs a new client with convienence methods for talking to
// the server.
func NewClient(url string) *Client {
return &Client{url, url + API_URL_SUFFIX_V3, &http.Client{}, "", "", "", "", "", ""}
}
func closeBody(r *http.Response) {
if r.Body != nil {
ioutil.ReadAll(r.Body)
r.Body.Close()
}
}
func (c *Client) SetOAuthToken(token string) {
c.AuthToken = token
c.AuthType = HEADER_TOKEN
}
func (c *Client) ClearOAuthToken() {
c.AuthToken = ""
c.AuthType = HEADER_BEARER
}
func (c *Client) SetTeamId(teamId string) {
c.TeamId = teamId
}
func (c *Client) GetTeamId() string {
if len(c.TeamId) == 0 {
println(`You are trying to use a route that requires a team_id,
but you have not called SetTeamId() in client.go`)
}
return c.TeamId
}
func (c *Client) ClearTeamId() {
c.TeamId = ""
}
func (c *Client) GetTeamRoute() string {
return fmt.Sprintf("/teams/%v", c.GetTeamId())
}
func (c *Client) GetChannelRoute(channelId string) string {
return fmt.Sprintf("/teams/%v/channels/%v", c.GetTeamId(), channelId)
}
func (c *Client) GetUserRequiredRoute(userId string) string {
return fmt.Sprintf("/users/%v", userId)
}
func (c *Client) GetChannelNameRoute(channelName string) string {
return fmt.Sprintf("/teams/%v/channels/name/%v", c.GetTeamId(), channelName)
}
func (c *Client) GetEmojiRoute() string {
return "/emoji"
}
func (c *Client) GetGeneralRoute() string {
return "/general"
}
func (c *Client) GetFileRoute(fileId string) string {
return fmt.Sprintf("/files/%v", fileId)
}
func (c *Client) DoPost(url, data, contentType string) (*http.Response, *AppError) {
rq, _ := http.NewRequest("POST", c.Url+url, strings.NewReader(data))
rq.Header.Set("Content-Type", contentType)
rq.Close = true
if rp, err := c.HttpClient.Do(rq); err != nil {
return nil, NewLocAppError(url, "model.client.connecting.app_error", nil, err.Error())
} else if rp.StatusCode >= 300 {
defer closeBody(rp)
return nil, AppErrorFromJson(rp.Body)
} else {
return rp, nil
}
}
func (c *Client) DoApiPost(url string, data string) (*http.Response, *AppError) {
rq, _ := http.NewRequest("POST", c.ApiUrl+url, strings.NewReader(data))
rq.Close = true
if len(c.AuthToken) > 0 {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
}
if rp, err := c.HttpClient.Do(rq); err != nil {
return nil, NewLocAppError(url, "model.client.connecting.app_error", nil, err.Error())
} else if rp.StatusCode >= 300 {
defer closeBody(rp)
return nil, AppErrorFromJson(rp.Body)
} else {
return rp, nil
}
}
func (c *Client) DoApiGet(url string, data string, etag string) (*http.Response, *AppError) {
rq, _ := http.NewRequest("GET", c.ApiUrl+url, strings.NewReader(data))
rq.Close = true
if len(etag) > 0 {
rq.Header.Set(HEADER_ETAG_CLIENT, etag)
}
if len(c.AuthToken) > 0 {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
}
if rp, err := c.HttpClient.Do(rq); err != nil {
return nil, NewLocAppError(url, "model.client.connecting.app_error", nil, err.Error())
} else if rp.StatusCode == 304 {
return rp, nil
} else if rp.StatusCode >= 300 {
defer closeBody(rp)
return rp, AppErrorFromJson(rp.Body)
} else {
return rp, nil
}
}
func getCookie(name string, resp *http.Response) *http.Cookie {
for _, cookie := range resp.Cookies() {
if cookie.Name == name {
return cookie
}
}
return nil
}
// Must is a convenience function used for testing.
func (c *Client) Must(result *Result, err *AppError) *Result {
if err != nil {
l4g.Close()
time.Sleep(time.Second)
panic(err)
}
return result
}
// MustGeneric is a convenience function used for testing.
func (c *Client) MustGeneric(result interface{}, err *AppError) interface{} {
if err != nil {
l4g.Close()
time.Sleep(time.Second)
panic(err)
}
return result
}
// CheckStatusOK is a convenience function for checking the return of Web Service
// call that return the a map of status=OK.
func (c *Client) CheckStatusOK(r *http.Response) bool {
m := MapFromJson(r.Body)
defer closeBody(r)
if m != nil && m[STATUS] == STATUS_OK {
return true
}
return false
}
func (c *Client) fillInExtraProperties(r *http.Response) {
c.RequestId = r.Header.Get(HEADER_REQUEST_ID)
c.Etag = r.Header.Get(HEADER_ETAG_SERVER)
c.ServerVersion = r.Header.Get(HEADER_VERSION_ID)
}
func (c *Client) clearExtraProperties() {
c.RequestId = ""
c.Etag = ""
c.ServerVersion = ""
}
// General Routes Section
// GetClientProperties returns properties needed by the client to show/hide
// certian features. It returns a map of strings.
func (c *Client) GetClientProperties() (map[string]string, *AppError) {
c.clearExtraProperties()
if r, err := c.DoApiGet(c.GetGeneralRoute()+"/client_props", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return MapFromJson(r.Body), nil
}
}
// LogClient is a convenience Web Service call so clients can log messages into
// the server-side logs. For example we typically log javascript error messages
// into the server-side. It returns true if the logging was successful.
func (c *Client) LogClient(message string) (bool, *AppError) {
c.clearExtraProperties()
m := make(map[string]string)
m["level"] = "ERROR"
m["message"] = message
if r, err := c.DoApiPost(c.GetGeneralRoute()+"/log_client", MapToJson(m)); err != nil {
return false, err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return c.CheckStatusOK(r), nil
}
}
// GetPing returns a map of strings with server time, server version, and node Id.
// Systems that want to check on health status of the server should check the
// url /api/v3/ping for a 200 status response.
func (c *Client) GetPing() (map[string]string, *AppError) {
c.clearExtraProperties()
if r, err := c.DoApiGet(c.GetGeneralRoute()+"/ping", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return MapFromJson(r.Body), nil
}
}
// Team Routes Section
// CreateTeam creates a team based on the provided Team struct. On success it returns
// the Team struct with the Id, CreateAt and other server-decided fields populated.
func (c *Client) CreateTeam(team *Team) (*Result, *AppError) {
if r, err := c.DoApiPost("/teams/create", team.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), TeamFromJson(r.Body)}, nil
}
}
// GetAllTeams returns a map of all teams using team ids as the key.
func (c *Client) GetAllTeams() (*Result, *AppError) {
if r, err := c.DoApiGet("/teams/all", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), TeamMapFromJson(r.Body)}, nil
}
}
// GetAllTeamListings returns a map of all teams that are available to join
// using team ids as the key. Must be authenticated.
func (c *Client) GetAllTeamListings() (*Result, *AppError) {
if r, err := c.DoApiGet("/teams/all_team_listings", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), TeamMapFromJson(r.Body)}, nil
}
}
// FindTeamByName returns the strings "true" or "false" depending on if a team
// with the provided name was found.
func (c *Client) FindTeamByName(name string) (*Result, *AppError) {
m := make(map[string]string)
m["name"] = name
if r, err := c.DoApiPost("/teams/find_team_by_name", MapToJson(m)); err != nil {
return nil, err
} else {
val := false
if body, _ := ioutil.ReadAll(r.Body); string(body) == "true" {
val = true
}
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), val}, nil
}
}
// Adds a user directly to the team without sending an invite.
// The teamId and userId are required. You must be a valid member of the team and/or
// have the correct role to add new users to the team. Returns a map of user_id=userId
// if successful, otherwise returns an AppError.
func (c *Client) AddUserToTeam(teamId string, userId string) (*Result, *AppError) {
if len(teamId) == 0 {
teamId = c.GetTeamId()
}
data := make(map[string]string)
data["user_id"] = userId
if r, err := c.DoApiPost(fmt.Sprintf("/teams/%v", teamId)+"/add_user_to_team", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
// AddUserToTeamFromInvite adds a user to a team based off data provided in an invite link.
// Either hash and dataToHash are required or inviteId is required.
func (c *Client) AddUserToTeamFromInvite(hash, dataToHash, inviteId string) (*Result, *AppError) {
data := make(map[string]string)
data["hash"] = hash
data["data"] = dataToHash
data["invite_id"] = inviteId
if r, err := c.DoApiPost("/teams/add_user_to_team_from_invite", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), TeamFromJson(r.Body)}, nil
}
}
// Removes a user directly from the team.
// The teamId and userId are required. You must be a valid member of the team and/or
// have the correct role to remove a user from the team. Returns a map of user_id=userId
// if successful, otherwise returns an AppError.
func (c *Client) RemoveUserFromTeam(teamId string, userId string) (*Result, *AppError) {
if len(teamId) == 0 {
teamId = c.GetTeamId()
}
data := make(map[string]string)
data["user_id"] = userId
if r, err := c.DoApiPost(fmt.Sprintf("/teams/%v", teamId)+"/remove_user_from_team", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) InviteMembers(invites *Invites) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/invite_members", invites.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), InvitesFromJson(r.Body)}, nil
}
}
// UpdateTeam updates a team based on the changes in the provided team struct. On success
// it returns a sanitized version of the updated team. Must be authenticated as a team admin
// for that team or a system admin.
func (c *Client) UpdateTeam(team *Team) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/update", team.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
// User Routes Section
// CreateUser creates a user in the system based on the provided user struct.
func (c *Client) CreateUser(user *User, hash string) (*Result, *AppError) {
if r, err := c.DoApiPost("/users/create", user.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil
}
}
// CreateUserWithInvite creates a user based on the provided user struct. Either the hash and
// data strings or the inviteId is required from the invite.
func (c *Client) CreateUserWithInvite(user *User, hash string, data string, inviteId string) (*Result, *AppError) {
url := "/users/create?d=" + url.QueryEscape(data) + "&h=" + url.QueryEscape(hash) + "&iid=" + url.QueryEscape(inviteId)
if r, err := c.DoApiPost(url, user.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil
}
}
func (c *Client) CreateUserFromSignup(user *User, data string, hash string) (*Result, *AppError) {
if r, err := c.DoApiPost("/users/create?d="+url.QueryEscape(data)+"&h="+hash, user.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil
}
}
// GetUser returns a user based on a provided user id string. Must be authenticated.
func (c *Client) GetUser(id string, etag string) (*Result, *AppError) {
if r, err := c.DoApiGet("/users/"+id+"/get", "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil
}
}
// getByUsername returns a user based on a provided username string. Must be authenticated.
func (c *Client) GetByUsername(username string, etag string) (*Result, *AppError) {
if r, err := c.DoApiGet(fmt.Sprintf("/users/name/%v", username), "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil
}
}
// getByEmail returns a user based on a provided username string. Must be authenticated.
func (c *Client) GetByEmail(email string, etag string) (*User, *ResponseMetadata) {
if r, err := c.DoApiGet(fmt.Sprintf("/users/email/%v", email), "", etag); err != nil {
return nil, &ResponseMetadata{StatusCode: r.StatusCode, Error: err}
} else {
defer closeBody(r)
return UserFromJson(r.Body),
&ResponseMetadata{
StatusCode: r.StatusCode,
RequestId: r.Header.Get(HEADER_REQUEST_ID),
Etag: r.Header.Get(HEADER_ETAG_SERVER),
}
}
}
// GetMe returns the current user.
func (c *Client) GetMe(etag string) (*Result, *AppError) {
if r, err := c.DoApiGet("/users/me", "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil
}
}
// GetProfiles returns a map of users using user id as the key. Must be authenticated.
func (c *Client) GetProfiles(offset int, limit int, etag string) (*Result, *AppError) {
if r, err := c.DoApiGet(fmt.Sprintf("/users/%v/%v", offset, limit), "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil
}
}
// GetProfilesInTeam returns a map of users for a team using user id as the key. Must
// be authenticated.
func (c *Client) GetProfilesInTeam(teamId string, offset int, limit int, etag string) (*Result, *AppError) {
if r, err := c.DoApiGet(fmt.Sprintf("/teams/%v/users/%v/%v", teamId, offset, limit), "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil
}
}
// GetProfilesInChannel returns a map of users for a channel using user id as the key. Must
// be authenticated.
func (c *Client) GetProfilesInChannel(channelId string, offset int, limit int, etag string) (*Result, *AppError) {
if r, err := c.DoApiGet(fmt.Sprintf(c.GetChannelRoute(channelId)+"/users/%v/%v", offset, limit), "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil
}
}
// GetProfilesNotInChannel returns a map of users not in a channel but on the team using user id as the key. Must
// be authenticated.
func (c *Client) GetProfilesNotInChannel(channelId string, offset int, limit int, etag string) (*Result, *AppError) {
if r, err := c.DoApiGet(fmt.Sprintf(c.GetChannelRoute(channelId)+"/users/not_in_channel/%v/%v", offset, limit), "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil
}
}
// GetProfilesByIds returns a map of users based on the user ids provided. Must
// be authenticated.
func (c *Client) GetProfilesByIds(userIds []string) (*Result, *AppError) {
if r, err := c.DoApiPost("/users/ids", ArrayToJson(userIds)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil
}
}
// SearchUsers returns a list of users that have a username matching or similar to the search term. Must
// be authenticated.
func (c *Client) SearchUsers(params UserSearch) (*Result, *AppError) {
if r, err := c.DoApiPost("/users/search", params.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserListFromJson(r.Body)}, nil
}
}
// AutocompleteUsersInChannel returns two lists for autocompletion of users in a channel. The first list "in_channel",
// specifies users in the channel. The second list "out_of_channel" specifies users outside of the
// channel. Term, the string to search against, is required, channel id is also required. Must be authenticated.
func (c *Client) AutocompleteUsersInChannel(term string, channelId string) (*Result, *AppError) {
url := fmt.Sprintf("%s/users/autocomplete?term=%s", c.GetChannelRoute(channelId), url.QueryEscape(term))
if r, err := c.DoApiGet(url, "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserAutocompleteInChannelFromJson(r.Body)}, nil
}
}
// AutocompleteUsersInTeam returns a list for autocompletion of users in a team. The list "in_team" specifies
// the users in the team that match the provided term, matching against username, full name and
// nickname. Must be authenticated.
func (c *Client) AutocompleteUsersInTeam(term string) (*Result, *AppError) {
url := fmt.Sprintf("%s/users/autocomplete?term=%s", c.GetTeamRoute(), url.QueryEscape(term))
if r, err := c.DoApiGet(url, "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserAutocompleteInTeamFromJson(r.Body)}, nil
}
}
// AutocompleteUsers returns a list for autocompletion of users on the system that match the provided term,
// matching against username, full name and nickname. Must be authenticated.
func (c *Client) AutocompleteUsers(term string) (*Result, *AppError) {
url := fmt.Sprintf("/users/autocomplete?term=%s", url.QueryEscape(term))
if r, err := c.DoApiGet(url, "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserListFromJson(r.Body)}, nil
}
}
// LoginById authenticates a user by user id and password.
func (c *Client) LoginById(id string, password string) (*Result, *AppError) {
m := make(map[string]string)
m["id"] = id
m["password"] = password
return c.login(m)
}
// Login authenticates a user by login id, which can be username, email or some sort
// of SSO identifier based on configuration, and a password.
func (c *Client) Login(loginId string, password string) (*Result, *AppError) {
m := make(map[string]string)
m["login_id"] = loginId
m["password"] = password
return c.login(m)
}
// LoginByLdap authenticates a user by LDAP id and password.
func (c *Client) LoginByLdap(loginId string, password string) (*Result, *AppError) {
m := make(map[string]string)
m["login_id"] = loginId
m["password"] = password
m["ldap_only"] = "true"
return c.login(m)
}
// LoginWithDevice authenticates a user by login id (username, email or some sort
// of SSO identifier based on configuration), password and attaches a device id to
// the session.
func (c *Client) LoginWithDevice(loginId string, password string, deviceId string) (*Result, *AppError) {
m := make(map[string]string)
m["login_id"] = loginId
m["password"] = password
m["device_id"] = deviceId
return c.login(m)
}
func (c *Client) login(m map[string]string) (*Result, *AppError) {
if r, err := c.DoApiPost("/users/login", MapToJson(m)); err != nil {
return nil, err
} else {
c.AuthToken = r.Header.Get(HEADER_TOKEN)
c.AuthType = HEADER_BEARER
sessionToken := getCookie(SESSION_COOKIE_TOKEN, r)
if c.AuthToken != sessionToken.Value {
NewLocAppError("/users/login", "model.client.login.app_error", nil, "")
}
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil
}
}
// Logout terminates the current user's session.
func (c *Client) Logout() (*Result, *AppError) {
if r, err := c.DoApiPost("/users/logout", ""); err != nil {
return nil, err
} else {
c.AuthToken = ""
c.AuthType = HEADER_BEARER
c.TeamId = ""
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
// CheckMfa returns a map with key "mfa_required" with the string value "true" or "false",
// indicating whether MFA is required to log the user in, based on a provided login id
// (username, email or some sort of SSO identifier based on configuration).
func (c *Client) CheckMfa(loginId string) (*Result, *AppError) {
m := make(map[string]string)
m["login_id"] = loginId
if r, err := c.DoApiPost("/users/mfa", MapToJson(m)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
// GenerateMfaSecret returns a QR code image containing the secret, to be scanned
// by a multi-factor authentication mobile application. It also returns the secret
// for manual entry. Must be authenticated.
func (c *Client) GenerateMfaSecret() (*Result, *AppError) {
if r, err := c.DoApiGet("/users/generate_mfa_secret", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
// UpdateMfa activates multi-factor authenticates for the current user if activate
// is true and a valid token is provided. If activate is false, then token is not
// required and multi-factor authentication is disabled for the current user.
func (c *Client) UpdateMfa(activate bool, token string) (*Result, *AppError) {
m := make(map[string]interface{})
m["activate"] = activate
m["token"] = token
if r, err := c.DoApiPost("/users/update_mfa", StringInterfaceToJson(m)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) AdminResetMfa(userId string) (*Result, *AppError) {
m := make(map[string]string)
m["user_id"] = userId
if r, err := c.DoApiPost("/admin/reset_mfa", MapToJson(m)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) RevokeSession(sessionAltId string) (*Result, *AppError) {
m := make(map[string]string)
m["id"] = sessionAltId
if r, err := c.DoApiPost("/users/revoke_session", MapToJson(m)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) GetSessions(id string) (*Result, *AppError) {
if r, err := c.DoApiGet("/users/"+id+"/sessions", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), SessionsFromJson(r.Body)}, nil
}
}
func (c *Client) EmailToOAuth(m map[string]string) (*Result, *AppError) {
if r, err := c.DoApiPost("/users/claim/email_to_oauth", MapToJson(m)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) OAuthToEmail(m map[string]string) (*Result, *AppError) {
if r, err := c.DoApiPost("/users/claim/oauth_to_email", MapToJson(m)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) LDAPToEmail(m map[string]string) (*Result, *AppError) {
if r, err := c.DoApiPost("/users/claim/ldap_to_email", MapToJson(m)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) EmailToLDAP(m map[string]string) (*Result, *AppError) {
if r, err := c.DoApiPost("/users/claim/ldap_to_email", MapToJson(m)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) Command(channelId string, command string) (*Result, *AppError) {
args := &CommandArgs{ChannelId: channelId, Command: command}
if r, err := c.DoApiPost(c.GetTeamRoute()+"/commands/execute", args.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), CommandResponseFromJson(r.Body)}, nil
}
}
func (c *Client) ListCommands() (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetTeamRoute()+"/commands/list", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), CommandListFromJson(r.Body)}, nil
}
}
func (c *Client) ListTeamCommands() (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetTeamRoute()+"/commands/list_team_commands", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), CommandListFromJson(r.Body)}, nil
}
}
func (c *Client) CreateCommand(cmd *Command) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/commands/create", cmd.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), CommandFromJson(r.Body)}, nil
}
}
func (c *Client) UpdateCommand(cmd *Command) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/commands/update", cmd.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), CommandFromJson(r.Body)}, nil
}
}
func (c *Client) RegenCommandToken(data map[string]string) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/commands/regen_token", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), CommandFromJson(r.Body)}, nil
}
}
func (c *Client) DeleteCommand(data map[string]string) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/commands/delete", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) GetAudits(id string, etag string) (*Result, *AppError) {
if r, err := c.DoApiGet("/users/"+id+"/audits", "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), AuditsFromJson(r.Body)}, nil
}
}
func (c *Client) GetLogs() (*Result, *AppError) {
if r, err := c.DoApiGet("/admin/logs", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ArrayFromJson(r.Body)}, nil
}
}
func (c *Client) GetClusterStatus() ([]*ClusterInfo, *AppError) {
if r, err := c.DoApiGet("/admin/cluster_status", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return ClusterInfosFromJson(r.Body), nil
}
}
// GetRecentlyActiveUsers returns a map of users including lastActivityAt using user id as the key
func (c *Client) GetRecentlyActiveUsers(teamId string) (*Result, *AppError) {
if r, err := c.DoApiGet("/admin/recently_active_users/"+teamId, "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil
}
}
func (c *Client) GetAllAudits() (*Result, *AppError) {
if r, err := c.DoApiGet("/admin/audits", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), AuditsFromJson(r.Body)}, nil
}
}
func (c *Client) GetConfig() (*Result, *AppError) {
if r, err := c.DoApiGet("/admin/config", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ConfigFromJson(r.Body)}, nil
}
}
// ReloadConfig will reload the config.json file from disk. Properties
// requiring a server restart will still need a server restart. You must
// have the system admin role to call this method. It will return status=OK
// if it's successfully reloaded the config file, otherwise check the returned error.
func (c *Client) ReloadConfig() (bool, *AppError) {
c.clearExtraProperties()
if r, err := c.DoApiGet("/admin/reload_config", "", ""); err != nil {
return false, err
} else {
c.fillInExtraProperties(r)
return c.CheckStatusOK(r), nil
}
}
func (c *Client) InvalidateAllCaches() (bool, *AppError) {
c.clearExtraProperties()
if r, err := c.DoApiGet("/admin/invalidate_all_caches", "", ""); err != nil {
return false, err
} else {
c.fillInExtraProperties(r)
return c.CheckStatusOK(r), nil
}
}
func (c *Client) SaveConfig(config *Config) (*Result, *AppError) {
if r, err := c.DoApiPost("/admin/save_config", config.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
// RecycleDatabaseConnection will attempt to recycle the database connections.
// You must have the system admin role to call this method. It will return status=OK
// if it's successfully recycled the connections, otherwise check the returned error.
func (c *Client) RecycleDatabaseConnection() (bool, *AppError) {
c.clearExtraProperties()
if r, err := c.DoApiGet("/admin/recycle_db_conn", "", ""); err != nil {
return false, err
} else {
c.fillInExtraProperties(r)
return c.CheckStatusOK(r), nil
}
}
func (c *Client) TestEmail(config *Config) (*Result, *AppError) {
if r, err := c.DoApiPost("/admin/test_email", config.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
// TestLdap will run a connection test on the current LDAP settings.
// It will return the standard OK response if settings work. Otherwise
// it will return an appropriate error.
func (c *Client) TestLdap(config *Config) (*Result, *AppError) {
if r, err := c.DoApiPost("/admin/ldap_test", config.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) GetComplianceReports() (*Result, *AppError) {
if r, err := c.DoApiGet("/admin/compliance_reports", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), CompliancesFromJson(r.Body)}, nil
}
}
func (c *Client) SaveComplianceReport(job *Compliance) (*Result, *AppError) {
if r, err := c.DoApiPost("/admin/save_compliance_report", job.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ComplianceFromJson(r.Body)}, nil
}
}
func (c *Client) DownloadComplianceReport(id string) (*Result, *AppError) {
var rq *http.Request
rq, _ = http.NewRequest("GET", c.ApiUrl+"/admin/download_compliance_report/"+id, nil)
rq.Close = true
if len(c.AuthToken) > 0 {
rq.Header.Set(HEADER_AUTH, "BEARER "+c.AuthToken)
}
if rp, err := c.HttpClient.Do(rq); err != nil {
return nil, NewLocAppError("/admin/download_compliance_report", "model.client.connecting.app_error", nil, err.Error())
} else if rp.StatusCode >= 300 {
defer rp.Body.Close()
return nil, AppErrorFromJson(rp.Body)
} else {
defer closeBody(rp)
return &Result{rp.Header.Get(HEADER_REQUEST_ID),
rp.Header.Get(HEADER_ETAG_SERVER), rp.Body}, nil
}
}
func (c *Client) GetTeamAnalytics(teamId, name string) (*Result, *AppError) {
if r, err := c.DoApiGet("/admin/analytics/"+teamId+"/"+name, "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), AnalyticsRowsFromJson(r.Body)}, nil
}
}
func (c *Client) GetSystemAnalytics(name string) (*Result, *AppError) {
if r, err := c.DoApiGet("/admin/analytics/"+name, "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), AnalyticsRowsFromJson(r.Body)}, nil
}
}
// Initiate immediate synchronization of LDAP users.
// The synchronization will be performed asynchronously and this function will
// always return OK unless you don't have permissions.
// You must be the system administrator to use this function.
func (c *Client) LdapSyncNow() (*Result, *AppError) {
if r, err := c.DoApiPost("/admin/ldap_sync_now", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) CreateChannel(channel *Channel) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/create", channel.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil
}
}
func (c *Client) CreateDirectChannel(userId string) (*Result, *AppError) {
data := make(map[string]string)
data["user_id"] = userId
if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/create_direct", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil
}
}
func (c *Client) CreateGroupChannel(userIds []string) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/create_group", ArrayToJson(userIds)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil
}
}
func (c *Client) UpdateChannel(channel *Channel) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/update", channel.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil
}
}
func (c *Client) UpdateChannelHeader(data map[string]string) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/update_header", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil
}
}
func (c *Client) UpdateChannelPurpose(data map[string]string) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/update_purpose", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil
}
}
func (c *Client) UpdateNotifyProps(data map[string]string) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/update_notify_props", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) GetMyChannelMembers() (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetTeamRoute()+"/channels/members", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelMembersFromJson(r.Body)}, nil
}
}
func (c *Client) GetChannel(id, etag string) (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetChannelRoute(id)+"/", "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelDataFromJson(r.Body)}, nil
}
}
// SCHEDULED FOR DEPRECATION IN 3.7 - use GetMoreChannelsPage instead
func (c *Client) GetMoreChannels(etag string) (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetTeamRoute()+"/channels/more", "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelListFromJson(r.Body)}, nil
}
}
// GetMoreChannelsPage will return a page of open channels the user is not in based on
// the provided offset and limit. Must be authenticated.
func (c *Client) GetMoreChannelsPage(offset int, limit int) (*Result, *AppError) {
if r, err := c.DoApiGet(fmt.Sprintf(c.GetTeamRoute()+"/channels/more/%v/%v", offset, limit), "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelListFromJson(r.Body)}, nil
}
}
// SearchMoreChannels will return a list of open channels the user is not in, that matches
// the search criteria provided. Must be authenticated.
func (c *Client) SearchMoreChannels(channelSearch ChannelSearch) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/more/search", channelSearch.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelListFromJson(r.Body)}, nil
}
}
// AutocompleteChannels will return a list of open channels that match the provided
// string. Must be authenticated.
func (c *Client) AutocompleteChannels(term string) (*Result, *AppError) {
url := fmt.Sprintf("%s/channels/autocomplete?term=%s", c.GetTeamRoute(), url.QueryEscape(term))
if r, err := c.DoApiGet(url, "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelListFromJson(r.Body)}, nil
}
}
func (c *Client) GetChannelCounts(etag string) (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetTeamRoute()+"/channels/counts", "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelCountsFromJson(r.Body)}, nil
}
}
func (c *Client) GetChannels(etag string) (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetTeamRoute()+"/channels/", "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelListFromJson(r.Body)}, nil
}
}
func (c *Client) GetChannelByName(channelName string) (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetChannelNameRoute(channelName), "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil
}
}
func (c *Client) JoinChannel(id string) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetChannelRoute(id)+"/join", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), nil}, nil
}
}
func (c *Client) JoinChannelByName(name string) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetChannelNameRoute(name)+"/join", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), nil}, nil
}
}
func (c *Client) LeaveChannel(id string) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetChannelRoute(id)+"/leave", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), nil}, nil
}
}
func (c *Client) DeleteChannel(id string) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetChannelRoute(id)+"/delete", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), nil}, nil
}
}
func (c *Client) AddChannelMember(id, user_id string) (*Result, *AppError) {
data := make(map[string]string)
data["user_id"] = user_id
if r, err := c.DoApiPost(c.GetChannelRoute(id)+"/add", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), nil}, nil
}
}
func (c *Client) RemoveChannelMember(id, user_id string) (*Result, *AppError) {
data := make(map[string]string)
data["user_id"] = user_id
if r, err := c.DoApiPost(c.GetChannelRoute(id)+"/remove", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), nil}, nil
}
}
// UpdateLastViewedAt will mark a channel as read.
// The channelId indicates the channel to mark as read. If active is true, push notifications
// will be cleared if there are unread messages. The default for active is true.
// SCHEDULED FOR DEPRECATION IN 3.8 - use ViewChannel instead
func (c *Client) UpdateLastViewedAt(channelId string, active bool) (*Result, *AppError) {
data := make(map[string]interface{})
data["active"] = active
if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+"/update_last_viewed_at", StringInterfaceToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), nil}, nil
}
}
// ViewChannel performs all the actions related to viewing a channel. This includes marking
// the channel and the previous one as read, and marking the channel as being actively viewed.
// ChannelId is required but may be blank to indicate no channel is being viewed.
// PrevChannelId is optional, populate to indicate a channel switch occurred.
func (c *Client) ViewChannel(params ChannelView) (bool, *ResponseMetadata) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/view", params.ToJson()); err != nil {
return false, &ResponseMetadata{StatusCode: r.StatusCode, Error: err}
} else {
return c.CheckStatusOK(r),
&ResponseMetadata{
StatusCode: r.StatusCode,
RequestId: r.Header.Get(HEADER_REQUEST_ID),
Etag: r.Header.Get(HEADER_ETAG_SERVER),
}
}
}
func (c *Client) GetChannelStats(id string, etag string) (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetChannelRoute(id)+"/stats", "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelStatsFromJson(r.Body)}, nil
}
}
func (c *Client) GetChannelMember(channelId string, userId string) (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+"/members/"+userId, "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelMemberFromJson(r.Body)}, nil
}
}
// GetChannelMembersByIds will return channel member objects as an array based on the
// channel id and a list of user ids provided. Must be authenticated.
func (c *Client) GetChannelMembersByIds(channelId string, userIds []string) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+"/members/ids", ArrayToJson(userIds)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), ChannelMembersFromJson(r.Body)}, nil
}
}
func (c *Client) CreatePost(post *Post) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetChannelRoute(post.ChannelId)+"/posts/create", post.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), PostFromJson(r.Body)}, nil
}
}
func (c *Client) UpdatePost(post *Post) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetChannelRoute(post.ChannelId)+"/posts/update", post.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), PostFromJson(r.Body)}, nil
}
}
func (c *Client) GetPosts(channelId string, offset int, limit int, etag string) (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/page/%v/%v", offset, limit), "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil
}
}
func (c *Client) GetPostsSince(channelId string, time int64) (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/since/%v", time), "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil
}
}
func (c *Client) GetPostsBefore(channelId string, postid string, offset int, limit int, etag string) (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/before/%v/%v", postid, offset, limit), "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil
}
}
func (c *Client) GetPostsAfter(channelId string, postid string, offset int, limit int, etag string) (*Result, *AppError) {
if r, err := c.DoApiGet(fmt.Sprintf(c.GetChannelRoute(channelId)+"/posts/%v/after/%v/%v", postid, offset, limit), "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil
}
}
func (c *Client) GetPost(channelId string, postId string, etag string) (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/get", postId), "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil
}
}
// GetPostById returns a post and any posts in the same thread by post id
func (c *Client) GetPostById(postId string, etag string) (*PostList, *ResponseMetadata) {
if r, err := c.DoApiGet(c.GetTeamRoute()+fmt.Sprintf("/posts/%v", postId), "", etag); err != nil {
return nil, &ResponseMetadata{StatusCode: r.StatusCode, Error: err}
} else {
defer closeBody(r)
return PostListFromJson(r.Body),
&ResponseMetadata{
StatusCode: r.StatusCode,
RequestId: r.Header.Get(HEADER_REQUEST_ID),
Etag: r.Header.Get(HEADER_ETAG_SERVER),
}
}
}
// GetPermalink returns a post list, based on the provided channel and post ID.
func (c *Client) GetPermalink(channelId string, postId string, etag string) (*PostList, *ResponseMetadata) {
if r, err := c.DoApiGet(c.GetTeamRoute()+fmt.Sprintf("/pltmp/%v", postId), "", etag); err != nil {
return nil, &ResponseMetadata{StatusCode: r.StatusCode, Error: err}
} else {
defer closeBody(r)
return PostListFromJson(r.Body),
&ResponseMetadata{
StatusCode: r.StatusCode,
RequestId: r.Header.Get(HEADER_REQUEST_ID),
Etag: r.Header.Get(HEADER_ETAG_SERVER),
}
}
}
func (c *Client) DeletePost(channelId string, postId string) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/delete", postId), ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) SearchPosts(terms string, isOrSearch bool) (*Result, *AppError) {
data := map[string]interface{}{}
data["terms"] = terms
data["is_or_search"] = isOrSearch
if r, err := c.DoApiPost(c.GetTeamRoute()+"/posts/search", StringInterfaceToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil
}
}
// GetFlaggedPosts will return a post list of posts that have been flagged by the user.
// The page is set by the integer parameters offset and limit.
func (c *Client) GetFlaggedPosts(offset int, limit int) (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetTeamRoute()+fmt.Sprintf("/posts/flagged/%v/%v", offset, limit), "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil
}
}
func (c *Client) GetPinnedPosts(channelId string) (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+"/pinned", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil
}
}
func (c *Client) UploadProfileFile(data []byte, contentType string) (*Result, *AppError) {
return c.uploadFile(c.ApiUrl+"/users/newimage", data, contentType)
}
func (c *Client) UploadPostAttachment(data []byte, channelId string, filename string) (*FileUploadResponse, *AppError) {
c.clearExtraProperties()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
if part, err := writer.CreateFormFile("files", filename); err != nil {
return nil, NewLocAppError("UploadPostAttachment", "model.client.upload_post_attachment.file.app_error", nil, err.Error())
} else if _, err = io.Copy(part, bytes.NewBuffer(data)); err != nil {
return nil, NewLocAppError("UploadPostAttachment", "model.client.upload_post_attachment.file.app_error", nil, err.Error())
}
if part, err := writer.CreateFormField("channel_id"); err != nil {
return nil, NewLocAppError("UploadPostAttachment", "model.client.upload_post_attachment.channel_id.app_error", nil, err.Error())
} else if _, err = io.Copy(part, strings.NewReader(channelId)); err != nil {
return nil, NewLocAppError("UploadPostAttachment", "model.client.upload_post_attachment.channel_id.app_error", nil, err.Error())
}
if err := writer.Close(); err != nil {
return nil, NewLocAppError("UploadPostAttachment", "model.client.upload_post_attachment.writer.app_error", nil, err.Error())
}
if result, err := c.uploadFile(c.ApiUrl+c.GetTeamRoute()+"/files/upload", body.Bytes(), writer.FormDataContentType()); err != nil {
return nil, err
} else {
return result.Data.(*FileUploadResponse), nil
}
}
func (c *Client) uploadFile(url string, data []byte, contentType string) (*Result, *AppError) {
rq, _ := http.NewRequest("POST", url, bytes.NewReader(data))
rq.Header.Set("Content-Type", contentType)
rq.Close = true
if len(c.AuthToken) > 0 {
rq.Header.Set(HEADER_AUTH, "BEARER "+c.AuthToken)
}
if rp, err := c.HttpClient.Do(rq); err != nil {
return nil, NewLocAppError(url, "model.client.connecting.app_error", nil, err.Error())
} else if rp.StatusCode >= 300 {
return nil, AppErrorFromJson(rp.Body)
} else {
defer closeBody(rp)
return &Result{rp.Header.Get(HEADER_REQUEST_ID),
rp.Header.Get(HEADER_ETAG_SERVER), FileUploadResponseFromJson(rp.Body)}, nil
}
}
func (c *Client) GetFile(fileId string) (io.ReadCloser, *AppError) {
if r, err := c.DoApiGet(c.GetFileRoute(fileId)+"/get", "", ""); err != nil {
return nil, err
} else {
c.fillInExtraProperties(r)
return r.Body, nil
}
}
func (c *Client) GetFileThumbnail(fileId string) (io.ReadCloser, *AppError) {
if r, err := c.DoApiGet(c.GetFileRoute(fileId)+"/get_thumbnail", "", ""); err != nil {
return nil, err
} else {
c.fillInExtraProperties(r)
return r.Body, nil
}
}
func (c *Client) GetFilePreview(fileId string) (io.ReadCloser, *AppError) {
if r, err := c.DoApiGet(c.GetFileRoute(fileId)+"/get_preview", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return r.Body, nil
}
}
func (c *Client) GetFileInfo(fileId string) (*FileInfo, *AppError) {
if r, err := c.DoApiGet(c.GetFileRoute(fileId)+"/get_info", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return FileInfoFromJson(r.Body), nil
}
}
func (c *Client) GetPublicLink(fileId string) (string, *AppError) {
if r, err := c.DoApiGet(c.GetFileRoute(fileId)+"/get_public_link", "", ""); err != nil {
return "", err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return StringFromJson(r.Body), nil
}
}
func (c *Client) UpdateUser(user *User) (*Result, *AppError) {
if r, err := c.DoApiPost("/users/update", user.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil
}
}
func (c *Client) UpdateUserRoles(userId string, roles string) (*Result, *AppError) {
data := make(map[string]string)
data["new_roles"] = roles
if r, err := c.DoApiPost(c.GetUserRequiredRoute(userId)+"/update_roles", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) UpdateTeamRoles(userId string, roles string) (*Result, *AppError) {
data := make(map[string]string)
data["new_roles"] = roles
data["user_id"] = userId
if r, err := c.DoApiPost(c.GetTeamRoute()+"/update_member_roles", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) AttachDeviceId(deviceId string) (*Result, *AppError) {
data := make(map[string]string)
data["device_id"] = deviceId
if r, err := c.DoApiPost("/users/attach_device", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil
}
}
func (c *Client) UpdateActive(userId string, active bool) (*Result, *AppError) {
data := make(map[string]string)
data["user_id"] = userId
data["active"] = strconv.FormatBool(active)
if r, err := c.DoApiPost("/users/update_active", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil
}
}
func (c *Client) UpdateUserNotify(data map[string]string) (*Result, *AppError) {
if r, err := c.DoApiPost("/users/update_notify", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil
}
}
func (c *Client) UpdateUserPassword(userId, currentPassword, newPassword string) (*Result, *AppError) {
data := make(map[string]string)
data["current_password"] = currentPassword
data["new_password"] = newPassword
data["user_id"] = userId
if r, err := c.DoApiPost("/users/newpassword", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) SendPasswordReset(email string) (*Result, *AppError) {
data := map[string]string{}
data["email"] = email
if r, err := c.DoApiPost("/users/send_password_reset", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) ResetPassword(code, newPassword string) (*Result, *AppError) {
data := map[string]string{}
data["code"] = code
data["new_password"] = newPassword
if r, err := c.DoApiPost("/users/reset_password", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) AdminResetPassword(userId, newPassword string) (*Result, *AppError) {
data := map[string]string{}
data["user_id"] = userId
data["new_password"] = newPassword
if r, err := c.DoApiPost("/admin/reset_password", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
// GetStatuses returns a map of string statuses using user id as the key
func (c *Client) GetStatuses() (*Result, *AppError) {
if r, err := c.DoApiGet("/users/status", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
// GetStatusesByIds returns a map of string statuses using user id as the key,
// based on the provided user ids
func (c *Client) GetStatusesByIds(userIds []string) (*Result, *AppError) {
if r, err := c.DoApiPost("/users/status/ids", ArrayToJson(userIds)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
// SetActiveChannel sets the the channel id the user is currently viewing.
// The channelId key is required but the value can be blank. Returns standard
// response.
// SCHEDULED FOR DEPRECATION IN 3.8 - use ViewChannel instead
func (c *Client) SetActiveChannel(channelId string) (*Result, *AppError) {
data := map[string]string{}
data["channel_id"] = channelId
if r, err := c.DoApiPost("/users/status/set_active_channel", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) GetMyTeam(etag string) (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetTeamRoute()+"/me", "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), TeamFromJson(r.Body)}, nil
}
}
// GetTeamMembers will return a page of team member objects as an array paged based on the
// team id, offset and limit provided. Must be authenticated.
func (c *Client) GetTeamMembers(teamId string, offset int, limit int) (*Result, *AppError) {
if r, err := c.DoApiGet(fmt.Sprintf("/teams/%v/members/%v/%v", teamId, offset, limit), "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), TeamMembersFromJson(r.Body)}, nil
}
}
// GetMyTeamMembers will return an array with team member objects that the current user
// is a member of. Must be authenticated.
func (c *Client) GetMyTeamMembers() (*Result, *AppError) {
if r, err := c.DoApiGet("/teams/members", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), TeamMembersFromJson(r.Body)}, nil
}
}
// GetMyTeamsUnread will return an array with TeamUnread objects that contain the amount of
// unread messages and mentions the current user has for the teams it belongs to.
// An optional team ID can be set to exclude that team from the results. Must be authenticated.
func (c *Client) GetMyTeamsUnread(teamId string) (*Result, *AppError) {
endpoint := "/teams/unread"
if teamId != "" {
endpoint += fmt.Sprintf("?id=%s", url.QueryEscape(teamId))
}
if r, err := c.DoApiGet(endpoint, "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), TeamsUnreadFromJson(r.Body)}, nil
}
}
// GetTeamMember will return a team member object based on the team id and user id provided.
// Must be authenticated.
func (c *Client) GetTeamMember(teamId string, userId string) (*Result, *AppError) {
if r, err := c.DoApiGet(fmt.Sprintf("/teams/%v/members/%v", teamId, userId), "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), TeamMemberFromJson(r.Body)}, nil
}
}
// GetTeamStats will return a team stats object containing the number of users on the team
// based on the team id provided. Must be authenticated.
func (c *Client) GetTeamStats(teamId string) (*Result, *AppError) {
if r, err := c.DoApiGet(fmt.Sprintf("/teams/%v/stats", teamId), "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), TeamStatsFromJson(r.Body)}, nil
}
}
// GetTeamStats will return a team stats object containing the number of users on the team
// based on the team id provided. Must be authenticated.
func (c *Client) GetTeamByName(teamName string) (*Result, *AppError) {
if r, err := c.DoApiGet(fmt.Sprintf("/teams/name/%v", teamName), "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), TeamStatsFromJson(r.Body)}, nil
}
}
// GetTeamMembersByIds will return team member objects as an array based on the
// team id and a list of user ids provided. Must be authenticated.
func (c *Client) GetTeamMembersByIds(teamId string, userIds []string) (*Result, *AppError) {
if r, err := c.DoApiPost(fmt.Sprintf("/teams/%v/members/ids", teamId), ArrayToJson(userIds)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), TeamMembersFromJson(r.Body)}, nil
}
}
// RegisterApp creates a new OAuth2 app to be used with the OAuth2 Provider. On success
// it returns the created app. Must be authenticated as a user.
func (c *Client) RegisterApp(app *OAuthApp) (*Result, *AppError) {
if r, err := c.DoApiPost("/oauth/register", app.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), OAuthAppFromJson(r.Body)}, nil
}
}
// AllowOAuth allows a new session by an OAuth2 App. On success
// it returns the url to be redirected back to the app which initiated the oauth2 flow.
// Must be authenticated as a user.
func (c *Client) AllowOAuth(rspType, clientId, redirect, scope, state string) (*Result, *AppError) {
if r, err := c.DoApiGet("/oauth/allow?response_type="+rspType+"&client_id="+clientId+"&redirect_uri="+url.QueryEscape(redirect)+"&scope="+scope+"&state="+url.QueryEscape(state), "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
// GetOAuthAppsByUser returns the OAuth2 Apps registered by the user. On success
// it returns a list of OAuth2 Apps from the same user or all the registered apps if the user
// is a System Administrator. Must be authenticated as a user.
func (c *Client) GetOAuthAppsByUser() (*Result, *AppError) {
if r, err := c.DoApiGet("/oauth/list", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), OAuthAppListFromJson(r.Body)}, nil
}
}
// GetOAuthAppInfo lookup an OAuth2 App using the client_id. On success
// it returns a Sanitized OAuth2 App. Must be authenticated as a user.
func (c *Client) GetOAuthAppInfo(clientId string) (*Result, *AppError) {
if r, err := c.DoApiGet("/oauth/app/"+clientId, "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), OAuthAppFromJson(r.Body)}, nil
}
}
// DeleteOAuthApp deletes an OAuth2 app, the app must be deleted by the same user who created it or
// a System Administrator. On success returs Status OK. Must be authenticated as a user.
func (c *Client) DeleteOAuthApp(id string) (*Result, *AppError) {
data := make(map[string]string)
data["id"] = id
if r, err := c.DoApiPost("/oauth/delete", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
// GetOAuthAuthorizedApps returns the OAuth2 Apps authorized by the user. On success
// it returns a list of sanitized OAuth2 Authorized Apps by the user.
func (c *Client) GetOAuthAuthorizedApps() (*Result, *AppError) {
if r, err := c.DoApiGet("/oauth/authorized", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), OAuthAppListFromJson(r.Body)}, nil
}
}
// OAuthDeauthorizeApp deauthorize a user an OAuth 2.0 app. On success
// it returns status OK or an AppError on fail.
func (c *Client) OAuthDeauthorizeApp(clientId string) *AppError {
if r, err := c.DoApiPost("/oauth/"+clientId+"/deauthorize", ""); err != nil {
return err
} else {
defer closeBody(r)
return nil
}
}
// RegenerateOAuthAppSecret generates a new OAuth App Client Secret. On success
// it returns an OAuth2 App. Must be authenticated as a user and the same user who
// registered the app or a System Admin.
func (c *Client) RegenerateOAuthAppSecret(clientId string) (*Result, *AppError) {
if r, err := c.DoApiPost("/oauth/"+clientId+"/regen_secret", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), OAuthAppFromJson(r.Body)}, nil
}
}
func (c *Client) GetAccessToken(data url.Values) (*Result, *AppError) {
if r, err := c.DoPost("/oauth/access_token", data.Encode(), "application/x-www-form-urlencoded"); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), AccessResponseFromJson(r.Body)}, nil
}
}
func (c *Client) CreateIncomingWebhook(hook *IncomingWebhook) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/incoming/create", hook.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), IncomingWebhookFromJson(r.Body)}, nil
}
}
func (c *Client) UpdateIncomingWebhook(hook *IncomingWebhook) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/incoming/update", hook.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), IncomingWebhookFromJson(r.Body)}, nil
}
}
func (c *Client) PostToWebhook(id, payload string) (*Result, *AppError) {
if r, err := c.DoPost("/hooks/"+id, payload, "application/x-www-form-urlencoded"); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), nil}, nil
}
}
func (c *Client) DeleteIncomingWebhook(id string) (*Result, *AppError) {
data := make(map[string]string)
data["id"] = id
if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/incoming/delete", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) ListIncomingWebhooks() (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetTeamRoute()+"/hooks/incoming/list", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), IncomingWebhookListFromJson(r.Body)}, nil
}
}
func (c *Client) GetAllPreferences() (*Result, *AppError) {
if r, err := c.DoApiGet("/preferences/", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
preferences, _ := PreferencesFromJson(r.Body)
return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), preferences}, nil
}
}
func (c *Client) SetPreferences(preferences *Preferences) (*Result, *AppError) {
if r, err := c.DoApiPost("/preferences/save", preferences.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), preferences}, nil
}
}
func (c *Client) GetPreference(category string, name string) (*Result, *AppError) {
if r, err := c.DoApiGet("/preferences/"+category+"/"+name, "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PreferenceFromJson(r.Body)}, nil
}
}
func (c *Client) GetPreferenceCategory(category string) (*Result, *AppError) {
if r, err := c.DoApiGet("/preferences/"+category, "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
preferences, _ := PreferencesFromJson(r.Body)
return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), preferences}, nil
}
}
// DeletePreferences deletes a list of preferences owned by the current user. If successful,
// it will return status=ok. Otherwise, an error will be returned.
func (c *Client) DeletePreferences(preferences *Preferences) (bool, *AppError) {
if r, err := c.DoApiPost("/preferences/delete", preferences.ToJson()); err != nil {
return false, err
} else {
return c.CheckStatusOK(r), nil
}
}
func (c *Client) CreateOutgoingWebhook(hook *OutgoingWebhook) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/outgoing/create", hook.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), OutgoingWebhookFromJson(r.Body)}, nil
}
}
func (c *Client) UpdateOutgoingWebhook(hook *OutgoingWebhook) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/outgoing/update", hook.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), OutgoingWebhookFromJson(r.Body)}, nil
}
}
func (c *Client) DeleteOutgoingWebhook(id string) (*Result, *AppError) {
data := make(map[string]string)
data["id"] = id
if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/outgoing/delete", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) ListOutgoingWebhooks() (*Result, *AppError) {
if r, err := c.DoApiGet(c.GetTeamRoute()+"/hooks/outgoing/list", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), OutgoingWebhookListFromJson(r.Body)}, nil
}
}
func (c *Client) RegenOutgoingWebhookToken(id string) (*Result, *AppError) {
data := make(map[string]string)
data["id"] = id
if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/outgoing/regen_token", MapToJson(data)); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), OutgoingWebhookFromJson(r.Body)}, nil
}
}
func (c *Client) MockSession(sessionToken string) {
c.AuthToken = sessionToken
c.AuthType = HEADER_BEARER
}
func (c *Client) GetClientLicenceConfig(etag string) (*Result, *AppError) {
if r, err := c.DoApiGet("/license/client_config", "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
}
}
func (c *Client) GetInitialLoad() (*Result, *AppError) {
if r, err := c.DoApiGet("/users/initial_load", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), InitialLoadFromJson(r.Body)}, nil
}
}
// ListEmoji returns a list of all user-created emoji for the server.
func (c *Client) ListEmoji() ([]*Emoji, *AppError) {
if r, err := c.DoApiGet(c.GetEmojiRoute()+"/list", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return EmojiListFromJson(r.Body), nil
}
}
// CreateEmoji will save an emoji to the server if the current user has permission
// to do so. If successful, the provided emoji will be returned with its Id field
// filled in. Otherwise, an error will be returned.
func (c *Client) CreateEmoji(emoji *Emoji, image []byte, filename string) (*Emoji, *AppError) {
c.clearExtraProperties()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
if part, err := writer.CreateFormFile("image", filename); err != nil {
return nil, NewLocAppError("CreateEmoji", "model.client.create_emoji.image.app_error", nil, err.Error())
} else if _, err = io.Copy(part, bytes.NewBuffer(image)); err != nil {
return nil, NewLocAppError("CreateEmoji", "model.client.create_emoji.image.app_error", nil, err.Error())
}
if err := writer.WriteField("emoji", emoji.ToJson()); err != nil {
return nil, NewLocAppError("CreateEmoji", "model.client.create_emoji.emoji.app_error", nil, err.Error())
}
if err := writer.Close(); err != nil {
return nil, NewLocAppError("CreateEmoji", "model.client.create_emoji.writer.app_error", nil, err.Error())
}
rq, _ := http.NewRequest("POST", c.ApiUrl+c.GetEmojiRoute()+"/create", body)
rq.Header.Set("Content-Type", writer.FormDataContentType())
rq.Close = true
if len(c.AuthToken) > 0 {
rq.Header.Set(HEADER_AUTH, "BEARER "+c.AuthToken)
}
if r, err := c.HttpClient.Do(rq); err != nil {
return nil, NewLocAppError("CreateEmoji", "model.client.connecting.app_error", nil, err.Error())
} else if r.StatusCode >= 300 {
return nil, AppErrorFromJson(r.Body)
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return EmojiFromJson(r.Body), nil
}
}
// DeleteEmoji will delete an emoji from the server if the current user has permission
// to do so. If successful, it will return status=ok. Otherwise, an error will be returned.
func (c *Client) DeleteEmoji(id string) (bool, *AppError) {
data := map[string]string{"id": id}
if r, err := c.DoApiPost(c.GetEmojiRoute()+"/delete", MapToJson(data)); err != nil {
return false, err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return c.CheckStatusOK(r), nil
}
}
// GetCustomEmojiImageUrl returns the API route that can be used to get the image used by
// the given emoji.
func (c *Client) GetCustomEmojiImageUrl(id string) string {
return c.GetEmojiRoute() + "/" + id
}
// Uploads a x509 base64 Certificate or Private Key file to be used with SAML.
// data byte array is required and needs to be a Multi-Part with 'certificate' as the field name
// contentType is also required. Returns nil if succesful, otherwise returns an AppError
func (c *Client) UploadCertificateFile(data []byte, contentType string) *AppError {
url := c.ApiUrl + "/admin/add_certificate"
rq, _ := http.NewRequest("POST", url, bytes.NewReader(data))
rq.Header.Set("Content-Type", contentType)
rq.Close = true
if len(c.AuthToken) > 0 {
rq.Header.Set(HEADER_AUTH, "BEARER "+c.AuthToken)
}
if rp, err := c.HttpClient.Do(rq); err != nil {
return NewLocAppError(url, "model.client.connecting.app_error", nil, err.Error())
} else if rp.StatusCode >= 300 {
return AppErrorFromJson(rp.Body)
} else {
defer closeBody(rp)
c.fillInExtraProperties(rp)
return nil
}
}
// Removes a x509 base64 Certificate or Private Key file used with SAML.
// filename is required. Returns nil if successful, otherwise returns an AppError
func (c *Client) RemoveCertificateFile(filename string) *AppError {
if r, err := c.DoApiPost("/admin/remove_certificate", MapToJson(map[string]string{"filename": filename})); err != nil {
return err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return nil
}
}
// Checks if the x509 base64 Certificates and Private Key files used with SAML exists on the file system.
// Returns a map[string]interface{} if successful, otherwise returns an AppError. Must be System Admin authenticated.
func (c *Client) SamlCertificateStatus(filename string) (map[string]interface{}, *AppError) {
if r, err := c.DoApiGet("/admin/remove_certificate", "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return StringInterfaceFromJson(r.Body), nil
}
}
// GetWebrtcToken if Successful returns a map with a valid token, stun server and turn server with credentials to use with
// the Mattermost WebRTC service, otherwise returns an AppError. Must be authenticated user.
func (c *Client) GetWebrtcToken() (map[string]string, *AppError) {
if r, err := c.DoApiPost("/webrtc/token", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return MapFromJson(r.Body), nil
}
}
// GetFileInfosForPost returns a list of FileInfo objects for a given post id, if successful.
// Otherwise, it returns an error.
func (c *Client) GetFileInfosForPost(channelId string, postId string, etag string) ([]*FileInfo, *AppError) {
c.clearExtraProperties()
if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/get_file_infos", postId), "", etag); err != nil {
return nil, err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return FileInfosFromJson(r.Body), nil
}
}
// Saves an emoji reaction for a post in the given channel. Returns the saved reaction if successful, otherwise returns an AppError.
func (c *Client) SaveReaction(channelId string, reaction *Reaction) (*Reaction, *AppError) {
if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/reactions/save", reaction.PostId), reaction.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return ReactionFromJson(r.Body), nil
}
}
// Removes an emoji reaction for a post in the given channel. Returns nil if successful, otherwise returns an AppError.
func (c *Client) DeleteReaction(channelId string, reaction *Reaction) *AppError {
if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/reactions/delete", reaction.PostId), reaction.ToJson()); err != nil {
return err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return nil
}
}
// Lists all emoji reactions made for the given post in the given channel. Returns a list of Reactions if successful, otherwise returns an AppError.
func (c *Client) ListReactions(channelId string, postId string) ([]*Reaction, *AppError) {
if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/reactions", postId), "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return ReactionsFromJson(r.Body), nil
}
}
// Updates the user's roles in the channel by replacing them with the roles provided.
func (c *Client) UpdateChannelRoles(channelId string, userId string, roles string) (map[string]string, *ResponseMetadata) {
data := make(map[string]string)
data["new_roles"] = roles
data["user_id"] = userId
if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+"/update_member_roles", MapToJson(data)); err != nil {
metadata := ResponseMetadata{Error: err}
if r != nil {
metadata.StatusCode = r.StatusCode
}
return nil, &metadata
} else {
defer closeBody(r)
return MapFromJson(r.Body),
&ResponseMetadata{
StatusCode: r.StatusCode,
RequestId: r.Header.Get(HEADER_REQUEST_ID),
Etag: r.Header.Get(HEADER_ETAG_SERVER),
}
}
}
func (c *Client) PinPost(channelId string, postId string) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+"/posts/"+postId+"/pin", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), PostFromJson(r.Body)}, nil
}
}
func (c *Client) UnpinPost(channelId string, postId string) (*Result, *AppError) {
if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+"/posts/"+postId+"/unpin", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
return &Result{r.Header.Get(HEADER_REQUEST_ID),
r.Header.Get(HEADER_ETAG_SERVER), PostFromJson(r.Body)}, nil
}
}
| asaadmahmoodspin/platform | model/client.go | GO | agpl-3.0 | 84,229 |
require 'spec_helper'
describe Queries::SignaturesExport do
subject { Queries::SignaturesExport.new(petition_id: petition_id) }
let(:petition_id) { '1' }
it "should have generate some SQL" do
subject.sql.should start_with("SELECT")
end
context "with objects" do
let(:petition) { FactoryGirl.create(:petition) }
let(:petition_id) { petition.id }
let!(:signature) { FactoryGirl.create(:signature, petition: petition) }
before(:each) do
@result = ""
subject.as_csv_stream.each do |chunk|
@result << chunk
end
end
context "when parsed" do
before(:each) do
@parsed = CSV.parse(@result)
end
describe "header" do
let(:header) { @parsed[0] }
specify{ header.should include("email")}
end
describe "first row" do
let(:first_row) { @parsed[1] }
specify{ first_row.should include(signature.email)}
end
end
end
end
| MayOneUS/victorykit | spec/models/queries/signatures_export_spec.rb | Ruby | agpl-3.0 | 963 |
/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#include "SubItemPropertyWizardPane.hpp"
#include "ItemListPropertyHandler.hpp"
#include "SimulationItemDiscovery.hpp"
#include "SimulationItemTools.hpp"
#include "SimulationItem.hpp"
#include <QVBoxLayout>
#include <QLabel>
#include <QRadioButton>
#include <QButtonGroup>
#include <QVariant>
using namespace SimulationItemDiscovery;
////////////////////////////////////////////////////////////////////
SubItemPropertyWizardPane::SubItemPropertyWizardPane(PropertyHandlerPtr handler, QObject* target)
: PropertyWizardPane(handler, target)
{
auto hdlr = handlerCast<ItemListPropertyHandler>();
// create the layout so that we can add stuff one by one
auto layout = new QVBoxLayout;
// add the question
layout->addWidget(new QLabel("Select one of the following options for item #"
+ QString::number(selectedIndex()+1) + " in " + hdlr->title() + " list:"));
// determine the current and default item types
QByteArray currentType = itemType(hdlr->value()[selectedIndex()]);
QByteArray defaultType = hdlr->hasDefaultValue() ? hdlr->defaultItemType() : "";
// make a button group to contain the radio buttons reflecting the possible choices
auto buttonGroup = new QButtonGroup;
// add the choices
for (auto choiceType : SimulationItemTools::allowedDescendants(hdlr->baseType(),hdlr->target()))
{
auto choiceTitle = title(choiceType);
if (!choiceTitle.isEmpty()) choiceTitle.replace(0, 1, choiceTitle[0].toUpper());
if (SimulationItemDiscovery::inherits(choiceType,defaultType)) choiceTitle += " [default]";
auto choiceButton = new QRadioButton(choiceTitle);
choiceButton->setFocusPolicy(Qt::NoFocus);
buttonGroup->addButton(choiceButton);
layout->addWidget(choiceButton);
// associate the item type corresponding to this button with the button object
choiceButton->setProperty("choiceType", choiceType);
choiceButton->setToolTip(choiceType);
// if this button corresponds to the current type, select it
if (choiceType==currentType)
{
choiceButton->setChecked(true);
emit propertyValidChanged(true);
}
}
// connect the button group to ourselves
connect(buttonGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(selectTypeFor(QAbstractButton*)));
// finalize the layout and assign it to ourselves
layout->addStretch();
setLayout(layout);
}
////////////////////////////////////////////////////////////////////
int SubItemPropertyWizardPane::selectedIndex()
{
auto hdlr = handlerCast<ItemListPropertyHandler>();
return SimulationItemTools::retrieveSelectedRow(hdlr->target(), hdlr->name());
}
////////////////////////////////////////////////////////////////////
void SubItemPropertyWizardPane::selectTypeFor(QAbstractButton* button)
{
auto hdlr = handlerCast<ItemListPropertyHandler>();
// update the value if needed
auto newType = button->property("choiceType").toByteArray();
int index = selectedIndex();
if (itemType(hdlr->value()[index]) != newType)
{
hdlr->removeValueAt(index);
hdlr->insertNewItemOfType(index, newType);
emit propertyValueChanged();
}
// signal the change
emit propertyValidChanged(true);
}
////////////////////////////////////////////////////////////////////
| raesjo/SKIRTcorona | SkirtMakeUp/SubItemPropertyWizardPane.cpp | C++ | agpl-3.0 | 3,696 |
/********
* This file is part of Ext.NET.
*
* Ext.NET is free software: you can redistribute it and/or modify
* it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Ext.NET is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
* along with Ext.NET. If not, see <http://www.gnu.org/licenses/>.
*
*
* @version : 1.2.0 - Ext.NET Pro License
* @author : Ext.NET, Inc. http://www.ext.net/
* @date : 2011-09-12
* @copyright : Copyright (c) 2006-2011, Ext.NET, Inc. (http://www.ext.net/). All rights reserved.
* @license : GNU AFFERO GENERAL PUBLIC LICENSE (AGPL) 3.0.
* See license.txt and http://www.ext.net/license/.
* See AGPL License at http://www.gnu.org/licenses/agpl-3.0.txt
********/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Ext.Net
{
public partial class TreeGridBooleanColumn
{
/// <summary>
///
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[XmlIgnore]
[JsonIgnore]
public override ConfigOptionsCollection ConfigOptions
{
get
{
ConfigOptionsCollection list = base.ConfigOptions;
list.Add("xType", new ConfigOption("xType", new SerializationOptions("xtype"), null, this.XType ));
list.Add("falseText", new ConfigOption("falseText", null, "false", this.FalseText ));
list.Add("trueText", new ConfigOption("trueText", null, "true", this.TrueText ));
list.Add("undefinedText", new ConfigOption("undefinedText", null, " ", this.UndefinedText ));
return list;
}
}
}
} | daowzq/ExtNet | ext.net.community/Ext.Net/Factory/ConfigOptions/TreeGridBooleanColumnConfigOptions.cs | C# | agpl-3.0 | 2,361 |
/**
* Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of fiware-tidoop (FI-WARE project).
*
* fiware-tidoop is free software: you can redistribute it and/or modify it under the terms of the GNU Affero
* General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
* fiware-tidoop is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License along with fiware-tidoop. If not, see
* http://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License please contact with
* francisco.romerobueno at telefonica dot com
*/
package com.telefonica.iot.tidoop.apiext.utils;
import com.telefonica.iot.tidoop.apiext.hadoop.ckan.CKANInputFormat;
import com.telefonica.iot.tidoop.apiext.hadoop.ckan.CKANOutputFormat;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
*
* @author frb
*/
public final class CKANMapReduceExample extends Configured implements Tool {
/**
* Constructor. It is private since utility classes should not have a public or default constructor.
*/
private CKANMapReduceExample() {
} // CKANMapReduceTest
/**
* Mapper class. It receives a CKAN record pair (Object key, Text ckanRecord) and returns a (Text globalKey,
* IntWritable recordLength) pair about a common global key and the length of the record.
*/
public static class RecordSizeGetter extends Mapper<Object, Text, Text, IntWritable> {
private final Text globalKey = new Text("size");
private final IntWritable recordLength = new IntWritable();
@Override
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
recordLength.set(value.getLength());
context.write(globalKey, recordLength);
} // map
} // RecordSizeGetter
/**
* Reducer class. It receives a list of (Text globalKey, IntWritable length) pairs and computes the sum of all the
* lengths, producing a final (Text globalKey, IntWritable totalLength).
*/
public static class RecordSizeAdder extends Reducer<Text, IntWritable, Text, IntWritable> {
private final IntWritable totalLength = new IntWritable();
@Override
public void reduce(Text globalKey, Iterable<IntWritable> recordLengths, Context context)
throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : recordLengths) {
sum += val.get();
} // for
totalLength.set(sum);
context.write(globalKey, totalLength);
} // reduce
} // RecordSizeAdder
/**
* Main class.
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new CKANMapReduceExample(), args);
System.exit(res);
} // main
@Override
public int run(String[] args) throws Exception {
// check the number of arguments, show the usage if it is wrong
if (args.length != 7) {
showUsage();
return -1;
} // if
// get the arguments
String ckanHost = args[0];
String ckanPort = args[1];
boolean sslEnabled = args[2].equals("true");
String ckanAPIKey = args[3];
String ckanInputs = args[4];
String ckanOutput = args[5];
String splitsLength = args[6];
// create and configure a MapReduce job
Configuration conf = this.getConf();
Job job = Job.getInstance(conf, "CKAN MapReduce test");
job.setJarByClass(CKANMapReduceExample.class);
job.setMapperClass(RecordSizeGetter.class);
job.setCombinerClass(RecordSizeAdder.class);
job.setReducerClass(RecordSizeAdder.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setInputFormatClass(CKANInputFormat.class);
CKANInputFormat.setInput(job, ckanInputs);
CKANInputFormat.setEnvironment(job, ckanHost, ckanPort, sslEnabled, ckanAPIKey);
CKANInputFormat.setSplitsLength(job, splitsLength);
job.setOutputFormatClass(CKANOutputFormat.class);
CKANOutputFormat.setEnvironment(job, ckanHost, ckanPort, sslEnabled, ckanAPIKey);
CKANOutputFormat.setOutputPkg(job, ckanOutput);
// run the MapReduce job
return job.waitForCompletion(true) ? 0 : 1;
} // main
private void showUsage() {
System.out.println("Usage:");
System.out.println();
System.out.println("hadoop jar \\");
System.out.println(" target/ckan-protocol-0.1-jar-with-dependencies.jar \\");
System.out.println(" es.tid.fiware.fiwareconnectors.ckanprotocol.utils.CKANMapReduceTest \\");
System.out.println(" -libjars target/ckan-protocol-0.1-jar-with-dependencies.jar \\");
System.out.println(" <ckan host> \\");
System.out.println(" <ckan port> \\");
System.out.println(" <ssl enabled=true|false> \\");
System.out.println(" <ckan API key> \\");
System.out.println(" <comma-separated list of ckan inputs> \\");
System.out.println(" <ckan output package> \\");
System.out.println(" <splits length>");
} // showUsage
} // CKANMapReduceTest
| telefonicaid/fiware-tidoop | tidoop-hadoop-ext/src/main/java/com/telefonica/iot/tidoop/apiext/utils/CKANMapReduceExample.java | Java | agpl-3.0 | 6,139 |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Agile Business Group sagl
# (<http://www.agilebg.com>)
# @author Alex Comba <alex.comba@agilebg.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': "Stock Invoice Picking Incoterm",
'version': '0.1',
'category': 'Warehouse Management',
'description': """
This module adds the field incoterm to invoice and picking. In this way the
user can specify the incoterm directly on these documents, with no need to
refer to the incoterm of the order (which could even be missing).
The module extends 'stock_invoice_picking' so that the invoices created
from pickings will have the same incoterm set in the picking.
""",
'author': 'Agile Business Group',
'website': 'http://www.agilebg.com',
'license': 'AGPL-3',
'depends': [
'stock_invoice_picking',
],
'data': [
'account_invoice_view.xml',
'stock_view.xml',
],
'test': [
'test/invoice_picking_incoterm.yml',
],
'installable': False
}
| jbaudoux/account-invoicing | __unported__/stock_invoice_picking_incoterm/__openerp__.py | Python | agpl-3.0 | 1,830 |
package org.yamcs.parameter;
import org.yamcs.protobuf.Yamcs.Value.Type;
public class FloatValue extends Value {
final float v;
public FloatValue(float v) {
this.v = v;
}
@Override
public Type getType() {
return Type.FLOAT;
}
@Override
public float getFloatValue() {
return v;
}
@Override
public double toDouble() {
return v;
}
@Override
public int hashCode() {
return Float.hashCode(v);
}
public boolean equals(Object obj) {
return (obj instanceof FloatValue)
&& (Float.floatToIntBits(((FloatValue) obj).v) == Float.floatToIntBits(v));
}
@Override
public String toString() {
return Float.toString(v);
}
}
| fqqb/yamcs | yamcs-core/src/main/java/org/yamcs/parameter/FloatValue.java | Java | agpl-3.0 | 767 |
from django.utils.translation import ugettext as _, ugettext_lazy as _lazy
from django.core import urlresolvers
from django.http import HttpResponse, HttpResponseServerError
from flexi_auth.models import ObjectWithContext
from rest.views.blocks.base import BlockSSDataTables, ResourceBlockAction, CREATE_CSV
from consts import VIEW_CONFIDENTIAL, CONFIDENTIAL_VERBOSE_HTML, CASH
from gf.base.templatetags.accounting_tags import human_readable_account_csv,human_readable_kind, signed_ledger_entry_amount
from django.template.loader import render_to_string
import datetime, csv
import cStringIO as StringIO
#from simple_accounting.models import economic_subject, AccountingDescriptor
#from simple_accounting.models import account_type
#from simple_accounting.exceptions import MalformedTransaction
#from simple_accounting.models import AccountingProxy
#from simple_accounting.utils import register_transaction, register_simple_transaction
#from gf.base.accounting import PersonAccountingProxy
from lib.shortcuts import render_to_xml_response, render_to_context_response
#------------------------------------------------------------------------------#
# #
#------------------------------------------------------------------------------#
#OLD: ENCODING = "iso-8859-1"
class Block(BlockSSDataTables):
BLOCK_NAME = "transactions"
BLOCK_DESCRIPTION = _("Economic transactions")
BLOCK_VALID_RESOURCE_TYPES = ["gas", "supplier", "pact"]
COLUMN_INDEX_NAME_MAP = {
0: 'id',
1: 'transaction__date',
2: '',
3: '',
4: 'amount',
5: 'transaction__description',
}
#WAS 2: 'transaction__issuer',
#WAS 3: 'transaction__source',
#WAS 3: 'transaction__kind', --> FIXME: In case of translation the search does not operate correctly
def __init__(self, *args, **kw):
super(Block, self).__init__(*args, **kw)
# Default start closed. Mainly for GAS -> Accounting tab ("Conto")
self.start_open = False
def _check_permission(self, request):
if request.resource.gas:
return request.user.has_perm(
CASH, obj=ObjectWithContext(request.resource.gas)
)
else:
return True
def _get_resource_list(self, request):
#Accounting.LedgerEntry or Transactions
return request.resource.economic_movements
def get_response(self, request, resource_type, resource_id, args):
"""Check for confidential access permission and call superclass if needed"""
if not self._check_permission(request):
return render_to_xml_response(
"blocks/table_html_message.xml",
{ 'msg' : CONFIDENTIAL_VERBOSE_HTML }
)
if args == CREATE_CSV:
return self._create_csv(request)
return super(Block, self).get_response(request, resource_type, resource_id, args)
#TODO: Filter grid by
# Date From --> To
# Kind iof transctions: can be checkbox list multiselect
# Subject: Radio or multiple checkbox onto values [GAS borselino, GASMemmbers, Suppliers]
# def options_response(self, request, resource_type, resource_id):
# """Get options for transaction block.
# WARNING: call to this method doesn't pass through get_response
# so you have to reset self.request and self.resource attribute if you want
# """
# self.request = request
# self.resource = request.resource
# fields = []
# #DATE FROM
# fields.append({
# 'field_type' : 'datetime',
# 'field_label' : 'from date',
# 'field_name' : 'from',
# 'field_values' : [{ 'value' : '22/09/2012', 'selected' : ''}]
# })
# #DATE TO
# fields.append({
# 'field_type' : 'datetime',
# 'field_label' : 'to date',
# 'field_name' : 'to',
# 'field_values' : [{ 'value' : '28/09/2012', 'label' : 'labelvalue', 'selected' : 'sel'}]
# })
# ctx = {
# 'block_name' : self.description,
# 'fields': fields,
# }
# #Can use html template loader
# return render_to_xml_response('eco-options.xml', ctx)
def _get_user_actions(self, request):
user_actions = []
resource_type = request.resource.resource_type
if self._check_permission(request):
user_actions += [
ResourceBlockAction(
block_name = self.BLOCK_NAME,
resource = request.resource,
name=CREATE_CSV, verbose_name=_("Create CSV"),
popup_form=False,
method="OPENURL",
),
]
return user_actions
def _create_csv(self, request):
""" Create CSV of this block transactions
#MATTEO TOREMOVE: lascio la prima implementazione (da levare
ovviamente dall'integrazione) come monito a me stesso -->
kiss, kiss e ancora kiss !!
#NOTA: eliminare nell'integrazione tutte le righe commentate con #OLD:
"""
headers = [_(u'Id'), _(u'Data'), _(u'Account'), _(u'Kind'), _(u'Cash amount'), _(u'Description')]
records = self._get_resource_list(request)
csvfile = StringIO.StringIO()
writer = csv.writer(csvfile, delimiter=';',quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(headers)
for res in self._get_resource_list(request):
writer.writerow([res.pk,
'{0:%a %d %b %Y %H:%M}'.format(res.date),
human_readable_account_csv(res.account),
human_readable_kind(res.transaction.kind),
signed_ledger_entry_amount(res),
res.transaction.description.encode("utf-8", "ignore")
])
csv_data = csvfile.getvalue()
if not csv_data:
rv = HttpResponseServerError(_('Report not generated'))
else:
response = HttpResponse(csv_data, content_type='text/csv')
filename = "%(res)s_%(date)s.csv" % {
'res': request.resource,
'date' : '{0:%Y%m%d_%H%M}'.format(datetime.datetime.now())
}
response['Content-Disposition'] = "attachment; filename=" + filename
rv = response
return rv
| befair/gasistafelice | gasistafelice/rest/views/blocks/transactions.py | Python | agpl-3.0 | 6,479 |
require 'test_helper'
class CurrenciesHelperTest < ActionView::TestCase
end
| BCJonesey/CDB3 | test/unit/helpers/currencies_helper_test.rb | Ruby | agpl-3.0 | 77 |
<?php
/**
* Interface denoting an event is a deferred event that should be raised only at the end of the multirequest
*
* @package Core
* @subpackage events
*/
interface IKalturaMultiDeferredEvent
{
/**
* @param array $partnerCriteriaParams
*/
public function setPartnerCriteriaParams(array $partnerCriteriaParams);
} | kaltura/server | alpha/apps/kaltura/lib/events/interfaces/IKalturaMultiDeferredEvent.php | PHP | agpl-3.0 | 330 |
package org.tasgoon.coherence.client;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.io.FileUtils;
import org.tasgoon.coherence.common.Library;
import org.tasgoon.coherence.ziputils.ZipUtility;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
public class CohereUndoer {
//public final Logger logger = LogManager.getLogger("Coherence");
public String pid, ip, minecraftCmd;
public boolean crashed = false;
public static void main(String[] args) throws IOException, InterruptedException {
OptionParser parser = new OptionParser("i:p:c::");
/*OptionSpec<String> ip = parser.accepts("ip", "The previous IP Minecraft was connected to").withRequiredArg();
OptionSpec<String> pid = parser.accepts("pid", "PID of the minecraft process").withRequiredArg();
OptionSpec<String> cmd = parser.accepts("cmd", "The minecraft command, for crash recovery").withOptionalArg();*/
new CohereUndoer(parser.parse(args));
}
public CohereUndoer(OptionSet options) throws IOException, InterruptedException {
System.out.println("Starting coherence undoer");
pid = (String) options.valueOf("p");
ip = (String) options.valueOf("i");
if (options.has("c")) {
crashed = true;
minecraftCmd = (String) options.valueOf("c");
}
System.out.println("Using command: " + getCommand());
System.out.println("Starting process kill detector");
waitForProcessEnd();
undo();
}
public String getCommand() {
String command;
String os = System.getProperty("os.name").toLowerCase();
if (os.indexOf("win") >= 0)
command = System.getenv("windir") + "\\system32\\" + "tasklist.exe /FI \"PID eq %s\"";
else
command = "ps -p %s";
return String.format(command, pid);
}
public void waitForProcessEnd() throws IOException, InterruptedException {
boolean detected = true;
String line;
while (detected) {
detected = false;
Process process = Runtime.getRuntime().exec(getCommand());
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = input.readLine()) != null) {
if (line.contains(pid))
detected = true;
}
}
}
public void undo() {
System.out.println("Moving files back.");
File modsDir = new File("mods");
File originalModsDir = Library.getFile("coherence", "localhost", "mods");
/*//Because the reversal script is running from a file in the mods directory, I can't just remove the file.
//So, I have to iterate through the folder and remove all the files save for Coherence.
for (File file : cohereModsDir.listFiles())
FileUtils.deleteQuietly(file);*/
FileUtils.deleteQuietly(modsDir);
for (File file : originalModsDir.listFiles()) {
try {
FileUtils.moveToDirectory(file, modsDir, false);
} catch (IOException e) {
System.err.println("Could not move file " + file.getAbsolutePath() + " back.");
e.printStackTrace();
}
}
File config = new File("config");
File customConfig = Library.getFile("coherence", ip, "customConfig.zip");
System.out.println("Saving current configs to " + customConfig.getAbsolutePath());
ZipUtility.compressFolder(config, customConfig);
System.out.println("Deleting configs from config folder");
try {
FileUtils.forceDelete(config);
} catch (IOException e) {
System.err.println("Could not delete synchronized config files.");
e.printStackTrace();
}
System.out.println("Moving old configs back to main config folder");
new File("oldConfig").renameTo(config);
FileUtils.deleteQuietly(new File("coherence", "localhost")); //Contains mods that were just moved back
if (crashed)
startMC();
}
public void startMC() {
try {
Runtime.getRuntime().exec(minecraftCmd);
} catch (IOException e) {}
}
}
| Kagiu/Coherence | src/main/java/org/tasgoon/coherence/client/CohereUndoer.java | Java | agpl-3.0 | 3,832 |
(function () {
var ns = $.namespace('pskl.service');
ns.SelectedColorsService = function () {
this.reset();
};
ns.SelectedColorsService.prototype.init = function () {
$.subscribe(Events.PRIMARY_COLOR_SELECTED, this.onPrimaryColorUpdate_.bind(this));
$.subscribe(Events.SECONDARY_COLOR_SELECTED, this.onSecondaryColorUpdate_.bind(this));
};
ns.SelectedColorsService.prototype.getPrimaryColor = function () {
return this.primaryColor_;
};
ns.SelectedColorsService.prototype.getSecondaryColor = function () {
return this.secondaryColor_;
};
ns.SelectedColorsService.prototype.reset = function () {
this.primaryColor_ = Constants.DEFAULT_PEN_COLOR;
this.secondaryColor_ = Constants.TRANSPARENT_COLOR;
};
ns.SelectedColorsService.prototype.onPrimaryColorUpdate_ = function (evt, color) {
this.primaryColor_ = color;
};
ns.SelectedColorsService.prototype.onSecondaryColorUpdate_ = function (evt, color) {
this.secondaryColor_ = color;
};
})();
| RichardMarks/piskel | src/js/service/SelectedColorsService.js | JavaScript | agpl-3.0 | 1,011 |
<?php
return [
'accessories' => 'Accessories',
'activated' => 'Aktivoitu',
'accessory' => 'Accessory',
'accessory_report' => 'Accessory Report',
'action' => 'Toiminto',
'activity_report' => 'Activity Report',
'address' => 'Osoite',
'admin' => 'Ylläpitäjä',
'add_seats' => 'Added seats',
'all_assets' => 'Kaikki Laitteet',
'all' => 'Kaikki',
'archived' => 'Arkistoitu',
'asset_models' => 'Laitemallit',
'asset' => 'Laite',
'asset_report' => 'Laiteraportti',
'asset_tag' => 'Laitetunnus',
'assets_available' => 'laitetta vapaana',
'assets' => 'Laitteet',
'avatar_delete' => 'Poista käyttäjäkuva',
'avatar_upload' => 'Lähetä Käyttäjäkuva',
'back' => 'Edellinen',
'bad_data' => 'Nothing found. Maybe bad data?',
'bulk_checkout' => 'Bulk Checkout',
'cancel' => 'Peruuta',
'categories' => 'Kategoriat',
'category' => 'Kategoria',
'changeemail' => 'Muuta Email-osoite',
'changepassword' => 'Muuta Salasana',
'checkin' => 'Palauta',
'checkin_from' => 'Checkin from',
'checkout' => 'Luovuta',
'city' => 'Kaupunki',
'companies' => 'Yritykset',
'company' => 'Yritys',
'component' => 'Komponentti',
'components' => 'Komponentit',
'consumable' => 'Consumable',
'consumables' => 'Consumables',
'country' => 'Maa',
'create' => 'Luo Uusi',
'created' => 'Item Created',
'created_asset' => 'laite luotu',
'created_at' => 'Luontiaika',
'currency' => '€', // this is deprecated
'current' => 'Käytössä Olevat',
'custom_report' => 'Muokattu Laiteraportti',
'dashboard' => 'Hallintasivu',
'date' => 'Päivä',
'debug_warning' => 'Warning!',
'debug_warning_text' => 'This application is running in production mode with debugging enabled. This can expose sensitive data if your application is accessible to the outside world. Disable debug mode by setting the <code>APP_DEBUG</code> value in your <code>.env</code> file to <code>false</code>.',
'delete' => 'Poista',
'deleted' => 'Poistettu',
'delete_seats' => 'Deleted Seats',
'deployed' => 'Käyttöönotettu',
'depreciation_report' => 'Poistoraportti',
'download' => 'Lataa',
'depreciation' => 'Poistoluokka',
'editprofile' => 'Muokkaa Profiilia',
'eol' => 'Elinikä',
'email_domain' => 'Email Domain',
'email_format' => 'Email Format',
'email_domain_help' => 'This is used to generate email addresses when importing',
'filastname_format' => 'First Initial Last Name (jsmith@example.com)',
'firstname_lastname_format' => 'First Name Last Name (jane.smith@example.com)',
'first' => 'Ensimmäinen',
'first_name' => 'Etunimi',
'first_name_format' => 'First Name (jane@example.com)',
'file_name' => 'Tiedosto',
'file_uploads' => 'Tiedostolataus',
'generate' => 'Luo',
'groups' => 'Ryhmät',
'gravatar_email' => 'Gravatarin Email-osoite',
'history' => 'History',
'history_for' => 'Laitehistoria käyttäjälle',
'id' => 'Tunnus',
'image_delete' => 'Poista Kuva',
'image_upload' => 'Lähetä Kuva',
'import' => 'Tuo tiedot',
'import-history' => 'Import History',
'asset_maintenance' => 'Asset Maintenance',
'asset_maintenance_report' => 'Asset Maintenance Report',
'asset_maintenances' => 'Asset Maintenances',
'item' => 'Item',
'insufficient_permissions' => 'Insufficient permissions!',
'language' => 'Kieli',
'last' => 'Last',
'last_name' => 'Sukunimi',
'license' => 'Lisenssi',
'license_report' => 'Lisenssiraportti',
'licenses_available' => 'Vapaana olevat lisenssit',
'licenses' => 'Lisenssit',
'list_all' => 'Listaa Kaikki',
'loading' => 'Ladataan',
'lock_passwords' => 'This field cannot be edited in this installation.',
'feature_disabled' => 'This feature has been disabled for the demo installation.',
'location' => 'Sijainti',
'locations' => 'Sijainnit',
'logout' => 'Kirjaudu Ulos',
'lookup_by_tag' => 'Lookup by Asset Tag',
'manufacturer' => 'Valmistaja',
'manufacturers' => 'Valmistajat',
'markdown' => 'This field allows <a href="https://help.github.com/articles/github-flavored-markdown/">Github flavored markdown</a>.',
'min_amt' => 'Min. QTY',
'min_amt_help' => 'Minimum number of items that should be available before an alert gets triggered.',
'model_no' => 'Mallinumero',
'months' => 'Kuukautta',
'moreinfo' => 'Lisätiedot',
'name' => 'Nimi',
'next' => 'Seuraava',
'new' => 'new!',
'no_depreciation' => 'Ei poistoluokkaa',
'no_results' => 'Ei tuloksia.',
'no' => 'Ei',
'notes' => 'Muistiinpanot',
'order_number' => 'Order Number',
'page_menu' => 'Showing _MENU_ items',
'pagination_info' => 'Showing _START_ to _END_ of _TOTAL_ items',
'pending' => 'Odottaa',
'people' => 'Ihmiset',
'per_page' => 'Tuloksia Per Sivu',
'previous' => 'Edellinen',
'processing' => 'Käsitellään',
'profile' => 'Profiilisi',
'purchase_cost' => 'Purchase Cost',
'purchase_date' => 'Purchase Date',
'qty' => 'KPL',
'quantity' => 'Määrä',
'ready_to_deploy' => 'Käyttöönotettavissa',
'recent_activity' => 'Viimeisin toiminta',
'remove_company' => 'Remove Company Association',
'reports' => 'Raportit',
'requested' => 'Requested',
'request_canceled' => 'Request Canceled',
'save' => 'Tallenna',
'select' => 'Valitse',
'search' => 'Etsi',
'select_category' => 'Select a Category',
'select_depreciation' => 'Select a Depreciation Type',
'select_location' => 'Valitse sijainti',
'select_manufacturer' => 'Valitse valmistaja',
'select_model' => 'Select a Model',
'select_supplier' => 'Valitse toimittaja',
'select_user' => 'Valitse käyttäjä',
'select_date' => 'Select Date',
'select_statuslabel' => 'Select Status',
'select_company' => 'Select Company',
'select_asset' => 'Select Asset',
'settings' => 'Asetukset',
'sign_in' => 'Kirjaudu sisään',
'signature' => 'Signature',
'some_features_disabled' => 'DEMO MODE: Some features are disabled for this installation.',
'site_name' => 'Sivuston Nimi',
'state' => 'Lääni',
'status_labels' => 'Tilamerkinnät',
'status' => 'Tila',
'supplier' => 'Supplier',
'suppliers' => 'Toimittajat',
'submit' => 'Submit',
'total_assets' => 'laitteita yhteensä',
'total_licenses' => 'lisenssejä yhteensä',
'total_accessories' => 'total accessories',
'total_consumables' => 'total consumables',
'type' => 'Tyyppi',
'undeployable' => 'Ei-käyttöönotettavissa',
'unknown_admin' => 'Tuntematon Ylläpitäjä',
'username_format' => 'Username Format',
'update' => 'Päivitä',
'uploaded' => 'Ladattu',
'user' => 'Käyttäjä',
'accepted' => 'hyväksytty',
'declined' => 'hylkää',
'unaccepted_asset_report' => 'Unaccepted Assets',
'users' => 'Käyttäjät',
'viewassets' => 'Näytä Käyttöönotetut Laitteet',
'website' => 'Verkkosivu',
'welcome' => 'Tervetuloa, :name',
'years' => 'vuotta',
'yes' => 'Kyllä',
'zip' => 'Postinumero',
'noimage' => 'No image uploaded or image not found.',
'token_expired' => 'Istuntosi on vanhentunut. Ole hyvä ja kirjaudu uudelleen.',
];
| Murima/asset-mgmt | resources/lang/fi/general.php | PHP | agpl-3.0 | 8,191 |
// Copyright 2016 The Mangos Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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.
// survey implements a survey example. server is a surveyor listening
// socket, and clients are dialing respondent sockets.
//
// To use:
//
// $ go build .
// $ url=tcp://127.0.0.1:40899
// $ ./survey server $url server & server=$!
// $ ./survey client $url client0 & client0=$!
// $ ./survey client $url client1 & client1=$!
// $ ./survey client $url client2 & client2=$!
// $ sleep 5
// $ kill $server $client0 $client1 $client2
//
package main
import (
"fmt"
"github.com/go-mangos/mangos"
"github.com/go-mangos/mangos/protocol/respondent"
"github.com/go-mangos/mangos/protocol/surveyor"
"github.com/go-mangos/mangos/transport/ipc"
"github.com/go-mangos/mangos/transport/tcp"
"os"
"time"
)
func die(format string, v ...interface{}) {
fmt.Fprintln(os.Stderr, fmt.Sprintf(format, v...))
os.Exit(1)
}
func date() string {
return time.Now().Format(time.ANSIC)
}
func server(url string) {
var sock mangos.Socket
var err error
var msg []byte
if sock, err = surveyor.NewSocket(); err != nil {
die("can't get new surveyor socket: %s", err)
}
sock.AddTransport(ipc.NewTransport())
sock.AddTransport(tcp.NewTransport())
if err = sock.Listen(url); err != nil {
die("can't listen on surveyor socket: %s", err.Error())
}
err = sock.SetOption(mangos.OptionSurveyTime, time.Second/2)
if err != nil {
die("SetOption(): %s", err.Error())
}
for {
time.Sleep(time.Second)
fmt.Println("SERVER: SENDING DATE SURVEY REQUEST")
if err = sock.Send([]byte("DATE")); err != nil {
die("Failed sending survey: %s", err.Error())
}
for {
if msg, err = sock.Recv(); err != nil {
break
}
fmt.Printf("SERVER: RECEIVED \"%s\" SURVEY RESPONSE\n",
string(msg))
}
fmt.Println("SERVER: SURVEY OVER")
}
}
func client(url string, name string) {
var sock mangos.Socket
var err error
var msg []byte
if sock, err = respondent.NewSocket(); err != nil {
die("can't get new respondent socket: %s", err.Error())
}
sock.AddTransport(ipc.NewTransport())
sock.AddTransport(tcp.NewTransport())
if err = sock.Dial(url); err != nil {
die("can't dial on respondent socket: %s", err.Error())
}
for {
if msg, err = sock.Recv(); err != nil {
die("Cannot recv: %s", err.Error())
}
fmt.Printf("CLIENT(%s): RECEIVED \"%s\" SURVEY REQUEST\n",
name, string(msg))
d := date()
fmt.Printf("CLIENT(%s): SENDING DATE SURVEY RESPONSE\n", name)
if err = sock.Send([]byte(d)); err != nil {
die("Cannot send: %s", err.Error())
}
}
}
func main() {
if len(os.Args) > 2 && os.Args[1] == "server" {
server(os.Args[2])
os.Exit(0)
}
if len(os.Args) > 3 && os.Args[1] == "client" {
client(os.Args[2], os.Args[3])
os.Exit(0)
}
fmt.Fprintf(os.Stderr, "Usage: survey server|client <URL> <ARG>\n")
os.Exit(1)
}
| synapse-garden/sg-proto | vendor/github.com/go-mangos/mangos/examples/survey/survey.go | GO | agpl-3.0 | 3,364 |
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
from copy import deepcopy
from .oml_replicate import metacl_oml_replicate
meta_test_test_kwargs = dict(
# Setup the meta-testing phase and allow it to run.
run_meta_test=True,
# This resets the fast params (in this case the output layer of the OMLNetwork)
reset_fast_params=True,
# Results reported over 15 sampled.
meta_test_sample_size=15,
# Run meta-testing over 10 and 50 classes.
num_meta_test_classes=[10, 50],
# The best lr was chosen among the following; done separately for each number of
# classes trained on.
lr_sweep_range=[0.03, 0.01, 0.003, 0.001, 0.0003, 0.0001, 0.00003, 0.00001],
# Run through meta-test testing 5 images at a time. No training occurs here.
test_test_batch_size=60,
)
# Run OML for 2000 steps to ensure meta=testing accuracy hasn't regressed.
# |--------------------------------------------------------------|
# | Num Classes | Meta-test test | Meta-test train | LR |
# |--------------:|:-----------------|:------------------|------:|
# | 10 | 0.84 ± 0.06 | 0.94 ± 0.05 | 0.003 |
# | 50 | 0.75 ± 0.03 | 0.95 ± 0.01 | 0.001 |
# |--------------------------------------------------------------|
#
oml_regression_test = deepcopy(metacl_oml_replicate)
oml_regression_test.update(
# The number of outer (i.e. slow) steps.
epochs=2000,
# Log results to wandb.
wandb_args=dict(
name="oml_regression_test",
project="metacl",
),
# Meta-testing specific arguments.
**deepcopy(meta_test_test_kwargs),
)
# This is meant as a quick run to ensure all functionality is fully working.
# |---------------------------------------------------------------|
# | Num Classes | Meta-test test | Meta-test train | LR |
# |--------------:|:-----------------|:------------------|-------:|
# | 10 | 0.51 ± 0.03 | 0.81 ± 0.01 | 0.001 |
# |---------------------------------------------------------------|
#
oml_regression_test_50_epochs = deepcopy(oml_regression_test)
oml_regression_test_50_epochs.update(
# The number of outer (i.e. slow) steps.
epochs=50,
# Average over 10 meta-test runs.
num_meta_testing_runs=3,
num_meta_test_classes=[10],
num_lr_search_runs=1,
lr_sweep_range=[0.001],
# Log results to wandb.
wandb_args=dict(
name="oml_regression_test_50_epochs",
project="metacl",
),
)
# ------------
# All configs.
# ------------
CONFIGS = dict(
oml_regression_test=oml_regression_test,
oml_regression_test_50_epochs=oml_regression_test_50_epochs,
)
| mrcslws/nupic.research | projects/meta_cl/experiments/oml_regression_test.py | Python | agpl-3.0 | 3,610 |
// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package stateconfigwatcher_test
import (
"sync"
"time"
"github.com/juju/names/v4"
"github.com/juju/testing"
jc "github.com/juju/testing/checkers"
"github.com/juju/utils/v2/voyeur"
"github.com/juju/worker/v2"
"github.com/juju/worker/v2/dependency"
dt "github.com/juju/worker/v2/dependency/testing"
gc "gopkg.in/check.v1"
coreagent "github.com/juju/juju/agent"
"github.com/juju/juju/controller"
coretesting "github.com/juju/juju/testing"
"github.com/juju/juju/worker/stateconfigwatcher"
)
type ManifoldSuite struct {
testing.IsolationSuite
agent *mockAgent
goodContext dependency.Context
agentConfigChanged *voyeur.Value
manifold dependency.Manifold
worker worker.Worker
}
var _ = gc.Suite(&ManifoldSuite{})
func (s *ManifoldSuite) SetUpTest(c *gc.C) {
s.IsolationSuite.SetUpTest(c)
s.agent = new(mockAgent)
s.agent.conf.setStateServingInfo(true)
s.agent.conf.tag = names.NewMachineTag("99")
s.goodContext = dt.StubContext(nil, map[string]interface{}{
"agent": s.agent,
})
s.agentConfigChanged = voyeur.NewValue(0)
s.manifold = stateconfigwatcher.Manifold(stateconfigwatcher.ManifoldConfig{
AgentName: "agent",
AgentConfigChanged: s.agentConfigChanged,
})
}
func (s *ManifoldSuite) TestInputs(c *gc.C) {
c.Assert(s.manifold.Inputs, jc.SameContents, []string{"agent"})
}
func (s *ManifoldSuite) TestNoAgent(c *gc.C) {
context := dt.StubContext(nil, map[string]interface{}{
"agent": dependency.ErrMissing,
})
_, err := s.manifold.Start(context)
c.Assert(err, gc.Equals, dependency.ErrMissing)
}
func (s *ManifoldSuite) TestNilAgentConfigChanged(c *gc.C) {
manifold := stateconfigwatcher.Manifold(stateconfigwatcher.ManifoldConfig{
AgentName: "agent",
})
_, err := manifold.Start(s.goodContext)
c.Assert(err, gc.ErrorMatches, "nil AgentConfigChanged .+")
}
func (s *ManifoldSuite) TestNotMachineAgent(c *gc.C) {
s.agent.conf.tag = names.NewUnitTag("foo/0")
_, err := s.manifold.Start(s.goodContext)
c.Assert(err, gc.ErrorMatches, "manifold can only be used with a machine or controller agent")
}
func (s *ManifoldSuite) TestStart(c *gc.C) {
w, err := s.manifold.Start(s.goodContext)
c.Assert(err, jc.ErrorIsNil)
checkStop(c, w)
}
func (s *ManifoldSuite) TestOutputBadWorker(c *gc.C) {
var out bool
err := s.manifold.Output(dummyWorker{}, &out)
c.Check(err, gc.ErrorMatches, `in should be a \*stateconfigwatcher.stateConfigWatcher; .+`)
}
func (s *ManifoldSuite) TestOutputWrongType(c *gc.C) {
w, err := s.manifold.Start(s.goodContext)
c.Assert(err, jc.ErrorIsNil)
defer checkStop(c, w)
var out int
err = s.manifold.Output(w, &out)
c.Check(err, gc.ErrorMatches, `out should be \*bool; got .+`)
}
func (s *ManifoldSuite) TestOutputSuccessNotStateServer(c *gc.C) {
s.agent.conf.setStateServingInfo(false)
w, err := s.manifold.Start(s.goodContext)
c.Assert(err, jc.ErrorIsNil)
defer checkStop(c, w)
var out bool
err = s.manifold.Output(w, &out)
c.Check(err, jc.ErrorIsNil)
c.Check(out, jc.IsFalse)
}
func (s *ManifoldSuite) TestOutputSuccessStateServer(c *gc.C) {
s.agent.conf.setStateServingInfo(true)
w, err := s.manifold.Start(s.goodContext)
c.Assert(err, jc.ErrorIsNil)
defer checkStop(c, w)
var out bool
err = s.manifold.Output(w, &out)
c.Check(err, jc.ErrorIsNil)
c.Check(out, jc.IsTrue)
}
func (s *ManifoldSuite) TestBounceOnChange(c *gc.C) {
s.agent.conf.setStateServingInfo(false)
w, err := s.manifold.Start(s.goodContext)
c.Assert(err, jc.ErrorIsNil)
checkNotExiting(c, w)
checkOutput := func(expected bool) {
var out bool
err = s.manifold.Output(w, &out)
c.Assert(err, jc.ErrorIsNil)
c.Check(out, gc.Equals, expected)
}
// Not a state server yet, initial output should be False.
checkOutput(false)
// Changing the config without changing the state server status -
// worker should keep running and output should remain false.
s.agentConfigChanged.Set(0)
checkNotExiting(c, w)
checkOutput(false)
// Now change the config to include state serving info, worker
// should bounce.
s.agent.conf.setStateServingInfo(true)
s.agentConfigChanged.Set(0)
checkExitsWithError(c, w, dependency.ErrBounce)
// Restart the worker, the output should now be true.
w, err = s.manifold.Start(s.goodContext)
c.Assert(err, jc.ErrorIsNil)
checkNotExiting(c, w)
checkOutput(true)
// Changing the config again without changing the state serving
// info shouldn't cause the agent to exit.
s.agentConfigChanged.Set(0)
checkNotExiting(c, w)
checkOutput(true)
// Now remove the state serving info, the agent should bounce.
s.agent.conf.setStateServingInfo(false)
s.agentConfigChanged.Set(0)
checkExitsWithError(c, w, dependency.ErrBounce)
}
func (s *ManifoldSuite) TestClosedVoyeur(c *gc.C) {
w, err := s.manifold.Start(s.goodContext)
c.Assert(err, jc.ErrorIsNil)
checkNotExiting(c, w)
s.agentConfigChanged.Close()
c.Check(waitForExit(c, w), gc.ErrorMatches, "config changed value closed")
}
func checkStop(c *gc.C, w worker.Worker) {
err := worker.Stop(w)
c.Check(err, jc.ErrorIsNil)
}
func checkNotExiting(c *gc.C, w worker.Worker) {
exited := make(chan bool)
go func() {
w.Wait()
close(exited)
}()
select {
case <-exited:
c.Fatal("worker exited unexpectedly")
case <-time.After(coretesting.ShortWait):
// Worker didn't exit (good)
}
}
func checkExitsWithError(c *gc.C, w worker.Worker, expectedErr error) {
c.Check(waitForExit(c, w), gc.Equals, expectedErr)
}
func waitForExit(c *gc.C, w worker.Worker) error {
errCh := make(chan error)
go func() {
errCh <- w.Wait()
}()
select {
case err := <-errCh:
return err
case <-time.After(coretesting.LongWait):
c.Fatal("timed out waiting for worker to exit")
}
panic("can't get here")
}
type mockAgent struct {
coreagent.Agent
conf mockConfig
}
func (ma *mockAgent) CurrentConfig() coreagent.Config {
return &ma.conf
}
type mockConfig struct {
coreagent.ConfigSetter
tag names.Tag
mu sync.Mutex
ssInfoIsSet bool
}
func (mc *mockConfig) Tag() names.Tag {
return mc.tag
}
func (mc *mockConfig) setStateServingInfo(isSet bool) {
mc.mu.Lock()
defer mc.mu.Unlock()
mc.ssInfoIsSet = isSet
}
func (mc *mockConfig) StateServingInfo() (controller.StateServingInfo, bool) {
mc.mu.Lock()
defer mc.mu.Unlock()
return controller.StateServingInfo{}, mc.ssInfoIsSet
}
type dummyWorker struct {
worker.Worker
}
| freyes/juju | worker/stateconfigwatcher/manifold_test.go | GO | agpl-3.0 | 6,489 |
class Admin::PetitionsController < ApplicationController
before_filter :require_admin
def index
params[:time_span] ||= 'month'
respond_to do |format|
format.html {}
format.json { render json: PetitionsDatatable.new(view_context, PetitionReportRepository.new) }
end
end
end
| ChrisAntaki/victorykit | app/controllers/admin/petitions_controller.rb | Ruby | agpl-3.0 | 304 |
<?php
/**
* Skeleton subclass for representing a row from the 'audit_trail_config' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package plugins.audit
* @subpackage model
*/
class AuditTrailConfig extends BaseAuditTrailConfig {
public function actionEnabled($action)
{
$actions = explode(',', $this->getActions());
return in_array($action, $actions);
}
} // AuditTrailConfig
| jessp01/server | plugins/audit/lib/model/AuditTrailConfig.php | PHP | agpl-3.0 | 560 |
/*
* Async_MediaConnectionListener.java Version-1.4, 2002/11/22 09:26:10 -0800 (Fri)
* ECTF S.410-R2 Source code distribution.
*
* Copyright (c) 2002, Enterprise Computer Telephony Forum (ECTF),
* All Rights Reserved.
*
* Use and redistribution of this file is subject to a License.
* For terms and conditions see: javax/telephony/media/LICENSE.HTML
*
* In short, you can use this source code if you keep and display
* the ECTF Copyright and the License conditions. The code is supplied
* "AS IS" and ECTF disclaims all warranties and liability.
*/
package javax.telephony.media.connection.async;
import javax.telephony.media.connection.*;
import javax.telephony.media.async.*;
import javax.telephony.media.*;
/** Transaction completion Listener for connect() and related methods.
*
* @author Jeff Peck
* @since JTAPI-1.4
*/
public
interface Async_MediaConnectionListener extends MediaListener {
/**
* Connect complete.
* <tt>event.getEventID()</tt> is one of the connection type Symbols:
* <br>{<tt>ev_Bridge</tt>, <tt>ev_Join</tt>, <tt>ev_Loopback</tt>}.
* <p>
* <tt>event.getToken()</tt> identifies the connection:
* <ul><li>
* the other Group,
* </li><li>
* connection type,
* </li><li>
* dataFlow,
* </li><li>
* maxDataFlow.
* </li></ul>
*
* @param event the MediaConnectionEvent that is done.
*/
void onConnectDone( MediaConnectionEvent event );
/**
* Disconnect complete.
* event.getEventID() = <tt>ev_Disconnect</tt>.
* <p>
* The event.getToken() identifies the connection and Group
* which has been disconnected.
* Token.dataFlow and Token.maxDataFlow are <tt>null</tt>.
*
* <p>
* <tt>event.getEventID() = connType = ev_Disconnect</tt>.
*
* @param event the MediaConnectionEvent that is done.
*/
void onDisconnectDone( MediaConnectionEvent event );
/**
* SetDataFlow complete.
* event.getEventID() = <tt>ev_Disconnect</tt>.
* <p>
* The event.getToken() identifies the connection and Group
* which has been disconnected.
* Token.dataFlow and Token.maxDataFlow are <tt>null</tt>.
*
* <p>
* <tt>event.getEventID() = connType = ev_Disconnect</tt>.
*
* @param event the MediaConnectionEvent that is done.
*/
void onSetDataFlowDone( MediaConnectionEvent event );
}
| openss7/openss7 | src/java/javax/telephony/media/connection/async/Async_MediaConnectionListener.java | Java | agpl-3.0 | 2,435 |
// Copyright 2014 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum 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.
//
// The go-ethereum 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// Package miner implements Ethereum block creation and mining.
package miner
import (
"errors"
"math/big"
"sync/atomic"
"github.com/ethereumproject/go-ethereum/common"
"github.com/ethereumproject/go-ethereum/core"
"github.com/ethereumproject/go-ethereum/core/state"
"github.com/ethereumproject/go-ethereum/core/types"
"github.com/ethereumproject/go-ethereum/eth/downloader"
"github.com/ethereumproject/go-ethereum/event"
"github.com/ethereumproject/go-ethereum/logger"
"github.com/ethereumproject/go-ethereum/logger/glog"
"github.com/ethereumproject/go-ethereum/pow"
)
// HeaderExtra is a freeform description.
var HeaderExtra []byte
type Miner struct {
mux *event.TypeMux
worker *worker
MinAcceptedGasPrice *big.Int
threads int
coinbase common.Address
mining int32
eth core.Backend
pow pow.PoW
canStart int32 // can start indicates whether we can start the mining operation
shouldStart int32 // should start indicates whether we should start after sync
}
func New(eth core.Backend, config *core.ChainConfig, mux *event.TypeMux, pow pow.PoW) *Miner {
miner := &Miner{eth: eth, mux: mux, pow: pow, worker: newWorker(config, common.Address{}, eth), canStart: 1}
go miner.update()
return miner
}
// update keeps track of the downloader events. Please be aware that this is a one shot type of update loop.
// It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and
// the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks
// and halt your mining operation for as long as the DOS continues.
func (self *Miner) update() {
events := self.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{})
out:
for ev := range events.Chan() {
switch ev.Data.(type) {
case downloader.StartEvent:
atomic.StoreInt32(&self.canStart, 0)
if self.Mining() {
self.Stop()
atomic.StoreInt32(&self.shouldStart, 1)
glog.V(logger.Info).Infoln("Mining operation aborted due to sync operation")
}
case downloader.DoneEvent, downloader.FailedEvent:
shouldStart := atomic.LoadInt32(&self.shouldStart) == 1
atomic.StoreInt32(&self.canStart, 1)
atomic.StoreInt32(&self.shouldStart, 0)
if shouldStart {
self.Start(self.coinbase, self.threads)
}
// unsubscribe. we're only interested in this event once
events.Unsubscribe()
// stop immediately and ignore all further pending events
break out
}
}
}
func (m *Miner) SetGasPrice(price *big.Int) error {
if price == nil {
return nil
}
if m.MinAcceptedGasPrice != nil && price.Cmp(m.MinAcceptedGasPrice) == -1 {
priceTooLowError := errors.New("Gas price lower than minimum allowed.")
return priceTooLowError
}
m.worker.setGasPrice(price)
return nil
}
func (self *Miner) Start(coinbase common.Address, threads int) {
atomic.StoreInt32(&self.shouldStart, 1)
self.threads = threads
self.worker.coinbase = coinbase
self.coinbase = coinbase
if atomic.LoadInt32(&self.canStart) == 0 {
glog.V(logger.Info).Infoln("Can not start mining operation due to network sync (starts when finished)")
return
}
atomic.StoreInt32(&self.mining, 1)
for i := 0; i < threads; i++ {
self.worker.register(NewCpuAgent(i, self.pow))
}
mlogMinerStart.AssignDetails(
coinbase.Hex(),
threads,
).Send(mlogMiner)
glog.V(logger.Info).Infof("Starting mining operation (CPU=%d TOT=%d)\n", threads, len(self.worker.agents))
self.worker.start()
self.worker.commitNewWork()
}
func (self *Miner) Stop() {
self.worker.stop()
atomic.StoreInt32(&self.mining, 0)
atomic.StoreInt32(&self.shouldStart, 0)
if logger.MlogEnabled() {
mlogMinerStop.AssignDetails(
self.coinbase.Hex(),
self.threads,
).Send(mlogMiner)
}
}
func (self *Miner) Register(agent Agent) {
if self.Mining() {
agent.Start()
}
self.worker.register(agent)
}
func (self *Miner) Unregister(agent Agent) {
self.worker.unregister(agent)
}
func (self *Miner) Mining() bool {
return atomic.LoadInt32(&self.mining) > 0
}
func (self *Miner) HashRate() (tot int64) {
tot += self.pow.GetHashrate()
// do we care this might race? is it worth we're rewriting some
// aspects of the worker/locking up agents so we can get an accurate
// hashrate?
for agent := range self.worker.agents {
tot += agent.GetHashRate()
}
return
}
// Pending returns the currently pending block and associated state.
func (self *Miner) Pending() (*types.Block, *state.StateDB) {
return self.worker.pending()
}
func (self *Miner) SetEtherbase(addr common.Address) {
self.coinbase = addr
self.worker.setEtherbase(addr)
}
| adrianbrink/tendereum | vendor/github.com/ethereumproject/go-ethereum/miner/miner.go | GO | agpl-3.0 | 5,441 |