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 |
|---|---|---|---|---|---|
(function( window, $, undefined ) {
// http://www.netcu.de/jquery-touchwipe-iphone-ipad-library
$.fn.touchwipe = function(settings) {
var config = {
min_move_x: 20,
min_move_y: 20,
wipeLeft: function() { },
wipeRight: function() { },
wipeUp: function() { },
wipeDown: function() { },
preventDefaultEvents: true
};
if (settings) $.extend(config, settings);
this.each(function() {
var startX;
var startY;
var isMoving = false;
function cancelTouch() {
this.removeEventListener('touchmove', onTouchMove);
startX = null;
isMoving = false;
}
function onTouchMove(e) {
if(config.preventDefaultEvents) {
e.preventDefault();
}
if(isMoving) {
var x = e.touches[0].pageX;
var y = e.touches[0].pageY;
var dx = startX - x;
var dy = startY - y;
if(Math.abs(dx) >= config.min_move_x) {
cancelTouch();
if(dx > 0) {
config.wipeLeft();
}
else {
config.wipeRight();
}
}
else if(Math.abs(dy) >= config.min_move_y) {
cancelTouch();
if(dy > 0) {
config.wipeDown();
}
else {
config.wipeUp();
}
}
}
}
function onTouchStart(e)
{
if (e.touches.length == 1) {
startX = e.touches[0].pageX;
startY = e.touches[0].pageY;
isMoving = true;
this.addEventListener('touchmove', onTouchMove, false);
}
}
if ('ontouchstart' in document.documentElement) {
this.addEventListener('touchstart', onTouchStart, false);
}
});
return this;
};
$.elastislide = function( options, element ) {
this.$el = $( element );
this._init( options );
};
$.elastislide.defaults = {
speed : 450, // animation speed
easing : '', // animation easing effect
imageW : 190, // the images width
margin : 3, // image margin right
border : 2, // image border
minItems : 1, // the minimum number of items to show.
// when we resize the window, this will make sure minItems are always shown
// (unless of course minItems is higher than the total number of elements)
current : 0, // index of the current item
// when we resize the window, the carousel will make sure this item is visible
navPrev :'<span class="es-nav-prev">Prev</span>',
navNext :'<span class="es-nav-next">Next</span>',
onClick : function() { return false; } // click item callback
};
$.elastislide.prototype = {
_init : function( options ) {
this.options = $.extend( true, {}, $.elastislide.defaults, options );
// <ul>
this.$slider = this.$el.find('ul');
// <li>
this.$items = this.$slider.children('li');
// total number of elements / images
this.itemsCount = this.$items.length;
// cache the <ul>'s parent, since we will eventually need to recalculate its width on window resize
this.$esCarousel = this.$slider.parent();
// validate options
this._validateOptions();
// set sizes and initialize some vars...
this._configure();
// add navigation buttons
this._addControls();
// initialize the events
this._initEvents();
// show the <ul>
this.$slider.show();
// slide to current's position
this._slideToCurrent( false );
},
_validateOptions : function() {
if( this.options.speed < 0 )
this.options.speed = 450;
if( this.options.margin < 0 )
this.options.margin = 4;
if( this.options.border < 0 )
this.options.border = 1;
if( this.options.minItems < 1 || this.options.minItems > this.itemsCount )
this.options.minItems = 1;
if( this.options.current > this.itemsCount - 1 )
this.options.current = 0;
},
_configure : function() {
// current item's index
this.current = this.options.current;
// the ul's parent's (div.es-carousel) width is the "visible" width
this.visibleWidth = this.$esCarousel.width();
// test to see if we need to initially resize the items
if( this.visibleWidth < this.options.minItems * ( this.options.imageW + 2 * this.options.border ) + ( this.options.minItems - 1 ) * this.options.margin ) {
this._setDim( ( this.visibleWidth - ( this.options.minItems - 1 ) * this.options.margin ) / this.options.minItems );
this._setCurrentValues();
// how many items fit with the current width
this.fitCount = this.options.minItems;
}
else {
this._setDim();
this._setCurrentValues();
}
// set the <ul> width
this.$slider.css({
width : this.sliderW
});
},
_setDim : function( elW ) {
// <li> style
this.$items.css({
marginRight : this.options.margin,
width : ( elW ) ? elW : this.options.imageW + 2 * this.options.border
}).children('a').css({ // <a> style
borderWidth : this.options.border
});
},
_setCurrentValues : function() {
// the total space occupied by one item
this.itemW = this.$items.outerWidth(true);
// total width of the slider / <ul>
// this will eventually change on window resize
this.sliderW = this.itemW * this.itemsCount;
// the ul parent's (div.es-carousel) width is the "visible" width
this.visibleWidth = this.$esCarousel.width();
// how many items fit with the current width
this.fitCount = Math.floor( this.visibleWidth / this.itemW );
},
_addControls : function() {
this.$navNext = $(this.options.navNext);
this.$navPrev = $(this.options.navPrev);
$('<div class="es-nav"/>')
.append( this.$navPrev )
.append( this.$navNext )
.appendTo( this.$el );
//this._toggleControls();
},
_toggleControls : function( dir, status ) {
// show / hide navigation buttons
if( dir && status ) {
if( status === 1 )
( dir === 'right' ) ? this.$navNext.show() : this.$navPrev.show();
else
( dir === 'right' ) ? this.$navNext.hide() : this.$navPrev.hide();
}
else if( this.current === this.itemsCount - 1 || this.fitCount >= this.itemsCount )
this.$navNext.hide();
},
_initEvents : function() {
var instance = this;
// window resize
$(window).on('resize.elastislide', function( event ) {
instance._reload();
// slide to the current element
clearTimeout( instance.resetTimeout );
instance.resetTimeout = setTimeout(function() {
instance._slideToCurrent();
}, 200);
});
// navigation buttons events
this.$navNext.on('click.elastislide', function( event ) {
instance._slide('right');
});
this.$navPrev.on('click.elastislide', function( event ) {
instance._slide('left');
});
// item click event
this.$slider.on('click.elastislide', 'li', function( event ) {
instance.options.onClick( $(this) );
return false;
});
// touch events
instance.$slider.touchwipe({
wipeLeft : function() {
instance._slide('right');
},
wipeRight : function() {
instance._slide('left');
}
});
},
reload : function( callback ) {
this._reload();
if ( callback ) callback.call();
},
_reload : function() {
var instance = this;
// set values again
instance._setCurrentValues();
// need to resize items
if( instance.visibleWidth < instance.options.minItems * ( instance.options.imageW + 2 * instance.options.border ) + ( instance.options.minItems - 1 ) * instance.options.margin ) {
instance._setDim( ( instance.visibleWidth - ( instance.options.minItems - 1 ) * instance.options.margin ) / instance.options.minItems );
instance._setCurrentValues();
instance.fitCount = instance.options.minItems;
}
else{
instance._setDim();
instance._setCurrentValues();
}
instance.$slider.css({
width : instance.sliderW + 10 // TODO: +10px seems to solve a firefox "bug" :S
});
},
_slide : function( dir, val, anim, callback ) {
// if animating return
//if( this.$slider.is(':animated') )
//return false;
// current margin left
var ml = parseFloat( this.$slider.css('margin-left') );
// val is just passed when we want an exact value for the margin left (used in the _slideToCurrent function)
if( val === undefined ) {
// how much to slide?
var amount = this.fitCount * this.itemW, val;
if( amount < 0 ) return false;
// make sure not to leave a space between the last item / first item and the end / beggining of the slider available width
if( dir === 'right' && this.sliderW - ( Math.abs( ml ) + amount ) < this.visibleWidth ) {
amount = this.sliderW - ( Math.abs( ml ) + this.visibleWidth ) - this.options.margin; // decrease the margin left
// show / hide navigation buttons
this._toggleControls( 'right', -1 );
this._toggleControls( 'left', 1 );
}
else if( dir === 'left' && Math.abs( ml ) - amount < 0 ) {
amount = Math.abs( ml );
// show / hide navigation buttons
this._toggleControls( 'left', -1 );
this._toggleControls( 'right', 1 );
}
else {
var fml; // future margin left
( dir === 'right' )
? fml = Math.abs( ml ) + this.options.margin + Math.abs( amount )
: fml = Math.abs( ml ) - this.options.margin - Math.abs( amount );
// show / hide navigation buttons
if( fml > 0 )
this._toggleControls( 'left', 1 );
else
this._toggleControls( 'left', -1 );
if( fml < this.sliderW - this.visibleWidth )
this._toggleControls( 'right', 1 );
else
this._toggleControls( 'right', -1 );
}
( dir === 'right' ) ? val = '-=' + amount : val = '+=' + amount
}
else {
var fml = Math.abs( val ); // future margin left
if( Math.max( this.sliderW, this.visibleWidth ) - fml < this.visibleWidth ) {
val = - ( Math.max( this.sliderW, this.visibleWidth ) - this.visibleWidth );
if( val !== 0 )
val += this.options.margin; // decrease the margin left if not on the first position
// show / hide navigation buttons
this._toggleControls( 'right', -1 );
fml = Math.abs( val );
}
// show / hide navigation buttons
if( fml > 0 )
this._toggleControls( 'left', 1 );
else
this._toggleControls( 'left', -1 );
if( Math.max( this.sliderW, this.visibleWidth ) - this.visibleWidth > fml + this.options.margin )
this._toggleControls( 'right', 1 );
else
this._toggleControls( 'right', -1 );
}
$.fn.applyStyle = ( anim === undefined ) ? $.fn.animate : $.fn.css;
var sliderCSS = { marginLeft : val };
var instance = this;
this.$slider.stop().applyStyle( sliderCSS, $.extend( true, [], { duration : this.options.speed, easing : this.options.easing, complete : function() {
if( callback ) callback.call();
} } ) );
},
_slideToCurrent : function( anim ) {
// how much to slide?
var amount = this.current * this.itemW;
this._slide('', -amount, anim );
},
add : function( $newelems, callback ) {
// adds new items to the carousel
this.$items = this.$items.add( $newelems );
this.itemsCount = this.$items.length;
this._setDim();
this._setCurrentValues();
this.$slider.css({
width : this.sliderW
});
this._slideToCurrent();
if ( callback ) callback.call( $newelems );
},
setCurrent : function( idx, callback ) {
this.current = idx;
var ml = Math.abs( parseFloat( this.$slider.css('margin-left') ) ),
posR = ml + this.visibleWidth,
fml = Math.abs( this.current * this.itemW );
if( fml + this.itemW > posR || fml < ml ) {
this._slideToCurrent();
}
if ( callback ) callback.call();
},
destroy : function( callback ) {
this._destroy( callback );
},
_destroy : function( callback ) {
this.$el.off('.elastislide').removeData('elastislide');
$(window).off('.elastislide');
if ( callback ) callback.call();
}
};
var logError = function( message ) {
if ( this.console ) {
console.error( message );
}
};
$.fn.elastislide = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'elastislide' );
if ( !instance ) {
logError( "cannot call methods on elastislide prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for elastislide instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'elastislide' );
if ( !instance ) {
$.data( this, 'elastislide', new $.elastislide( options, this ) );
}
});
}
return this;
};
})( window, jQuery ); | LechDutkiewicz/serfenta_theme | lib/extensions/rg-gallery/jquery.elastislide.js | JavaScript | mit | 13,063 |
#include "test2D.hpp"
namespace boom {
namespace test2d {
MonoPolygon::MonoPolygon(DistV&& dL, DistV&& dR, const Vec2& ori, const Vec2& dir, float wofs):
_vOrigin(ori),
_vDir(dir),
_distL(std::move(dL)),
_distR(std::move(dR)),
_widthOffset(wofs)
{}
MonoPolygon MonoPolygon::Random(const FRandF& rff, const FRandI& rfi, const spn::RangeF& rV, const spn::RangeF& rLen, int nV) {
nV = std::max(3, nV);
// ランダムにスイープ方向を決める
auto dir = Vec2::RandomDir(rff);
// 原点座標
auto origin = Vec2::Random(rff, rV);
// 長さ
float length = rff(rLen);
int nLeft = rfi({1, nV-2}),
nRight = rfi({0, nV-2-nLeft});
auto fnMakeLengthList = [&rff](const int n, const float len) {
std::vector<Vec2> distL(n+1);
float sumL = 0;
for(auto& d : distL) {
float num = rff({1e-2f, 1e1f});
sumL += num;
d.x = num;
d.y = rff({0, 1e1f});
}
distL.back().y = 0;
for(auto& d : distL) {
d.x /= sumL;
d.x *= len;
}
return distL;
};
float width_offset = rff(rLen * 1e-1f);
auto distL = fnMakeLengthList(nLeft, length),
distR = fnMakeLengthList(nRight, length);
return MonoPolygon(std::move(distL),
std::move(distR),
origin,
dir,
width_offset);
}
geo2d::PointL MonoPolygon::getPoints() const {
int nLeft = _distL.size()-1,
nRight = _distR.size()-1;
geo2d::PointL pts(2 + nLeft + nRight);
auto* ptr = pts.data();
spn::Vec2 dir90{-_vDir.y, _vDir.x};
// 始点を追加
*ptr++ = _vOrigin + dir90*_widthOffset;
float cur = 0;
// 左側にランダムな数の頂点(最低1)
for(int i=0 ; i<nLeft ; i++) {
auto& dist = _distL[i];
cur += dist.x;
*ptr++ = _vOrigin + _vDir*cur + dir90*(dist.y + _widthOffset);
}
cur += _distL.back().x;
// 終点に頂点を配置
*ptr++ = _vOrigin + _vDir*cur + dir90*_widthOffset;
// 右側にランダムな数の頂点
cur -= _distR.back().x;
for(int i=nRight-1 ; i>=0 ; i--) {
auto& dist = _distR[i];
*ptr++ = _vOrigin + _vDir*cur - dir90*(dist.y - _widthOffset);
cur -= dist.x;
}
Assert(Trap, pts.data()+pts.size() == ptr)
return pts;
}
const spn::Vec2& MonoPolygon::getDir() const {
return _vDir;
}
bool MonoPolygon::hit(const spn::Vec2& p, float threshold) const {
Vec2 dir90(-_vDir.y, _vDir.x);
auto toP = p - (_vOrigin + dir90*_widthOffset);
float d_vert = _vDir.dot(toP),
d_horz = std::sqrt(toP.len_sq() - spn::Square(d_vert));
if(d_vert < 0)
return false;
auto fnGetHDist = [](const auto& distV, float d_vert, float invalid){
int nL = distV.size();
float cur_y = 0;
for(int i=0 ; i<nL ; i++) {
auto &dist = distV[i];
if(d_vert <= dist.x)
return spn::Lerp(cur_y, dist.y, d_vert / dist.x);
d_vert -= dist.x;
cur_y = dist.y;
}
return invalid;
};
if(dir90.dot(toP) < 0)
d_horz *= -1;
float dL = fnGetHDist(_distL, d_vert, -1.f),
dR = fnGetHDist(_distR, d_vert, -1.f);
return spn::IsInRange(d_horz, -dR-threshold, dL+threshold);
}
}
}
| degarashi/boomstick | tests/monopolygon.cpp | C++ | mit | 3,121 |
<?php
/*
* This file is part of AppBundle the package.
*
* (c) Ruslan Muriev <muriev.r@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace RonteLtd\JsonApiBundle\Serializer\Normalizer;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Class Collection
*
* @package RonteLtd\JsonApiBundle\Serializer\Normalizer
* @author Ruslan Muriev <muriev.r@gmail.com>
*/
class Collection extends ArrayCollection
{
/**
* JsonApi "jsonapi" example ["version" => "1.0"]
*
* @var array
*/
protected $jsonapi = [];
/**
* JsonApi meta
*
* @var array
*/
protected $meta = [];
/**
* JsonApi links
*
* @var array
*/
protected $links = [];
/**
* Initializes a new ArrayCollection.
*
* @param $elements
*/
public function __construct($elements = array())
{
if (!is_array($elements)) {
$elements = [$elements];
}
parent::__construct($elements);
}
/**
* @return array
*/
public function getJsonapi()
{
return $this->jsonapi;
}
/**
* @param array $jsonapi
*/
public function setJsonapi($jsonapi)
{
$this->jsonapi = $jsonapi;
}
/**
* @return array
*/
public function getMeta()
{
return $this->meta;
}
/**
* @param array $meta
*/
public function setMeta($meta)
{
$this->meta = $meta;
}
/**
* @return array
*/
public function getLinks()
{
return $this->links;
}
/**
* @param array $links
*/
public function setLinks($links)
{
$this->links = $links;
}
} | ronte-ltd/JsonApiBundle | Serializer/Normalizer/Collection.php | PHP | mit | 1,811 |
// $flavio.lisboa @ 2017-09-04.
//
/*
* @file basic_octdiff_cons.hpp
*/
#ifndef adl__oct__cons__basic_octdiff_cons__hpp__
#define adl__oct__cons__basic_octdiff_cons__hpp__
#include <type_traits>
#include <string>
#include <iosfwd>
#include <stdexcept>
#include "adl.cfg.hpp"
#include "adl/oct.fwd.hpp"
#include "adl/oct/constant.hpp"
#include "adl/oct/traits.hpp"
#include "adl/oct/var.hpp"
#include "adl/oct/vexpr.hpp"
#include "adl/oct/cons/cons_base_.hpp"
//
// [[ API ]]
//
adl_BEGIN_ROOT_MODULE
namespace oct {
template <typename ConstantType, typename VarType>
class basic_octdiff_cons : public cons_base_<ConstantType, VarType> {
private:
using superclass_ = cons_base_<ConstantType, VarType>;
public:
using typename superclass_::var_type;
using typename superclass_::constant_type;
using typename superclass_::vexpr_type;
using superclass_::cons_base_;
using superclass_::operator=;
using superclass_::space;
using superclass_::vexpr_;
using superclass_::c_;
static_assert(space == domain_space::octdiff, "Wrong variable type.");
constexpr basic_octdiff_cons() noexcept = default;
constexpr basic_octdiff_cons(basic_octdiff_cons const&) noexcept = default;
constexpr basic_octdiff_cons(basic_octdiff_cons &&) noexcept = default;
constexpr basic_octdiff_cons& operator=(basic_octdiff_cons const&) noexcept = default;
constexpr basic_octdiff_cons& operator=(basic_octdiff_cons &&) noexcept = default;
constexpr basic_octdiff_cons(vexpr_type vexpr, constant_type c);
constexpr static basic_octdiff_cons make_upper_limit(vexpr_type vexpr, constant_type c) noexcept; // +-xi [+- xj] <= c
template <
typename ConstantType_,
typename VarType_,
typename = std::enable_if_t<
common_var<VarType_>::is_octdiff_space
&& (!std::is_same<VarType_, var_type>::value || !std::is_same<ConstantType_, constant_type>::value)
&& std::is_convertible<ConstantType_, constant_type>::value>>
constexpr basic_octdiff_cons(basic_octdiff_cons<ConstantType_, VarType_> cons) noexcept;
template <
typename VarType_,
typename = std::enable_if_t<
common_var<VarType_>::is_octdiff_space
&& !std::is_same<VarType_, var_type>::value>>
explicit constexpr basic_octdiff_cons(basic_octdiff_vexpr<VarType_> vexpr) noexcept;
template <
typename VarType_ = var_type,
typename = std::enable_if_t<common_var<VarType_>::is_octdiff_space>>
constexpr basic_octdiff_vexpr<VarType_> to_vexpr() const noexcept;
template <
typename VarType_ = var_type,
typename = std::enable_if_t<common_var<VarType_>::is_octdiff_space>>
constexpr operator basic_octdiff_vexpr<VarType_>() const noexcept;
private:
friend class basic_octdiff_conjunction<ConstantType, VarType>;
constexpr basic_octdiff_cons& commute() noexcept;
constexpr basic_octdiff_cons to_commuted() const noexcept;
};
template <typename ConstantType> constexpr octdiff_cons<ConstantType> to_identity(octdiff_cons<ConstantType> cons) { return cons; }
template <typename ConstantType> constexpr octdiff_cons<ConstantType> to_identity(octdiff_lcons<ConstantType> cons) { return cons.to_identity(); }
template <
typename ConstantType,
typename VarType,
typename = std::enable_if_t<common_var<VarType>::is_octdiff_space>>
constexpr basic_octdiff_cons<ConstantType, VarType>
make_upper_limit(basic_octdiff_vexpr<VarType> vexpr, ConstantType c) noexcept {
return basic_octdiff_cons<ConstantType, VarType>::make_upper_limit(vexpr, c);
};
template <
typename ConstantType,
typename VarType,
typename = std::enable_if_t<common_var<VarType>::is_octdiff_space>>
constexpr basic_octdiff_cons<ConstantType, VarType> make_cons(basic_octdiff_vexpr<VarType> vexpr, ConstantType c) noexcept {
return basic_octdiff_cons<ConstantType, VarType>(vexpr, c);
};
} // namespace oct
namespace dsl {
inline namespace oct {
inline namespace cons {
template <
typename ConstantType,
typename VarType,
typename = std::enable_if_t<
adl::oct::common_var<VarType>::is_octdiff_space
&& std::is_arithmetic<ConstantType>::value>>
constexpr adl::oct::basic_octdiff_cons<ConstantType, VarType> operator<=(
adl::oct::basic_octdiff_vexpr<VarType> vexpr,
ConstantType rhs
) noexcept {
return adl::oct::make_upper_limit(vexpr, rhs);
};
}
}
}
namespace operators {
inline namespace oct {
inline namespace cons {
inline namespace comparison {
template <typename ConstantType,
typename VarType,
typename = std::enable_if_t<adl::oct::common_var<VarType>::is_octdiff_space>>
constexpr bool operator<(adl::oct::basic_octdiff_cons<ConstantType, VarType> lhs, adl::oct::basic_octdiff_cons<ConstantType, VarType> const& rhs) noexcept { return lhs.compare(rhs) < 0; }
template <typename ConstantType,
typename VarType,
typename = std::enable_if_t<adl::oct::common_var<VarType>::is_octdiff_space>>
constexpr bool operator<=(adl::oct::basic_octdiff_cons<ConstantType, VarType> lhs, adl::oct::basic_octdiff_cons<ConstantType, VarType> const& rhs) noexcept { return lhs.compare(rhs) <= 0; }
template <typename ConstantType,
typename VarType,
typename = std::enable_if_t<adl::oct::common_var<VarType>::is_octdiff_space>>
constexpr bool operator==(adl::oct::basic_octdiff_cons<ConstantType, VarType> lhs, adl::oct::basic_octdiff_cons<ConstantType, VarType> const& rhs) noexcept { return lhs.equals(rhs); }
template <typename ConstantType,
typename VarType,
typename = std::enable_if_t<adl::oct::common_var<VarType>::is_octdiff_space>>
constexpr bool operator!=(adl::oct::basic_octdiff_cons<ConstantType, VarType> lhs, adl::oct::basic_octdiff_cons<ConstantType, VarType> const& rhs) noexcept { return !lhs.equals(rhs); }
template <typename ConstantType,
typename VarType,
typename = std::enable_if_t<adl::oct::common_var<VarType>::is_octdiff_space>>
constexpr bool operator>=(adl::oct::basic_octdiff_cons<ConstantType, VarType> lhs, adl::oct::basic_octdiff_cons<ConstantType, VarType> const& rhs) noexcept { return lhs.compare(rhs) >= 0; }
template <typename ConstantType,
typename VarType,
typename = std::enable_if_t<adl::oct::common_var<VarType>::is_octdiff_space>>
constexpr bool operator>(adl::oct::basic_octdiff_cons<ConstantType, VarType> lhs, adl::oct::basic_octdiff_cons<ConstantType, VarType> const& rhs) noexcept { return lhs.compare(rhs) > 0; }
}
}
}
}
adl_END_ROOT_MODULE
template <typename ConstantType,
typename VarType,
typename Traits,
typename = std::enable_if_t<adl::oct::common_var<VarType>::is_octdiff_space>>
std::basic_ostream<char, Traits>& operator<<(
std::basic_ostream<char, Traits>& os,
adl::oct::basic_octdiff_cons<ConstantType, VarType> const& cons
) {
cons.print(os);
return os;
};
//
// [[ TEMPLATE IMPLEMENTATION ]]
//
#include "adl/oct/cons/basic_oct_cons.hpp"
#include "adl/oct/cons/basic_octdiff_conjunction.hpp"
adl_BEGIN_ROOT_MODULE
namespace oct {
//
// adl::oct::basic_octdiff_cons
//
template <typename ConstantType, typename VarType>
constexpr basic_octdiff_cons<ConstantType, VarType>::basic_octdiff_cons(vexpr_type vexpr, constant_type c) : superclass_(vexpr, c) {};
template <typename ConstantType, typename VarType>
constexpr basic_octdiff_cons<ConstantType, VarType>
basic_octdiff_cons<ConstantType, VarType>::make_upper_limit(vexpr_type vexpr, constant_type c) noexcept {
return basic_octdiff_cons<ConstantType, VarType>(vexpr, c);
};
template <typename ConstantType, typename VarType>
template <typename ConstantType_, typename VarType_, typename>
constexpr basic_octdiff_cons<ConstantType, VarType>::basic_octdiff_cons(
basic_octdiff_cons<ConstantType_, VarType_> cons
) noexcept : basic_octdiff_cons(vexpr_type(cons.xi(), cons.xj()), cons.c()) {};
template <typename ConstantType, typename VarType>
template <typename VarType_, typename>
constexpr basic_octdiff_cons<ConstantType, VarType>::basic_octdiff_cons(
basic_octdiff_vexpr<VarType_> vexpr
) noexcept : basic_octdiff_cons(vexpr, constant_type()) {};
template <typename ConstantType, typename VarType>
template <typename VarType_, typename>
constexpr basic_octdiff_vexpr<VarType_> basic_octdiff_cons<ConstantType, VarType>::to_vexpr() const noexcept {
return basic_octdiff_vexpr<VarType_>(this->xi(), this->xj());
};
template <typename ConstantType, typename VarType>
template <typename VarType_, typename>
constexpr basic_octdiff_cons<ConstantType, VarType>::operator basic_octdiff_vexpr<VarType_>() const noexcept {
return to_vexpr<VarType_>();
};
template <typename ConstantType, typename VarType>
constexpr basic_octdiff_cons<ConstantType, VarType>& basic_octdiff_cons<ConstantType, VarType>::commute() noexcept {
if (!vexpr_.unit()) vexpr_ = vexpr_type(vexpr_.xJ(), vexpr_.xI());
return *this;
}
template <typename ConstantType, typename VarType>
constexpr basic_octdiff_cons<ConstantType, VarType> basic_octdiff_cons<ConstantType, VarType>::to_commuted() const noexcept {
return basic_octdiff_cons<ConstantType, VarType>(*this).commute();
}
} // namespace oct
adl_END_ROOT_MODULE
#endif // adl__oct__cons__basic_octdiff_cons__hpp__
| flisboac/adl | include/adl/oct/cons/basic_octdiff_cons.hpp | C++ | mit | 10,062 |
#!/usr/bin/env node
var _ = require('lodash');
var async = require('async-chainable');
var asyncFlush = require('async-chainable-flush');
var colors = require('chalk');
var doop = require('.');
var glob = require('glob');
var fs = require('fs');
var fspath = require('path');
var program = require('commander');
var sha1 = require('node-sha1');
program
.version(require('./package.json').version)
.description('List units installed for the current project')
.option('-b, --basic', 'Display a simple list, do not attempt to hash file differences')
.option('-v, --verbose', 'Be verbose. Specify multiple times for increasing verbosity', function(i, v) { return v + 1 }, 0)
.parse(process.argv);
async()
.use(asyncFlush)
.then(doop.chProjectRoot)
.then(doop.getUserSettings)
// Get the list of units {{{
.then('units', function(next) {
doop.getUnits(function(err, units) {
if (err) return next(err);
next(null, units.map(u => { return {
id: u,
path: fspath.join(doop.settings.paths.units, u),
files: {},
} }));
});
})
// }}}
// Hash file comparisons unless program.basic {{{
// Get repo {{{
.then('repo', function(next) {
if (program.basic) return next();
doop.getDoopPath(next, program.repo);
})
.then(function(next) {
if (program.basic) return next();
if (program.verbose) console.log('Using Doop source:', colors.cyan(this.repo));
next();
})
// }}}
// Scan project + Doop file list and hash all files (unless !program.basic) {{{
.then(function(next) {
if (program.basic) return next();
// Make a list of all files in both this project and in the doop repo
// For each file create an object with a `local` sha1 hash and `doop` sha1 hash
var hashQueue = async(); // Hash tasks to perform
async()
.forEach(this.units, function(next, unit) {
async()
.parallel([
// Hash all project files {{{
function(next) {
glob(fspath.join(unit.path, '**'), {nodir: true}, function(err, files) {
if (files.length) {
unit.existsInProject = true;
files.forEach(function(file) {
hashQueue.defer(file, function(next) {
if (program.verbose) console.log('Hash file (Proj)', colors.cyan(file));
sha1(fs.createReadStream(file), function(err, hash) {
if (!unit.files[file]) unit.files[file] = {path: file};
unit.files[file].project = hash;
next();
});
});
});
} else {
unit.existsInProject = false;
}
next();
});
},
// }}}
// Hash all Doop files {{{
function(next) {
glob(fspath.join(doop.settings.paths.doop, unit.path, '**'), {nodir: true}, function(err, files) {
if (files.length) {
unit.existsInDoop = true;
files.forEach(function(rawFile) {
var croppedPath = rawFile.substr(doop.settings.paths.doop.length + 1);
var file = fspath.join(doop.settings.paths.doop, croppedPath);
hashQueue.defer(file, function(next) {
if (program.verbose) console.log('Hash file (Doop)', colors.cyan(croppedPath));
sha1(fs.createReadStream(file), function(err, hash) {
if (!unit.files[croppedPath]) unit.files[croppedPath] = {path: file};
unit.files[croppedPath].doop = hash;
next();
});
});
});
} else {
unit.existsInDoop = false;
}
next();
});
},
// }}}
])
.end(next)
})
.end(function(err) {
if (err) return next(err);
// Wait for hashing queue to finish
hashQueue.await().end(next);
});
})
// }}}
// }}}
// Present the list {{{
.then(function(next) {
var task = this;
if (program.verbose > 1) console.log();
this.units.forEach(function(unit) {
if (unit.existsInProject && !unit.existsInDoop) {
console.log(colors.grey(' -', unit.id));
} else if (!unit.existsInProject && unit.existsInDoop) {
console.log(colors.red(' -', unit.id));
} else { // In both Doop + Project - examine file differences
var changes = [];
// Edited {{{
var items = _.filter(unit.files, f => f.project && f.doop && f.project != f.doop);
if (_.get(doop.settings, 'list.changes.maxEdited') && items.length > doop.settings.list.changes.maxEdited) {
changes.push(colors.yellow.bold('~' + items.length + ' items'));
} else {
items.forEach(f => changes.push(colors.yellow.bold('~') + f.path.substr(unit.path.length+1)));
}
// }}}
// Created {{{
var items = _.filter(unit.files, f => f.project && !f.doop);
if (_.get(doop.settings, 'list.changes.maxCreated') && items.length > doop.settings.list.changes.maxCreated) {
changes.push(colors.green.bold('+' + items.length + ' items'));
} else {
items.forEach(f => changes.push(colors.green.bold('+') + f.path.substr(unit.path.length+1)));
}
// }}}
// Deleted {{{
var items = _.filter(unit.files, f => f.doop && !f.project);
if (_.get(doop.settings, 'list.changes.maxDeleted') && items.length > doop.settings.list.changes.maxDeleted) {
changes.push(colors.red.bold('-' + items.length + ' items'));
} else {
items.forEach(f => changes.push(colors.red.bold('-') + f.path.substr(doop.settings.paths.doop.length+unit.path.length+2)));
}
// }}}
if (changes.length) {
console.log(' -', unit.id, colors.blue('('), changes.join(', '), colors.blue(')'));
} else {
console.log(' -', unit.id);
}
}
});
next();
})
// }}}
// End {{{
.flush()
.end(function(err) {
if (err) {
console.log(colors.red('Doop Error'), err.toString());
process.exit(1);
} else {
process.exit(0);
}
});
// }}}
| MomsFriendlyDevCo/doop-cli | doop-list.js | JavaScript | mit | 5,758 |
#include "NoReturnFunctionExtractionValidator.hpp"
#include <cppmanip/boundary/ExtractMethodError.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/range/algorithm_ext/push_back.hpp>
#include <boost/range/algorithm/sort.hpp>
namespace cppmanip
{
namespace
{
std::string printOrderedVariableNameList(const ast::LocalVariables& variables)
{
using boost::adaptors::transformed;
std::vector<std::string> names;
boost::push_back(names, variables | transformed(std::bind(&ast::LocalVariable::getName, std::placeholders::_1)));
boost::sort(names);
return boost::algorithm::join(names, ", ");
}
}
void NoReturnFunctionExtractionValidator::validateStatements(const std::string& functionName, ast::ScopedStatementRange selected)
{
auto used = findVariablesDeclaredByAndUsedAfterStmts(selected.getRange(), selected.getScope());
if (!used.empty())
throw boundary::ExtractMethodError("Cannot extract \'" + functionName +
"\'. Following variables are in use after the selected statements: " + printOrderedVariableNameList(used));
}
}
| rafalprzywarski/libcppmanip | library/src/cppmanip/NoReturnFunctionExtractionValidator.cpp | C++ | mit | 1,135 |
<?php
namespace DomainBundle\Entity\Super;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\MappedSuperclass
*/
abstract class IntegerID extends Entity
{
/**
* @var int
*
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id = null;
public function __toString()
{
return (string) $this->getId();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
}
| sugatov/web-pms | src/DomainBundle/Entity/Super/IntegerID.php | PHP | mit | 528 |
if(!Hummingbird) { var Hummingbird = {}; }
Hummingbird.Base = function() {};
Hummingbird.Base.prototype = {
validMessageCount: 0,
messageRate: 20,
initialize: function() {
this.averageLog = [];
this.setFilter();
this.registerHandler();
},
registerHandler: function() {
this.socket.registerHandler(this.onData, this);
},
onMessage: function(message) {
console.log("Base class says: " + JSON.stringify(message));
},
onData: function(fullData) {
var average;
var message = this.extract(fullData);
if(typeof(message) != "undefined") {
this.validMessageCount += 1;
// Calculate the average over N seconds if the averageOver option is set
if(this.options.averageOver) { average = this.addToAverage(message); }
if((!this.options.every) || (this.validMessageCount % this.options.every == 0)) {
this.onMessage(message, this.average());
}
}
},
extract: function(data) {
if(typeof(data) == "undefined") { return; }
var obj = data;
for(var i = 0, len = this.filter.length; i < len; i++) {
obj = obj[this.filter[i]];
if(typeof(obj) == "undefined") { return; }
}
return obj;
},
setFilter: function() {
// TODO: extend this (and extract) to support multiple filters
var obj = this.options.data;
this.filter = [];
while(typeof(obj) == "object") {
for(var i in obj) {
this.filter.push(i);
obj = obj[i];
break;
}
}
},
addToAverage: function(newValue) {
var averageCount = this.options.averageOver * this.messageRate;
this.averageLog.push(newValue);
if(this.averageLog.length > averageCount) {
this.averageLog.shift();
}
},
average: function() {
if(this.averageLog.length == 0) { return 0; }
return this.averageLog.sum() * 1.0 / this.averageLog.length * this.messageRate;
}
};
| mikejihbe/hummingbird | public/js/widgets/base.js | JavaScript | mit | 1,907 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.sunnybat.paxchecker.setup.email;
import com.github.sunnybat.commoncode.email.EmailAddress;
import com.github.sunnybat.commoncode.email.account.EmailAccount;
import com.github.sunnybat.commoncode.preferences.PreferenceHandler;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
/**
*
* @author SunnyBat
*/
public class EmailSetupGUI extends javax.swing.JFrame {
private AuthenticationCallback myCallback = new AuthenticationCallback();
private AuthGmail authGmail = new AuthGmail(myCallback);
private AuthSMTP authSmtp = new AuthSMTP(myCallback);
private PreferenceHandler prefs;
private EmailAccount finalizedEmailAccount;
private boolean disableEmail = false;
private List<EmailAddress> savedEmailAddresses;
private boolean savedIsGmail;
/**
* Creates new form EmailUIWrapper
*
* @param prefs The Preferences to save email configuration settings to and load from
*/
public EmailSetupGUI(PreferenceHandler prefs) {
this.prefs = prefs;
initComponents();
customComponents();
}
private void customComponents() {
String smtpAddress = prefs.getStringPreference("EMAIL");
String emailString = prefs.getStringPreference("CELLNUM");
String emailType = prefs.getStringPreference("EMAILTYPE");
// TODO: we need to initialize everything here, including Send To
// addresses and the EmailAccount we're using
if (emailType != null && emailType.equalsIgnoreCase("SMTP")) {
JRBSMTP.setSelected(true);
setAuthPanel(authSmtp);
savedIsGmail = false;
if (smtpAddress != null) {
authSmtp.setEmailAddress(smtpAddress);
} else {
System.out.println("smtpIsNull");
}
authSmtp.recordCurrentFields();
} else {
JRBGmail.setSelected(true);
setAuthPanel(authGmail);
savedIsGmail = true;
if (emailType != null) { // Assumed to be Gmail
authGmail.authenticate();
}
authGmail.recordCurrentFields();
}
if (emailString != null) {
List<EmailAddress> addresses = EmailAddress.convertToList(emailString);
for (EmailAddress address : addresses) {
DefaultTableModel table = (DefaultTableModel) JTCellNumbers.getModel();
table.addRow(new Object[]{address.getCarrierName().equalsIgnoreCase("[Other]") ? address.getCompleteAddress() : address.getAddressBeginning(), address.getCarrierName()});
}
}
savedEmailAddresses = getCurrentEmails();
savedIsGmail = JRBGmail.isSelected();
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int result = JOptionPane.showConfirmDialog(null,
"Would you like to save your changes?\r\nYes: Save Changes\r\nNo: Disable Email\r\nCancel: Discard changes\r\n[X] Button: Keep window open",
"Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
saveChanges();
} else if (result == JOptionPane.NO_OPTION) {
disableEmail();
} else if (result == JOptionPane.CANCEL_OPTION) {
cancelChanges();
}
}
});
}
/**
* Gets the currently configured EmailAccount. This includes the email addresses currently
* configured to be sent to. The EmailAccount must be successfully authenticated, otherwise null
* will be returned.
*
* @return The EmailAccount configured, or null if not set up
*/
public EmailAccount getEmailAccount() {
if (disableEmail) {
return null;
}
EmailAccount account;
if (JRBGmail.isSelected() && authGmail.isAuthenticated()) {
account = authGmail.getEmailAccount();
} else if (JRBSMTP.isSelected() && authSmtp.isAuthenticated()) {
account = authSmtp.getEmailAccount();
} else {
return null;
}
// === Add emails to account ===
account.clearAllSendAddresses(); // TODO Check to make sure this is the right thing to do, or if there's a better way
DefaultTableModel tableModel = (DefaultTableModel) JTCellNumbers.getModel();
if (tableModel.getRowCount() == 0) {
return null;
} else {
for (int i = 0; i < tableModel.getRowCount(); i++) {
EmailAddress toAdd;
String emailBeginning = (String) tableModel.getValueAt(i, 0);
String emailCarrier = (String) tableModel.getValueAt(i, 1);
if (emailCarrier.equalsIgnoreCase("[Other]")) {
toAdd = new EmailAddress(emailBeginning);
} else {
toAdd = new EmailAddress(emailBeginning + EmailAddress.getCarrierExtension(emailCarrier));
}
account.addBccEmailAddress(toAdd);
}
}
finalizedEmailAccount = account;
return finalizedEmailAccount;
}
public String getEmailType() {
if (JRBGmail.isSelected() && authGmail.isAuthenticated()) {
return "Gmail API";
} else if (JRBSMTP.isSelected() && authSmtp.isAuthenticated()) {
return "SMTP";
} else {
return "Disabled";
}
}
/**
* Gets the semicolon-delimited String representing all of the email addresses configured.
*
* @return All the configured email addresses
*/
public String getEmailAddressesString() {
List<EmailAddress> addresses = getCurrentEmails();
StringBuilder allAddresses = new StringBuilder();
for (int i = 0; i < addresses.size(); i++) {
if (i > 0) {
allAddresses.append(";");
}
allAddresses.append(addresses.get(i).getCompleteAddress());
}
return allAddresses.toString();
}
private List<EmailAddress> getCurrentEmails() {
List<EmailAddress> ret = new ArrayList<>();
DefaultTableModel tableModel = (DefaultTableModel) JTCellNumbers.getModel();
for (int i = 0; i < tableModel.getRowCount(); i++) {
try {
EmailAddress toAdd;
String emailBeginning = (String) tableModel.getValueAt(i, 0);
String emailCarrier = (String) tableModel.getValueAt(i, 1);
if (emailCarrier.equalsIgnoreCase("[Other]")) {
toAdd = new EmailAddress(emailBeginning);
} else {
toAdd = new EmailAddress(emailBeginning + EmailAddress.getCarrierExtension(emailCarrier));
}
ret.add(toAdd);
} catch (IllegalArgumentException iae) {
System.out.println("Invalid email address: " + tableModel.getValueAt(i, 0) + tableModel.getValueAt(i, 1));
}
}
return ret;
}
private void addEmail() {
String cellNumber = JTFCellNumber.getText();
String carrier = JCBCarrier.getSelectedItem().toString();
if (!cellNumber.isEmpty()) {
if (cellNumber.contains("@")) { // Full email configured
carrier = "[Other]";
}
((DefaultTableModel) JTCellNumbers.getModel()).addRow(new Object[]{cellNumber, carrier});
JTFCellNumber.setText(null);
JCBCarrier.setSelectedIndex(0);
JTFCellNumber.requestFocus();
}
}
private void resetChanges() {
DefaultTableModel model = (DefaultTableModel) JTCellNumbers.getModel();
for (int i = model.getRowCount() - 1; i >= 0; i--) {
model.removeRow(i);
}
if (savedEmailAddresses != null) {
for (EmailAddress address : savedEmailAddresses) {
model.addRow(new Object[]{address.getAddressBeginning(), EmailAddress.getProvider(address.getAddressEnding())});
}
}
if (savedIsGmail) {
JRBGmail.setSelected(true);
setAuthPanel(authGmail);
} else {
JRBSMTP.setSelected(true);
setAuthPanel(authSmtp);
}
}
private void setAuthPanel(JPanel toUse) {
JPAuthInfo.removeAll();
JPAuthInfo.add(toUse);
JPAuthInfo.revalidate();
JPAuthInfo.repaint();
pack();
}
private void resetUserInputFields() {
JTPComponents.setSelectedIndex(0);
JTFCellNumber.setText(null);
JCBCarrier.setSelectedIndex(0);
}
private void updatePreferences() {
EmailAccount toSave = getEmailAccount();
if (!disableEmail && toSave != null) {
prefs.getPreferenceObject("EMAIL").setValue(toSave.getEmailAddress());
prefs.getPreferenceObject("CELLNUM").setValue(getEmailAddressesString());
prefs.getPreferenceObject("EMAILTYPE").setValue(getEmailType());
prefs.getPreferenceObject("EMAILENABLED").setValue(true);
} else {
prefs.getPreferenceObject("EMAIL").setValue(null);
prefs.getPreferenceObject("CELLNUM").setValue(null);
prefs.getPreferenceObject("EMAILTYPE").setValue(null);
prefs.getPreferenceObject("EMAILENABLED").setValue(false);
}
}
private void saveChanges() {
if (getCurrentEmails().isEmpty()) {
int result = JOptionPane.showConfirmDialog(null, "You have no Send To emails configured. This means emails will still be disabled.\r\nAre you sure you want to save your changes?\r\nPress Yes to save your changes, or No to add email addresses.",
"No Emails Input",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.NO_OPTION) {
JTPComponents.setSelectedComponent(JPSendTo);
return;
}
}
authGmail.recordCurrentFields();
authSmtp.recordCurrentFields();
savedEmailAddresses = getCurrentEmails();
savedIsGmail = JRBGmail.isSelected();
disableEmail = false;
setVisible(false);
resetUserInputFields();
updatePreferences();
}
private void cancelChanges() {
authGmail.resetChanges();
authSmtp.resetChanges();
resetChanges();
setVisible(false);
resetUserInputFields();
updatePreferences();
}
private void disableEmail() {
disableEmail = true;
authGmail.resetChanges();
authSmtp.resetChanges();
resetChanges();
setVisible(false);
resetUserInputFields();
updatePreferences();
}
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT
* modify this code. The content of this method is always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
BGAuthType = new ButtonGroup();
JTPComponents = new JTabbedPane();
JPAuthentication = new JPanel();
JRBGmail = new JRadioButton();
JRBSMTP = new JRadioButton();
JPAuthInfo = new JPanel();
JPSendTo = new JPanel();
JTFCellNumber = new JTextField();
JBAddNumber = new JButton();
JCBCarrier = new JComboBox<>();
jLabel1 = new JLabel();
jScrollPane1 = new JScrollPane();
JTCellNumbers = new JTable();
JPFinish = new JPanel();
JBSaveChanges = new JButton();
JBCancelChanges = new JButton();
JBDisableEmail = new JButton();
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("Email Setup");
setResizable(false);
BGAuthType.add(JRBGmail);
JRBGmail.setText("Gmail API");
JRBGmail.setToolTipText("<html>\n<i>English</i>\n<p width=\"500\">Authenticates with Google through your browser. Recommended.</p>\n<i>Tech</i>\n<p width=\"500\">Used for authenticating with Google via OAuth2.<br></p>\n</html>");
JRBGmail.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JRBGmailActionPerformed(evt);
}
});
BGAuthType.add(JRBSMTP);
JRBSMTP.setText("SMTP");
JRBSMTP.setToolTipText("<html>\n<i>English</i>\n<p width=\"500\">Authenticates with any email service. Not recommended.</p>\n<i>Tech</i>\n<p width=\"500\">Authenticates with any mailserver using SMTP. Issues with this have cropped up in the past, and it's hard to detect where the problem lies. My guess is ISPs or routers blocking SMTP traffic (insane), but I don't know for sure.</p>\n</html>");
JRBSMTP.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JRBSMTPActionPerformed(evt);
}
});
JPAuthInfo.setLayout(new BoxLayout(JPAuthInfo, BoxLayout.LINE_AXIS));
GroupLayout JPAuthenticationLayout = new GroupLayout(JPAuthentication);
JPAuthentication.setLayout(JPAuthenticationLayout);
JPAuthenticationLayout.setHorizontalGroup(JPAuthenticationLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(JPAuthenticationLayout.createSequentialGroup()
.addContainerGap()
.addComponent(JRBGmail)
.addGap(18, 18, 18)
.addComponent(JRBSMTP)
.addContainerGap(249, Short.MAX_VALUE))
.addComponent(JPAuthInfo, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
JPAuthenticationLayout.setVerticalGroup(JPAuthenticationLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(JPAuthenticationLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JPAuthenticationLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(JRBGmail)
.addComponent(JRBSMTP))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(JPAuthInfo, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
JTPComponents.addTab("Authentication", JPAuthentication);
JTFCellNumber.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
JTFCellNumberKeyPressed(evt);
}
});
JBAddNumber.setText("Add Number");
JBAddNumber.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JBAddNumberActionPerformed(evt);
}
});
JBAddNumber.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
JBAddNumberKeyPressed(evt);
}
});
JCBCarrier.setModel(new DefaultComboBoxModel<>(new String[] { "AT&T (MMS)", "AT&T (SMS)", "Verizon", "Sprint", "T-Mobile", "U.S. Cellular", "Bell", "Rogers", "Fido", "Koodo", "Telus", "Virgin (CAN)", "Wind", "Sasktel", "[Other]" }));
JCBCarrier.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
JCBCarrierKeyPressed(evt);
}
});
jLabel1.setText("Cell Number");
JTCellNumbers.setModel(new DefaultTableModel(
new Object [][] {
},
new String [] {
"Cell Number", "Carrier"
}
) {
Class[] types = new Class [] {
String.class, String.class
};
boolean[] canEdit = new boolean [] {
false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
JTCellNumbers.setToolTipText("Delete emails by selecting them and pressing the DEL key");
JTCellNumbers.setColumnSelectionAllowed(true);
JTCellNumbers.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
JTCellNumbersKeyPressed(evt);
}
});
jScrollPane1.setViewportView(JTCellNumbers);
GroupLayout JPSendToLayout = new GroupLayout(JPSendTo);
JPSendTo.setLayout(JPSendToLayout);
JPSendToLayout.setHorizontalGroup(JPSendToLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(JPSendToLayout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(JTFCellNumber, GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(JCBCarrier, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(JBAddNumber))
.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
);
JPSendToLayout.setVerticalGroup(JPSendToLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, JPSendToLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JPSendToLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(JTFCellNumber, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(JBAddNumber)
.addComponent(JCBCarrier, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE))
);
JTPComponents.addTab("Send To", JPSendTo);
JBSaveChanges.setText("Save Changes");
JBSaveChanges.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JBSaveChangesActionPerformed(evt);
}
});
JBCancelChanges.setText("Cancel Changes");
JBCancelChanges.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JBCancelChangesActionPerformed(evt);
}
});
JBDisableEmail.setText("Disable Email");
JBDisableEmail.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JBDisableEmailActionPerformed(evt);
}
});
GroupLayout JPFinishLayout = new GroupLayout(JPFinish);
JPFinish.setLayout(JPFinishLayout);
JPFinishLayout.setHorizontalGroup(JPFinishLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(JPFinishLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JPFinishLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(JBSaveChanges, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(JBCancelChanges, GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE)
.addComponent(JBDisableEmail, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
JPFinishLayout.setVerticalGroup(JPFinishLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, JPFinishLayout.createSequentialGroup()
.addContainerGap()
.addComponent(JBSaveChanges)
.addGap(18, 18, 18)
.addComponent(JBCancelChanges)
.addGap(18, 18, 18)
.addComponent(JBDisableEmail)
.addContainerGap(56, Short.MAX_VALUE))
);
JTPComponents.addTab("Finish", JPFinish);
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(JTPComponents)
);
layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(JTPComponents)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void JRBGmailActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JRBGmailActionPerformed
setAuthPanel(authGmail);
}//GEN-LAST:event_JRBGmailActionPerformed
private void JRBSMTPActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JRBSMTPActionPerformed
setAuthPanel(authSmtp);
}//GEN-LAST:event_JRBSMTPActionPerformed
private void JBAddNumberActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JBAddNumberActionPerformed
addEmail();
}//GEN-LAST:event_JBAddNumberActionPerformed
private void JTCellNumbersKeyPressed(KeyEvent evt) {//GEN-FIRST:event_JTCellNumbersKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
int[] selectedIndeces = JTCellNumbers.getSelectedRows();
for (int i = selectedIndeces.length - 1; i >= 0; i--) { // Iterate from the bottom up
((DefaultTableModel) JTCellNumbers.getModel()).removeRow(selectedIndeces[i]);
}
} else if (evt.getKeyCode() == KeyEvent.VK_TAB) {
this.transferFocus();
evt.consume();
}
}//GEN-LAST:event_JTCellNumbersKeyPressed
private void JTFCellNumberKeyPressed(KeyEvent evt) {//GEN-FIRST:event_JTFCellNumberKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
addEmail();
}
}//GEN-LAST:event_JTFCellNumberKeyPressed
private void JCBCarrierKeyPressed(KeyEvent evt) {//GEN-FIRST:event_JCBCarrierKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
addEmail();
}
}//GEN-LAST:event_JCBCarrierKeyPressed
private void JBAddNumberKeyPressed(KeyEvent evt) {//GEN-FIRST:event_JBAddNumberKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
addEmail();
}
}//GEN-LAST:event_JBAddNumberKeyPressed
private void JBSaveChangesActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JBSaveChangesActionPerformed
saveChanges();
}//GEN-LAST:event_JBSaveChangesActionPerformed
private void JBCancelChangesActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JBCancelChangesActionPerformed
cancelChanges();
}//GEN-LAST:event_JBCancelChangesActionPerformed
private void JBDisableEmailActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JBDisableEmailActionPerformed
disableEmail();
}//GEN-LAST:event_JBDisableEmailActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private ButtonGroup BGAuthType;
private JButton JBAddNumber;
private JButton JBCancelChanges;
private JButton JBDisableEmail;
private JButton JBSaveChanges;
private JComboBox<String> JCBCarrier;
private JPanel JPAuthInfo;
private JPanel JPAuthentication;
private JPanel JPFinish;
private JPanel JPSendTo;
private JRadioButton JRBGmail;
private JRadioButton JRBSMTP;
private JTable JTCellNumbers;
private JTextField JTFCellNumber;
private JTabbedPane JTPComponents;
private JLabel jLabel1;
private JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
private class AuthenticationCallback implements Runnable {
private boolean nextEnabledState = false;
public void run() {
JBSaveChanges.setEnabled(nextEnabledState);
JBCancelChanges.setEnabled(nextEnabledState);
JBDisableEmail.setEnabled(nextEnabledState);
JRBGmail.setEnabled(nextEnabledState);
JRBSMTP.setEnabled(nextEnabledState);
nextEnabledState = !nextEnabledState; // Invert
}
}
}
| SunnyBat/PAXChecker | src/main/java/com/github/sunnybat/paxchecker/setup/email/EmailSetupGUI.java | Java | mit | 22,577 |
#include "PSF.h"
#include "Utils.h"
#include <cassert>
#include <iostream>
#include <fstream>
using namespace std;
using namespace arma;
PSF::PSF(int size)
:size(size)
,pixels(size, vector<double>(size, 0.))
,fft_ready(false)
{
assert(size%2 == 1);
pixels[size/2][size/2] = 1.;
}
void PSF::set_size(int new_size)
{
size = new_size;
pixels.assign(size, vector<double>(size, 0.));
pixels[size/2][size/2] = 1.;
}
void PSF::load(const char* filename)
{
fstream fin(filename, ios::in);
if(!fin)
{
cerr<<"# ERROR: couldn't open file "<<filename<<"."<<endl;
return;
}
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
fin>>pixels[i][j];
fin.close();
normalise();
}
void PSF::normalise()
{
double sum = 0.;
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
sum += pixels[i][j];
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
pixels[i][j] /= sum;
}
void PSF::calculate_fft(int Ni, int Nj)
{
// Make the psf the same size as the image
mat psf(Ni, Nj);
psf.zeros();
int ni = pixels.size();
int nj = pixels[0].size();
int m, n;
for(int i=0; i<ni; i++)
{
m = mod(i - ni/2, Ni);
for(int j=0; j<nj; j++)
{
n = mod(j - nj/2, Nj);
psf(m, n) = pixels[i][j];
}
}
fft_of_psf = fft2(psf);
fft_ready = true;
}
void PSF::blur_image(vector< vector<double> >& img) const
{
// Make result image. Assume img is rectangular...
vector< vector<double> > result(img.size(),
vector<double>(img[0].size(), 0.));
int h = size/2;
int ii, jj;
int M = static_cast<int>(img.size());
int N = static_cast<int>(img[0].size());
for(int i=0; i<M; i++)
{
for(int j=0; j<N; j++)
{
if(img[i][j] != 0.)
{
for(int m=0; m<size; m++)
{
ii = i + m - h;
for(int n=0; n<size; n++)
{
jj = j + n - h;
if(ii >= 0 && ii < M &&
jj >= 0 && jj < N)
result[ii][jj] +=
img[i][j]*pixels[m][n];
}
}
}
}
}
img = result;
}
void PSF::blur_image2(vector< vector<double> >& img) const
{
if(!fft_ready)
cerr<<"# Blurring failed."<<endl;
// Copy the image into an Armadillo matrix
mat A(img.size(), img[0].size());
for(size_t i=0; i<img.size(); i++)
for(size_t j=0; j<img[0].size(); j++)
A(i, j) = img[i][j];
// Do the fft of it
cx_mat B = fft2(A);
// Multiply the two ffts
for(size_t i=0; i<img.size(); i++)
for(size_t j=0; j<img[0].size(); j++)
B(i, j) *= fft_of_psf(i, j);
// Do the inverse fft
B = ifft2(B);
// Put back in img
for(size_t i=0; i<img.size(); i++)
for(size_t j=0; j<img[0].size(); j++)
img[i][j] = real(B(i, j));
}
void PSF::test()
{
PSF psf(5);
psf.load("psf.txt");
psf.calculate_fft(20, 20);
// Point image
vector< vector<double> > pixels(20, vector<double>(20, 0.));
pixels[10][10] = 1.;
psf.blur_image(pixels);
// Print image and reset it to zero
for(size_t i=0; i<pixels.size(); i++)
{
for(size_t j=0; j<pixels.size(); j++)
{
cout<<pixels[i][j]<<' ';
pixels[i][j] = 0.;
}
}
cout<<endl;
// Do it again with ffts
pixels[10][10] = 1.;
psf.blur_image2(pixels);
for(size_t i=0; i<pixels.size(); i++)
for(size_t j=0; j<pixels.size(); j++)
cout<<pixels[i][j]<<' ';
cout<<endl;
}
| eggplantbren/TwinPeaks3 | Code/C++/Models/PSF.cpp | C++ | mit | 3,180 |
define([
'knockout'
],function(
ko
){
ko.bindingHandlers.withfirst = {
'init' : function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var savedNodes;
ko.computed(function() {
var dataValue = ko.utils.unwrapObservable(valueAccessor());
var shouldDisplay = typeof dataValue.length == "number" && dataValue.length;
var isFirstRender = !savedNodes;
// Save a copy of the inner nodes on the initial update,
// but only if we have dependencies.
if (isFirstRender && ko.computedContext.getDependenciesCount()) {
savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
}
if (shouldDisplay) {
if (!isFirstRender) {
ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(savedNodes));
}
ko.applyBindingsToDescendants( bindingContext['createChildContext'](dataValue && dataValue[0]), element);
} else {
ko.virtualElements.emptyNode(element);
}
}, null).extend({ rateLimit: 50 });
return { 'controlsDescendantBindings': true };
}
}
}); | ssddi456/ko_custom_bindings | ko.withfirst.js | JavaScript | mit | 1,190 |
var bunyanConfig = require('../index');
var bunyan = require('bunyan');
var path = require('path');
describe('bunyan-config', function () {
it('should not convert things it does not understand', function () {
bunyanConfig({
name: 'test',
streams: [{
path: '/tmp/log.log'
}, {
type: 'raw',
stream: 'unknown'
}],
serializers: 5
}).should.deep.equal({
name: 'test',
streams: [{
path: '/tmp/log.log'
}, {
type: 'raw',
stream: 'unknown'
}],
serializers: 5
});
});
describe('streams', function () {
it('should convert stdout and stderr', function () {
bunyanConfig({
streams: [{
level: 'info',
stream: 'stdout'
}, {
stream: {name: 'stderr'}
}]
}).should.deep.equal({
streams: [{
level: 'info',
stream: process.stdout
}, {
stream: process.stderr
}]
});
});
it('should convert bunyan-logstash', function () {
bunyanConfig({
streams: [{
level: 'error',
type: 'raw',
stream: {
name: 'bunyan-logstash',
params: {
host: 'example.com',
port: 1234
}
}
}]
}).should.deep.equal({
streams: [{
level: 'error',
type: 'raw',
stream: require('bunyan-logstash').createStream({
host: 'example.com',
port: 1234
})
}]
});
});
it('should convert bunyan-redis stream', function () {
var config = bunyanConfig({
streams: [{
type: 'raw',
stream: {
name: 'bunyan-redis',
params: {
host: 'example.com',
port: 1234
}
}
}]
});
config.streams[0].stream.should.be.an.instanceof(require('events').EventEmitter);
config.streams[0].stream._client.host.should.equal('example.com');
config.streams[0].stream._client.port.should.equal(1234);
config.streams[0].stream._client.end();
});
});
describe('serializers', function () {
it('should convert serializers property, if it is a string', function () {
bunyanConfig({
serializers: 'bunyan:stdSerializers'
}).should.deep.equal({
serializers: bunyan.stdSerializers
});
});
it('should not convert serializers, if it is an empty string', function () {
bunyanConfig({
serializers: ''
}).should.deep.equal({
serializers: ''
});
});
it('should convert serializers object', function () {
var absolutePathWithProps = path.resolve(__dirname, './fixtures/dummySerializerWithProps');
var relativePathWithProps = './' + path.relative(process.cwd(), absolutePathWithProps);
var absolutePathWithoutProps = path.resolve(__dirname, './fixtures/dummySerializerWithoutProps');
var relativePathWithoutProps = './' + path.relative(process.cwd(), absolutePathWithoutProps);
bunyanConfig({
serializers: {
moduleWithProps: 'bunyan:stdSerializers.req',
moduleWithoutProps: 'bunyan',
absoluteWithProps: relativePathWithProps + ':c',
relativeWithProps: relativePathWithProps + ':a.b',
absoluteWithoutProps: absolutePathWithoutProps,
relativeWithoutProps: relativePathWithoutProps,
empty: '',
noModuleId: ':abc'
}
}).should.deep.equal({
serializers: {
moduleWithProps: bunyan.stdSerializers.req,
moduleWithoutProps: bunyan,
absoluteWithProps: require('./fixtures/dummySerializerWithProps').c,
relativeWithProps: require('./fixtures/dummySerializerWithProps').a.b,
absoluteWithoutProps: require('./fixtures/dummySerializerWithoutProps'),
relativeWithoutProps: require('./fixtures/dummySerializerWithoutProps'),
empty: '',
noModuleId: ':abc'
}
});
});
});
});
| LSEducation/bunyan-config | test/bunyanConfig.test.js | JavaScript | mit | 5,253 |
/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 3.0 */
package org.cfeclipse.cfml.parser.cfscript;
/**
* This exception is thrown when parse errors are encountered.
* You can explicitly create objects of this exception type by
* calling the method generateParseException in the generated
* parser.
*
* You can modify this class to customize your error reporting
* mechanisms so long as you retain the public fields.
*/
public class ParseException extends Exception {
/**
* This constructor is used by the method "generateParseException"
* in the generated parser. Calling this constructor generates
* a new object of this type with the fields "currentToken",
* "expectedTokenSequences", and "tokenImage" set. The boolean
* flag "specialConstructor" is also set to true to indicate that
* this constructor was used to create this object.
* This constructor calls its super class with the empty string
* to force the "toString" method of parent class "Throwable" to
* print the error message in the form:
* ParseException: <result of getMessage>
*/
public ParseException(Token currentTokenVal,
int[][] expectedTokenSequencesVal,
String[] tokenImageVal
)
{
super("");
specialConstructor = true;
currentToken = currentTokenVal;
expectedTokenSequences = expectedTokenSequencesVal;
tokenImage = tokenImageVal;
}
/**
* The following constructors are for use by you for whatever
* purpose you can think of. Constructing the exception in this
* manner makes the exception behave in the normal way - i.e., as
* documented in the class "Throwable". The fields "errorToken",
* "expectedTokenSequences", and "tokenImage" do not contain
* relevant information. The JavaCC generated code does not use
* these constructors.
*/
public ParseException() {
super();
specialConstructor = false;
}
public ParseException(String message) {
super(message);
specialConstructor = false;
}
/**
* This variable determines which constructor was used to create
* this object and thereby affects the semantics of the
* "getMessage" method (see below).
*/
protected boolean specialConstructor;
/**
* This is the last token that has been consumed successfully. If
* this object has been created due to a parse error, the token
* followng this token will (therefore) be the first error token.
*/
public Token currentToken;
/**
* Each entry in this array is an array of integers. Each array
* of integers represents a sequence of tokens (by their ordinal
* values) that is expected at this point of the parse.
*/
public int[][] expectedTokenSequences;
/**
* This is a reference to the "tokenImage" array of the generated
* parser within which the parse error occurred. This array is
* defined in the generated ...Constants interface.
*/
public String[] tokenImage;
/**
* This method has the standard behavior when this object has been
* created using the standard constructors. Otherwise, it uses
* "currentToken" and "expectedTokenSequences" to generate a parse
* error message and returns it. If this object has been created
* due to a parse error, and you do not catch it (it gets thrown
* from the parser), then this method is called during the printing
* of the final stack trace, and hence the correct error message
* gets displayed.
*/
public String getMessage() {
if (!specialConstructor) {
return super.getMessage();
}
String expected = "";
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
for (int j = 0; j < expectedTokenSequences[i].length; j++) {
expected += tokenImage[expectedTokenSequences[i][j]] + " ";
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected += "...";
}
expected += eol + " ";
}
String retval = "Encountered \"";
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) retval += " ";
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += add_escapes(tok.image);
tok = tok.next;
}
retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
retval += "." + eol;
if (expectedTokenSequences.length == 1) {
retval += "Was expecting:" + eol + " ";
} else {
retval += "Was expecting one of:" + eol + " ";
}
retval += expected;
return retval;
}
/**
* The end of line string for this machine.
*/
protected String eol = System.getProperty("line.separator", "\n");
/**
* Used to convert raw characters to their escaped version
* when these raw version cannot be used as part of an ASCII
* string literal.
*/
protected String add_escapes(String str) {
StringBuffer retval = new StringBuffer();
char ch;
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i))
{
case 0 :
continue;
case '\b':
retval.append("\\b");
continue;
case '\t':
retval.append("\\t");
continue;
case '\n':
retval.append("\\n");
continue;
case '\f':
retval.append("\\f");
continue;
case '\r':
retval.append("\\r");
continue;
case '\"':
retval.append("\\\"");
continue;
case '\'':
retval.append("\\\'");
continue;
case '\\':
retval.append("\\\\");
continue;
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}
continue;
}
}
return retval.toString();
}
}
| cybersonic/org.cfeclipse.cfml | src/org/cfeclipse/cfml/parser/cfscript/ParseException.java | Java | mit | 6,569 |
'use strict';
var http = require('http');
var Logger = require('bunyan');
var log = new Logger({
name: 'test-server',
level: 'debug'
});
var server = http.createServer(function (request) {
var data = '';
log.info({ url: request.url }, 'Incoming Request');
request.on('data', function (chunk) {
data += chunk;
});
throw new Error('expected error');
});
var port = 3000;
server.listen(port);
log.info({
port: port
}, 'listening');
| timemachine3030/jenkman | test/test-server-errors.js | JavaScript | mit | 476 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.12.23 at 08:29:00 AM CST
//
package ca.ieso.reports.schema.iomspublicplannedoutageday;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ConfidentialityClass.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ConfidentialityClass">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="PUB"/>
* <enumeration value="CNF"/>
* <enumeration value="HCNF"/>
* <enumeration value="INT"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "ConfidentialityClass")
@XmlEnum
public enum ConfidentialityClass {
PUB,
CNF,
HCNF,
INT;
public String value() {
return name();
}
public static ConfidentialityClass fromValue(String v) {
return valueOf(v);
}
}
| r24mille/IesoPublicReportBindings | src/main/java/ca/ieso/reports/schema/iomspublicplannedoutageday/ConfidentialityClass.java | Java | mit | 1,298 |
#include "uritests.h"
#include "../guiutil.h"
#include "../walletmodel.h"
#include <QUrl>
void URITests::uriTests()
{
SendCoinsRecipient rv;
QUrl uri;
uri.setUrl(QString("mehcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?req-dontexist="));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("mehcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?dontexist="));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 0);
uri.setUrl(QString("mehcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?label=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString("Wikipedia Example Address"));
QVERIFY(rv.amount == 0);
uri.setUrl(QString("mehcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=0.001"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100000);
uri.setUrl(QString("mehcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1.001"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100100000);
uri.setUrl(QString("mehcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=100&label=Wikipedia Example"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.amount == 10000000000LL);
QVERIFY(rv.label == QString("Wikipedia Example"));
uri.setUrl(QString("mehcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?message=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
QVERIFY(GUIUtil::parseBitcoinURI("mehcoin://LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?message=Wikipedia Example Address", &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
// We currently don't implement the message parameter (ok, yea, we break spec...)
uri.setUrl(QString("mehcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?req-message=Wikipedia Example Address"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("mehcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1,000&label=Wikipedia Example"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("mehcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1,000.0&label=Wikipedia Example"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
}
| bitmagnet/mehcoin | src/qt/test/uritests.cpp | C++ | mit | 2,842 |
#region licence
// =====================================================
// EfSchemeCompare Project - project to compare EF schema to SQL schema
// Filename: DbUpRunner.cs
// Date Created: 2016/04/06
//
// Under the MIT License (MIT)
//
// Written by Jon Smith : GitHub JonPSmith, www.thereformedprogrammer.net
// =====================================================
#endregion
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using DbUp;
using GenericLibsBase;
using GenericLibsBase.Core;
[assembly: InternalsVisibleTo("Tests")]
namespace DbUpHelper
{
public class DbUpRunner
{
public ISuccessOrErrors ApplyMigrations(string dbConnectionString)
{
var status = new SuccessOrErrors();
var upgrader = DeployChanges.To
.SqlDatabase(dbConnectionString)
.WithScriptsAndCodeEmbeddedInAssembly(Assembly.GetExecutingAssembly())
.WithTransaction()
.LogToConsole()
.Build();
var result = upgrader.PerformUpgrade();
if (result.Successful)
{
var msg = result.Scripts.Any()
? "Successfully applied the last " + result.Scripts.Count() + " script(s) to the database."
: "No updates done to database.";
return status.SetSuccessMessage(msg);
}
return status.HasErrors
? status
: status.AddSingleError(result.Error.Message);
}
}
} | JonPSmith/EfSchemaCompare | DbUpHelper/DbUpRunner.cs | C# | mit | 1,582 |
#include "PrimitiveBatch.h"
#include "onut.h"
namespace onut
{
PrimitiveBatch::PrimitiveBatch()
{
// Create a white texture for rendering "without" texture
unsigned char white[4] = {255, 255, 255, 255};
m_pTexWhite = Texture::createFromData({1, 1}, white, false);
auto pDevice = ORenderer->getDevice();
auto pDeviceContext = ORenderer->getDeviceContext();
SVertexP2T2C4 vertices[MAX_VERTEX_COUNT];
// Set up the description of the static vertex buffer.
D3D11_BUFFER_DESC vertexBufferDesc;
vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexBufferDesc.ByteWidth = sizeof(vertices);
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the vertex data.
D3D11_SUBRESOURCE_DATA vertexData;
vertexData.pSysMem = vertices;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
auto ret = pDevice->CreateBuffer(&vertexBufferDesc, &vertexData, &m_pVertexBuffer);
assert(ret == S_OK);
}
PrimitiveBatch::~PrimitiveBatch()
{
if (m_pVertexBuffer) m_pVertexBuffer->Release();
delete m_pTexWhite;
}
void PrimitiveBatch::begin(ePrimitiveType primitiveType, Texture* pTexture, const Matrix& transform)
{
assert(!m_isDrawing); // Cannot call begin() twice without calling end()
if (!pTexture) pTexture = m_pTexWhite;
m_pTexture = pTexture;
m_primitiveType = primitiveType;
ORenderer->setupFor2D(transform);
m_isDrawing = true;
ORenderer->getDeviceContext()->Map(m_pVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &m_pMappedVertexBuffer);
}
void PrimitiveBatch::draw(const Vector2& position, const Color& color, const Vector2& texCoord)
{
SVertexP2T2C4* pVerts = static_cast<SVertexP2T2C4*>(m_pMappedVertexBuffer.pData) + m_vertexCount;
pVerts->position = position;
pVerts->texCoord = texCoord;
pVerts->color = color;
++m_vertexCount;
if (m_vertexCount == MAX_VERTEX_COUNT)
{
if (m_primitiveType == ePrimitiveType::LINE_STRIP)
{
auto lastVert = *pVerts;
flush();
auto pFirstVert = static_cast<SVertexP2T2C4*>(m_pMappedVertexBuffer.pData);
*pFirstVert = lastVert;
++m_vertexCount;
}
else
{
flush();
}
}
}
void PrimitiveBatch::end()
{
assert(m_isDrawing); // Should call begin() before calling end()
m_isDrawing = false;
if (m_vertexCount)
{
flush();
}
ORenderer->getDeviceContext()->Unmap(m_pVertexBuffer, 0);
}
void PrimitiveBatch::flush()
{
if (!m_vertexCount)
{
return; // Nothing to flush
}
auto pDeviceContext = ORenderer->getDeviceContext();
pDeviceContext->Unmap(m_pVertexBuffer, 0);
auto textureView = m_pTexture->getResourceView();
pDeviceContext->PSSetShaderResources(0, 1, &textureView);
switch (m_primitiveType)
{
case ePrimitiveType::POINTS:
pDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);
break;
case ePrimitiveType::LINES:
pDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
break;
case ePrimitiveType::LINE_STRIP:
pDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP);
break;
case ePrimitiveType::TRIANGLES:
pDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
break;
}
pDeviceContext->IASetVertexBuffers(0, 1, &m_pVertexBuffer, &m_stride, &m_offset);
pDeviceContext->Draw(m_vertexCount, 0);
pDeviceContext->Map(m_pVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &m_pMappedVertexBuffer);
m_vertexCount = 0;
}
}
| Daivuk/ggj16 | onut/src/PrimitiveBatch.cpp | C++ | mit | 4,307 |
//
// File: GameController.cpp
// Class: GameController
// Author: John Barbero Unenge
// All code is my own except where credited to others.
//
// Copyright (c) 2012 Catch22. All Rights Reserved.
//
// Date: 24/9/12
//
// License: The following code is licensed under the Catch22-License
//
#include "GameController.hpp"
#include "../Helper/Logger.hpp"
#include "../Helper/InputManager.hpp"
#include "../Helper/Constants.hpp"
#include "../Helper/CoordinatesManager.hpp"
#include "../Helper/CoordinatesManager.hpp"
GameController::GameController(int width, int height, CLTexture* texture)
{
srand ( time(NULL) );
Constants::init(width, height);
m_deviceWidth = width;
m_deviceHeight = height;
m_deviceOrientation = DeviceOrientationLandscapeLeft;
InputManager::getSharedManager()->addInputListener(this);
m_renderer = CreateRendererWithOpenGL10();
m_renderer->init(m_deviceWidth, m_deviceHeight, texture);
m_gameModel = new GameModel();
}
GameController::~GameController()
{
Log(LOG_INFO, "GameController", "Destroyed GameController");
}
void GameController::update(float dt)
{
m_renderer->update(dt);
m_gameModel->update(dt);
CoordinatesManager::getSharedInstance()->updateWorldCoordinate(Vector2d(m_gameModel->getCenterPoint()->m_x, 0.f));
m_renderer->render();
}
void GameController::onRotate(DeviceOrientation orientation)
{
m_deviceOrientation = orientation;
m_renderer->onRotate(m_deviceOrientation);
}
void GameController::didRecieveInputEvent(InputType type, int locX, int locY)
{
int conX, conY;
switch (this->m_deviceOrientation) {
case DeviceOrientationLandscapeLeft:
conX = locY;
conY = locX;
break;
case DeviceOrientationLandscapeRight:
conX = m_deviceHeight - locY;
conY = m_deviceWidth - locX;
break;
}
if (conX < m_deviceHeight * 0.3) {
m_gameModel->playerJump();
} else {
Vector2d worldCoords;
CoordinatesManager::getSharedInstance()->getWorldCoordinates(Vector2d((float)locY / (float)m_deviceHeight * Constants::getGameWidth(), (float)locX / (float)m_deviceWidth * Constants::getGameHeight()), worldCoords);
Log(LOG_INFO, "GameController", generateCString("ScreenCoords: %d, %d",((float)locX / (float)m_deviceWidth * Constants::getGameWidth()), ((float)locY / (float)m_deviceHeight * Constants::getGameHeight())));
Log(LOG_INFO, "GameController", generateCString("WorldCoords: %d, %d",worldCoords.m_x, worldCoords.m_y));
m_gameModel->playerThrowAt(worldCoords.m_x, worldCoords.m_y);
}
Log(LOG_EVENT, "GameController", "DidRecieveInputEvent");
}
| JBarberU/CatchLib | src/Controller/GameController.cpp | C++ | mit | 2,744 |
namespace DrinkAndRate.Web.User
{
using DrinkAndRate.Data;
using DrinkAndRate.Models;
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
public partial class EventCreate : BaseUserPage
{
private IDrinkAndRateData data;
protected void Page_Load(object sender, EventArgs e)
{
var dbContext = new DrinkAndRateDbContext();
this.data = new DrinkAndRateData(dbContext);
}
protected void Submit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
string filePathAndName = string.Empty;
try
{
filePathAndName = FileUploadControl.Upload();
}
catch (InvalidOperationException ex)
{
this.DivLabelErrorMessage.Visible = true;
this.LabelErrorMessage.Text = ex.Message;
return;
}
var loggedInUserName = HttpContext.Current.User.Identity.Name;
var currentUserId = this.data.Users.All().FirstOrDefault(x => x.UserName == loggedInUserName).Id;
var newImage = new Image
{
Path = filePathAndName
};
this.data.Images.Add(newImage);
this.data.SaveChanges();
var newEvent = new Event
{
Title = this.title.Value,
ImageID = newImage.ID,
Location = this.location.Value,
Date = Convert.ToDateTime(this.date.Value),
CreatorID = currentUserId
};
this.data.Events.Add(newEvent);
newEvent.UsersEvents.Add(new UsersEvents
{
UserID = currentUserId,
EventID = newEvent.ID
});
this.data.SaveChanges();
Response.Redirect("~/User/Events");
}
else
{
throw new InvalidOperationException("Error occured while saving the element!");
}
}
}
} | AynRandTelerik/DrinkAndRate | DrinkAndRate.Web/User/EventCreate.aspx.cs | C# | mit | 2,328 |
<?php
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\TestCase;
use Monolog\Logger;
/**
* @covers Monolog\Handler\NullHandler::handle
*/
class NullHandlerTest extends TestCase {
public function testHandle() {
$handler = new NullHandler();
$this->assertTrue($handler->handle($this->getRecord()));
}
public function testHandleLowerLevelRecord() {
$handler = new NullHandler(Logger::WARNING);
$this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG)));
}
}
| Amaire/filmy | vendor/monolog/monolog/tests/Monolog/Handler/NullHandlerTest.php | PHP | mit | 741 |
using BenchmarkDotNet.Attributes;
using Obj2ObjMapBench.Models;
using System.Collections.Generic;
using System.Linq;
namespace Obj2ObjMapBench
{
public abstract class BaseBenchmark
{
const int iterations = 10000;
protected IEnumerable<SimplePoco> _simpleData;
protected IEnumerable<NestedPoco> _nestedData;
[Setup]
public void Setup()
{
GenerateSampleData(iterations);
}
[Benchmark]
public void SimpleMap()
{
for (int i = 0; i < _simpleData.Count(); i++)
Map<SimplePoco, SimplePocoDTO>(_simpleData.ElementAt(i));
}
[Benchmark]
public void NestedMap()
{
for (int i = 0; i < _nestedData.Count(); i++)
Map<NestedPoco, NestedPocoDTO>(_nestedData.ElementAt(i));
}
public abstract TDest Map<TSource, TDest>(TSource source) where TDest : class;
void GenerateSampleData(int iterations)
{
var factory = AutoPoco.AutoPocoContainer.Configure(c =>
{
c.Conventions(o => o.UseDefaultConventions());
c.Include<SimplePoco>()
.Setup(p => p.Id).Use<AutoPoco.DataSources.IntegerIdSource>()
.Setup(p => p.Name).Use<AutoPoco.DataSources.FirstNameSource>()
.Setup(p => p.CreatedOn).Use<AutoPoco.DataSources.DateTimeSource>()
.Setup(p => p.Enabled).Use<AutoPoco.DataSources.BooleanSource>()
.Setup(p => p.Enabled).Use<AutoPoco.DataSources.BooleanSource>()
.Setup(p => p.PhoneNumber).Use<AutoPoco.DataSources.DutchTelephoneSource>()
.Setup(p => p.Town).Use<AutoPoco.DataSources.CitySource>()
.Setup(p => p.ZipCode).Use<AutoPoco.DataSources.PostalSource>()
.Setup(p => p.Address).Use<AutoPoco.DataSources.StreetSource>()
.Setup(p => p.BirthDate).Use<AutoPoco.DataSources.DateOfBirthSource>()
.Setup(p => p.Email).Use<AutoPoco.DataSources.ExtendedEmailAddressSource>();
c.Include<NestedPoco>();
});
var session = factory.CreateSession();
_simpleData = session.Collection<SimplePoco>(iterations);
_nestedData = session.List<NestedPoco>(iterations)
.Impose(o => o.NestedObjects,
session.List<NestedPoco>(5)
.Impose(s => s.NestedObjects,
session.Collection<NestedPoco>(10)).Get())
.Get();
}
}
}
| lusocoding/dotnet-objmap-benchmark | Obj2ObjMapBench/Benchmarks/BaseBenchmark.cs | C# | mit | 2,686 |
import Ember from 'ember';
export default Ember.Component.extend({
actions: {
addFavorite() {
this.sendAction('addFavorite', this.get('newFavorite'));
}
}
});
| fostertheweb/kappa-client | app/components/add-channel-form.js | JavaScript | mit | 178 |
<?php
namespace UserBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* Class User
* @package UserBundle\Entity
* @ORM\Entity(repositoryClass="\UserBundle\Entity\Repository\UserRepository")
* @ORM\Table(name="user", options={"collate"="utf8_general_ci"})
*/
class User implements \Serializable ,UserInterface
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", unique=true)
*/
private $username;
/**
* @ORM\Column(type="string", unique=true)
*/
private $email;
/**
* @ORM\Column(type="string", length=40)
*/
private $password;
/**
* @ORM\Column(type="string")
*/
private $salt;
/**
* @ORM\Column(type="datetime")
*/
private $created;
/**
* @ORM\Column(type="datetime")
*/
private $updated;
/**
* @ORM\Column(type="smallint")
*/
private $status;
/**
* @var \Doctrine\Common\Collections\ArrayCollection
* @ORM\ManyToMany(targetEntity="Role", inversedBy="users", cascade={"persist", "remove"})
* @ORM\JoinTable(name="users_roles")
*/
private $roles;
/**
* @ORM\OneToOne(targetEntity="UserAccount", mappedBy="user", cascade={"persist", "remove"})
*/
private $account;
/**
* @ORM\OneToMany(targetEntity="BlogBundle\Entity\Blog", mappedBy="user")
*/
protected $blogs;
/**
* @ORM\OneToMany(targetEntity="BlogBundle\Entity\Comment", mappedBy="user")
*/
protected $comments;
public function __construct()
{
$this->roles = new ArrayCollection();
$this->salt = md5(uniqid(null, TRUE));
$this->username = md5(uniqid(null, TRUE));
$this->created = new \DateTime();
$this->updated = new \DateTime();
$this->status = 1;
$this->blogs = new ArrayCollection();
}
public function serialize()
{
return serialize(array(
$this->id,
$this->username
));
}
public function unserialize($serialized)
{
list($this->id, $this->username) = unserialize($serialized);
}
public function getRoles()
{
return $this->roles->toArray();
}
public function getPassword()
{
return $this->password;
}
public function getSalt()
{
return $this->salt;
}
public function getUsername()
{
return $this->username;
}
public function eraseCredentials()
{
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* @param string $username
*
* @return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Set email
*
* @param string $email
*
* @return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set password
*
* @param string $password
*
* @return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Set salt
*
* @param string $salt
*
* @return User
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Set created
*
* @param \DateTime $created
*
* @return User
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* @return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set updated
*
* @param \DateTime $updated
*
* @return User
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* @return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set status
*
* @param integer $status
*
* @return User
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* @return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Add role
*
* @param \UserBundle\Entity\Role $role
*
* @return User
*/
public function addRole(\UserBundle\Entity\Role $role)
{
$this->roles[] = $role;
return $this;
}
/**
* Remove role
*
* @param \UserBundle\Entity\Role $role
*/
public function removeRole(\UserBundle\Entity\Role $role)
{
$this->roles->removeElement($role);
}
/**
* Set account
*
* @param \UserBundle\Entity\UserAccount $account
*
* @return User
*/
public function setAccount(\UserBundle\Entity\UserAccount $account = null)
{
$this->account = $account;
$account->setUser($this);
return $this;
}
/**
* Get account
*
* @return \UserBundle\Entity\UserAccount
*/
public function getAccount()
{
return $this->account;
}
public function getFullname()
{
$fullname = $this->getAccount()->getFirstName();
$lastname = $this->getAccount()->getLastName();
if($lastname){
$fullname = $fullname." ".$lastname;
}
return $fullname;
}
/**
* Add blog
*
* @param \BlogBundle\Entity\Blog $blog
*
* @return User
*/
public function addBlog(\BlogBundle\Entity\Blog $blog)
{
$this->blogs[] = $blog;
return $this;
}
/**
* Remove blog
*
* @param \BlogBundle\Entity\Blog $blog
*/
public function removeBlog(\BlogBundle\Entity\Blog $blog)
{
$this->blogs->removeElement($blog);
}
/**
* Get blogs
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getBlogs()
{
return $this->blogs;
}
}
| moroztaras/symfony_blog.dev | src/UserBundle/Entity/User.php | PHP | mit | 6,624 |
package sprites;
public class Enemy extends Paddle
{
public Enemy(int x, int y)
{
super(x,y);
}
int updateFrameCounter = 0;
float moveDirection = 0;
public void update(float dt, Ball ball)
{
//if(++updateFrameCounter%3==0)
//{
updateFrameCounter = 0;
if(position.y < ball.position.y)
moveDirection = 1;
else if (position.y > ball.position.y)
moveDirection = -1;
else
moveDirection = 0;
//}
setVVelocity(moveDirection, dt);
position.add(velocity.x, velocity.y);
bounds.setPosition(position.x, position.y);
}
} | lightofanima/GameDevelopmentTutorial | Pong/core/src/sprites/Enemy.java | Java | mit | 564 |
namespace StreetPacMan.Server
{
public class InitialApple
{
public AppleKind Type = AppleKind.Normal;
public double Lon;
public double Lat;
public override string ToString()
{
return string.Format("{0} apple at ({1}, {2})", Type, Lat, Lon);
}
}
} | QuickUnit/PacmanTlv | StreetPacMan.Server/InitialApple.cs | C# | mit | 322 |
'''
Created on Nov 19, 2011
@author: scottporter
'''
class BaseSingleton(object):
_instance = None
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance | freneticmonkey/epsilonc | resources/scripts/core/basesingleton.py | Python | mit | 263 |
(function ($) {
'use strict';
// Device check for limiting resize handling.
var IS_DEVICE = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
function FullHeight(el, options) {
this.el = $(el);
var data = {};
$.each(this.el.data(), function (attr, value) {
if (/^fullheight/.test(attr)) {
var key = attr.replace('fullheight', '').toLowerCase();
data[key] = value;
}
});
options = $.extend({}, FullHeight.defaults, options, data);
this.debug = options.debug;
this.container = $(options.container);
this.property = options.property;
this.propertyBefore = this.el.css(this.property);
// Chrome for Android resizes the browser a lot when scrolling due to the address bar collapsing.
// This causes a lot of arbitrary layout jumps and slow image resize operations with this plugin.
// So for device UA where height should not change, we only update if the width changes as well (f.ex.
// orientation changes).
this.allowDeviceHeightResize = !(
options.allowDeviceHeightResize === null ||
options.allowDeviceHeightResize === false ||
options.allowDeviceHeightResize === 'false'
);
this.lastWidth = this.container.innerWidth();
this.timerResize = 0;
this.container.on('resize.yrkup3.fullheight', $.proxy(this, '_onResize'));
this.update();
}
FullHeight.defaults = {
debug: false,
allowDeviceHeightResize: false,
container: window,
property: 'min-height'
};
FullHeight.prototype._onResize = function () {
var newWidth = this.container.innerWidth();
var allowResize = !IS_DEVICE || this.allowDeviceHeightResize || newWidth !== this.lastWidth;
// Do the update if expected.
if (allowResize) {
var root = this;
clearTimeout(this.timerResize);
this.timerResize = setTimeout(function () {
root.update();
}, 200);
}
this.lastWidth = newWidth;
};
FullHeight.prototype.update = function () {
if (this.debug) {
console.log('update', this.el);
}
var newHeight;
var offset = this.container.offset();
if (typeof offset == 'undefined') {
newHeight = $(window).innerHeight();
} else {
newHeight = this.container.innerHeight() - (this.el.offset().top - offset.top);
}
if (newHeight !== this.lastHeight) {
if (this.debug) {
console.log('set `' + this.property + '` to ' + newHeight);
}
this.el.css(this.property, newHeight);
this.lastHeight = newHeight;
}
};
FullHeight.prototype.dispose = function () {
if (this.debug) {
console.log('dispose');
}
this.container.off('.yrkup3.fullheight');
this.el.css(this.property, this.propertyBefore);
};
$.fn.fullheight = function (options) {
this.each(function () {
var el = $(this);
// Store data
var data = el.data('yrkup3.fullheight');
if (!data) {
el.data('yrkup3.fullheight', (data = new FullHeight(el, options)));
}
// Run command
if (typeof options == 'string') {
data[options]();
}
});
return this;
};
})(jQuery);
| yrkup3/jquery-fullheight | src/jquery-fullheight.js | JavaScript | mit | 2,998 |
require 'spec_helper'
require 'rspec'
require 'active_model'
class RegonBastard
include ActiveModel::Validations
attr_accessor :regon
validates :regon, :presence => true, :regon => true
end
describe RegonValidator do
before :each do
@model = RegonBastard.new
end
it "should be valid" do
@model.should_not be_valid
@model.regon = '590096454'
@model.should be_valid
end
it "should be invalid" do
@model.should_not be_valid
@model.regon = '590096453'
@model.should_not be_valid
end
it "should be valid 14-digit regon" do
@model.should_not be_valid
@model.regon = '12345678512347'
@model.should be_valid
end
it "should be invalid 14-digit regon" do
@model.should_not be_valid
@model.regon = '12345678512348'
@model.should_not be_valid
end
end
| zaiste/valideez | spec/regon_validator_spec.rb | Ruby | mit | 829 |
<?php
namespace Modules\Dynamicfield\Composers;
use Illuminate\Contracts\View\View;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Dynamicfield\Utility\DynamicFields;
use Request;
use Route;
class FrontendViewComposer
{
/**
* @param View $view
*/
public function compose(View $view)
{
$this->assignDynamicFieldsToPageObject($view);
}
/**
* @param $view
*
* @return mixed
*/
private function assignDynamicFieldsToPageObject($view)
{
$arrAllow = ['page', 'homepage',"en.blog.slug"];
$data = $view->getData();
$routName = Route::currentRouteName();
if (in_array($routName, $arrAllow)) {
$arrType = config('asgard.dynamicfield.config.entity-type');
$arrType = array_keys($arrType);
if (count($data)) {
foreach ($data as $item) {
if (is_object($item)) {
$className = get_class($item);
if (in_array($className, $arrType)) {
$locale = LaravelLocalization::getCurrentLocale();
$request = Request::all();
$dynamicFields = new DynamicFields($item, $locale);
$dynamicFields->init($request);
$fieldValues = $dynamicFields->getFieldValues($locale);
$view->with('dynamicfields', $fieldValues);
}
}
}
}
}
return $view;
}
}
| stone-lab/Dynamicfield | Composers/FrontendViewComposer.php | PHP | mit | 1,619 |
<?php
use Beanbun\Beanbun;
use JonnyW\PhantomJs\Client;
require_once(__DIR__ . '/vendor/autoload.php');
$beanbun = new Beanbun;
$beanbun->name = 'phantom';
$beanbun->count = 5;
$beanbun->interval = 2;
$beanbun->timeout = 10;
$beanbun->seed = [
'https://www.zhihu.com/question/23660494',
'https://www.zhihu.com/question/23010225',
];
$beanbun->logFile = __DIR__ . '/phantom_access.log';
$beanbun->downloadPage = function ($beanbun) {
$client = Client::getInstance();
$client->getEngine()->setPath('/Users/kiddyu/Documents/phantomjs/bin/phantomjs');
$width = 1440;
$height = 6000;
$top = 0;
$left = 0;
$request = $client->getMessageFactory()->createCaptureRequest($beanbun->url, $beanbun->method, 6000);
$request->setOutputFile('zhihu_test_' . md5($beanbun->url) .'.jpg');
$request->setViewportSize($width, $height);
$request->setCaptureDimensions($width, $height, $top, $left);
$response = $client->getMessageFactory()->createResponse();
$client->send($request, $response);
$worker_id = $beanbun->daemonize ? $this->id : '';
$beanbun->log("Beanbun worker {$worker_id} download {$beanbun->url} success.");
};
$beanbun->discoverUrl = function () {};
$beanbun->start();
| kiddyuchina/Beanbun | examples/phantomjs.php | PHP | mit | 1,249 |
/**
* Copyright (c) 2013-2014 Quentin Smetz <qsmetz@gmail.com>, Sebastien
* Jodogne <s.jodogne@gmail.com>
*
* 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.
**/
//!
//! \file ViewConfiguration.cpp
//! \brief The ViewConfiguration.cpp file contains the definition of non-inline
//! methods of the ViewConfiguration class.
//!
//! \author Quentin Smetz
//!
#include "ViewConfiguration.h"
using namespace std;
// Constructor
ViewConfiguration::ViewConfiguration()
{}
// Destructor
ViewConfiguration::~ViewConfiguration()
{}
// The 'setHounsfield' method
void ViewConfiguration::setHounsfield(Range const& hounsfield, Range const& hounsfieldMaxRange)
{
m_hounsfield = hounsfield;
m_hounsfieldMaxRange = hounsfieldMaxRange;
}
// The 'setColormap' method
void ViewConfiguration::setColormap(Colormap const& colormap)
{
m_colormap = colormap;
}
// The 'setTranslation' method
void ViewConfiguration::setTranslation(Vector3D const& translation)
{
m_translation = translation;
}
// The 'setRotation' method
void ViewConfiguration::setRotation(Vector3D const& rotation)
{
m_rotation = rotation;
}
| npettiaux/orthanc-viewer | Code/Model/ViewConfiguration.cpp | C++ | mit | 2,158 |
module Andrake::Generator
autoload :Rakefile, 'andrake/generator/rakefile'
end
| masarakki/andrake | lib/andrake/generator.rb | Ruby | mit | 81 |
<?php
function old_width($left, $right) {
$width = 540;
if (!$left ) {
$width = $width +190;
}
if (!$right) {
$width = $width +190;
}
return $width;
}
/**
* Return a themed breadcrumb trail.
*
* @param $breadcrumb
* An array containing the breadcrumb links.
* @return a string containing the breadcrumb output.
*/
function phptemplate_breadcrumb($breadcrumb) {
if (!empty($breadcrumb)) {
$breadcrumb[] = drupal_get_title();
array_shift($breadcrumb);
return '<div class="path"><p><span>'.t('You are here').'</span>'. implode(' / ', $breadcrumb) .'</p></div>';
}
}
| thomasturnbull/nycwhisky-angular | app/sites/nycwhisky.com/themes/old/template.php | PHP | mit | 628 |
using System;
namespace RecoTwAPI
{
[Serializable]
public class RecoTwException : Exception
{
public RecoTwException(ErrorCollection errors)
{
this.Errors = errors;
}
public ErrorCollection Errors { get; set; }
}
}
| atst1996/RecoTwAPI | RecoTwException.cs | C# | mit | 235 |
var _ = require('lodash'),
restify = require('restify'),
async = require('async');
module.exports = function(settings, server, db){
var globalLogger = require(settings.path.root('logger'));
var auth = require(settings.path.lib('auth'))(settings, db);
var api = require(settings.path.lib('api'))(settings, db);
var vAlpha = function(path){ return {path: path, version: settings.get("versions:alpha")} };
function context(req){
return {logger: req.log};
}
server.get(vAlpha('/ping'), function(req, res, next){
res.json();
next();
});
/**
* API to create or update an email template. If a template exists (accountId + Name pair), it will be updated. Otherwise a new one will be created
*/
server.post(vAlpha('/email/:name'), auth, function(req, res, next){
var logger = req.log || globalLogger;
var params = req.params;
if (!params || !params.name || !params.htmlData || !params.htmlType || !params.cssData || !params.cssType){
var err = new restify.BadRequestError("Invalid arguments");
logger.info(err, params);
return res.send(err);
}
api.email.createOrUpdate.call(context(req), params.accountId, params.name, params.htmlData, params.htmlType, params.cssData, params.cssType, function(err){
if (err) {
logger.error(err);
res.send(new restify.InternalServerError("Something went wrong"));
}
else {
res.json();
}
next();
});
});
server.put(vAlpha('/trigger/:name/on/event'), auth, function(req, res, next){
var logger = req.log || globalLogger;
var params = req.params;
if (!params.accountId || !params.name || !params.actionId || !params.eventName) {
var err = new restify.BadRequestError("Invalid arguments");
logger.info(err, params);
return res.send(err);
}
var eventCondition = {
name: params.eventName,
attrs: params.eventAttrs
};
api.trigger.create.call(context(req),
params.accountId, params.name, eventCondition, null, params.actionId,
function(err, triggerDoc){
if (err){
logger.error(err);
res.send(new restify.InternalServerError("Something went wrong"));
}
else {
res.json({id: triggerDoc.id})
}
next();
})
});
server.put(vAlpha('/trigger/:name/on/time'), auth, function(req, res, next){
var logger = req.log || globalLogger;
var params = req.params;
if (!params.accountId || !params.name || !params.actionId || (!params.next && !params.every)) {
var err = new restify.BadRequestError("Invalid arguments");
logger.info(err, params);
return res.send(err);
}
var timeCondition = {
next: params.next,
every: params.every
};
api.trigger.create.call(context(req),
params.accountId, params.name, null, timeCondition, params.actionId,
function(err, triggerDoc){
if (err){
logger.error(err);
res.send(new restify.InternalServerError("Something went wrong"));
}
else {
res.json({id: triggerDoc.id})
}
next();
})
});
server.post(vAlpha('/event/:name'), auth, function(req, res, next){
var logger = req.log || globalLogger;
var params = req.params;
if (!params.accountId || !params.name || !params.userId){
var err = restify.BadRequestError("Invalid Arguments");
logger.info(err, params);
return res.send(err);
}
api.event.add.call(context(req),
params.accountId, params.name, params.userId, params.attrs,
function(err){
if (err){
logger.error(err);
res.send(new restify.InternalServerError("Something went wrong"));
}
else {
res.send();
}
next();
});
});
};
| prokilogrammer/keet | routes.js | JavaScript | mit | 4,425 |
using Ghost.Server.Mgrs.Map;
using PNetR;
using System;
using System.Numerics;
namespace Ghost.Server.Utilities.Abstracts
{
public abstract class CreatureObject : WorldObject
{
protected bool _dead;
protected StatsMgr _stats;
protected NetworkView _view;
protected MovementGenerator _movement;
public bool IsDead
{
get { return _dead; }
}
public Player Owner
{
get { return _view.Owner; }
}
public bool HasStats
{
get { return _stats != null; }
}
public StatsMgr Stats
{
get { return _stats; }
}
public NetworkView View
{
get { return _view; }
}
public override ushort SGuid
{
get
{
return _view.Id.Id;
}
}
public override Vector3 Position
{
get { return _movement.Position; }
set { _movement.Position = value; }
}
public override Vector3 Rotation
{
get { return _movement.Rotation; }
set { _movement.Rotation = value; }
}
public MovementGenerator Movement
{
get { return _movement; }
}
public abstract Vector3 SpawnPosition
{
get;
}
public abstract Vector3 SpawnRotation
{
get;
}
public event Action<CreatureObject> OnKilled;
public CreatureObject(uint guid, ObjectsMgr manager)
: base(Constants.CreatureObject | guid, manager)
{
OnSpawn += CreatureObject_OnSpawn;
OnDespawn += CreatureObject_OnDespawn;
OnDestroy += CreatureObject_OnDestroy;
OnInitialize += CreatureObject_OnInitialize;
}
public void Kill(CreatureObject killer)
{
lock (this)
{
if (_dead) return;
_dead = true;
}
OnKilled?.Invoke(killer);
}
#region Events Handlers
private void CreatureObject_OnSpawn()
{
_dead = false;
}
private void CreatureObject_OnDespawn()
{
_view.ClearSubscriptions();
_server.Room.Destroy(_view, IsPlayer ? Constants.Fainted : Constants.Killed);
}
private void CreatureObject_OnDestroy()
{
_view.ClearSubscriptions();
_server.Room.Destroy(_view, _dead ? Constants.Killed : (byte)0);
_view = null;
_stats = null;
_movement = null;
}
private void CreatureObject_OnInitialize()
{
_stats = GetComponent<StatsMgr>();
_movement = GetComponent<MovementGenerator>();
}
#endregion
}
} | Ignis34Rus/LoE-Ghost.Server | Ghost.Server/Utilities/Abstracts/CreatureObject.cs | C# | mit | 2,904 |
/*******************************************************************************
* Manchester Centre for Integrative Systems Biology
* University of Manchester
* Manchester M1 7ND
* United Kingdom
*
* Copyright (C) 2008 University of Manchester
*
* This program is released under the Academic Free License ("AFL") v3.0.
* (http://www.opensource.org/licenses/academic.php)
*******************************************************************************/
package org.mcisb.subliminal.metacyc;
import java.io.*;
import java.util.*;
import org.mcisb.subliminal.*;
import org.mcisb.subliminal.model.*;
import org.mcisb.subliminal.sbml.*;
import org.sbml.jsbml.*;
/**
* @author Neil Swainston
*/
public class MetaCycExtracter extends Extracter
{
/**
*
*/
private final static String COMPARTMENT_SUFFIX = "_CCO_"; //$NON-NLS-1$
/**
*
*/
private final static String MXN_REF_PREFIX = "metacyc:"; //$NON-NLS-1$
/**
*
* @param taxonomyId
* @param outFile
* @param metaCycDirectory
* @throws Exception
*/
public static void run( final String taxonomyId, final File outFile, final File metaCycDirectory ) throws Exception
{
final String taxonomyName = SubliminalUtils.getTaxonomyName( taxonomyId );
if( taxonomyName == null )
{
throw new UnsupportedOperationException( "MetaCyc data unavailable for NCBI Taxonomy id " + taxonomyId ); //$NON-NLS-1$
}
final SBMLDocument document = initDocument( taxonomyId );
run( taxonomyId, taxonomyName, document, metaCycDirectory, false );
XmlFormatter.getInstance().write( document, outFile );
SbmlFactory.getInstance().unregister();
}
/**
*
* @param taxonomyId
* @param outFile
* @throws Exception
*/
public static void run( final String taxonomyId, final File outFile ) throws Exception
{
final SBMLDocument document = initDocument( taxonomyId );
run( taxonomyId, document );
XmlFormatter.getInstance().write( document, outFile );
SbmlFactory.getInstance().unregister();
}
/**
*
* @param taxonomyId
* @param document
* @throws Exception
*/
public static void run( final String taxonomyId, final SBMLDocument document ) throws Exception
{
final String taxonomyName = SubliminalUtils.getTaxonomyName( taxonomyId );
if( taxonomyName == null )
{
throw new UnsupportedOperationException( "MetaCyc data unavailable for NCBI Taxonomy id " + taxonomyId ); //$NON-NLS-1$
}
final File tempDirectory = new File( System.getProperty( "java.io.tmpdir" ) ); //$NON-NLS-1$
run( taxonomyId, taxonomyName, document, new File( tempDirectory, taxonomyName ), true );
}
/**
*
* @param taxonomyId
* @param document
* @param metaCycDirectory
* @throws Exception
*/
private static void run( final String taxonomyId, final String taxonomyName, final SBMLDocument document, final File metaCycDirectory, final boolean deleteSource ) throws Exception
{
try
{
final File metaCycSource = MetaCycDownloader.getMetaCycSource( metaCycDirectory, taxonomyName );
final File sbml = SubliminalUtils.find( metaCycSource, "metabolic-reactions.sbml" ); //$NON-NLS-1$
if( sbml != null )
{
System.out.println( "MetaCyc: " + taxonomyName ); //$NON-NLS-1$
final MetaCycFactory metaCycFactory = initFactory( metaCycSource );
final SBMLDocument inDocument = new SBMLReader().readSBML( sbml );
final Model inModel = inDocument.getModel();
for( int l = 0; l < inModel.getNumReactions(); l++ )
{
final Reaction inReaction = inModel.getReaction( l );
final Reaction outReaction = addReaction( document.getModel(), inReaction, taxonomyId, metaCycFactory );
if( inReaction.isSetReversible() )
{
outReaction.setReversible( inReaction.getReversible() );
}
}
final Collection<Object[]> resources = new ArrayList<>();
resources.add( new Object[] { "http://identifiers.org/biocyc/" + metaCycFactory.getOrganismId(), CVTerm.Qualifier.BQB_IS_DESCRIBED_BY } ); //$NON-NLS-1$
resources.add( new Object[] { "http://identifiers.org/pubmed/10592180", CVTerm.Qualifier.BQB_IS_DESCRIBED_BY } ); //$NON-NLS-1$
addResources( inModel, resources );
}
if( deleteSource )
{
SubliminalUtils.delete( metaCycSource );
}
}
catch( FileNotFoundException e )
{
e.printStackTrace();
}
}
/**
*
* @param source
* @return MetaCycReactionsParser
*/
private static MetaCycFactory initFactory( final File source )
{
final File versionFile = SubliminalUtils.find( source, "version.dat" ); //$NON-NLS-1$
final File reactionsFile = SubliminalUtils.find( source, "reactions.dat" ); //$NON-NLS-1$
final File enzymesFile = SubliminalUtils.find( source, "enzymes.col" ); //$NON-NLS-1$
return new MetaCycFactory( versionFile, reactionsFile, enzymesFile );
}
/**
*
* @param outModel
* @param inReaction
* @param taxonomyId
* @param metaCycEnzymeFactory
* @param resources
* @return Reaction
* @throws Exception
*/
private static Reaction addReaction( final Model outModel, final Reaction inReaction, final String taxonomyId, final MetaCycFactory metaCycEnzymeFactory ) throws Exception
{
final String inReactionId = inReaction.getId();
Reaction outReaction = addReaction( outModel, getId( inReactionId ), DEFAULT_COMPARTMENT_ID );
if( outReaction == null )
{
outReaction = outModel.createReaction();
outReaction.setId( inReactionId );
outReaction.setName( inReaction.getName() );
for( int l = 0; l < inReaction.getNumReactants(); l++ )
{
final SpeciesReference inReactant = inReaction.getReactant( l );
final SpeciesReference outReactant = outReaction.createReactant();
final String speciesId = inReactant.getSpecies();
final Species outSpecies = addSpecies( outModel, getId( speciesId ), inReaction.getModel().getSpecies( speciesId ).getName(), DEFAULT_COMPARTMENT_ID, SubliminalUtils.SBO_SIMPLE_CHEMICAL );
outReactant.setSpecies( outSpecies.getId() );
outReactant.setStoichiometry( inReactant.getStoichiometry() );
}
for( int l = 0; l < inReaction.getNumProducts(); l++ )
{
final SpeciesReference inProduct = inReaction.getProduct( l );
final SpeciesReference outProduct = outReaction.createProduct();
final String speciesId = inProduct.getSpecies();
final Species outSpecies = addSpecies( outModel, getId( speciesId ), inReaction.getModel().getSpecies( speciesId ).getName(), DEFAULT_COMPARTMENT_ID, SubliminalUtils.SBO_SIMPLE_CHEMICAL );
outProduct.setSpecies( outSpecies.getId() );
outProduct.setStoichiometry( inProduct.getStoichiometry() );
}
}
final Map<String,Integer> enzymes = metaCycEnzymeFactory.getEnzymes( inReactionId );
final String[] enzymeIds = enzymes.keySet().toArray( new String[ enzymes.keySet().size() ] );
for( String enzymeId : enzymeIds )
{
final String formattedEnzymeId = "MetaCyc:" + MetaCycUtils.unencode( enzymeId ); //$NON-NLS-1$
final List<String[]> results = SubliminalUtils.searchUniProt( SubliminalUtils.encodeUniProtSearchTerm( formattedEnzymeId ) + "+AND+taxonomy:" + taxonomyId );//$NON-NLS-1$
addEnzymes( outReaction, results, SubliminalUtils.getNormalisedId( formattedEnzymeId ), enzymeId, new ArrayList<Object[]>() );
}
return outReaction;
}
/**
*
* @param id
* @return String
*/
private static String getId( final String id )
{
String formattedId = id;
if( formattedId.contains( COMPARTMENT_SUFFIX ) )
{
formattedId = formattedId.substring( 0, id.indexOf( COMPARTMENT_SUFFIX ) );
}
return MXN_REF_PREFIX + MetaCycUtils.unencode( formattedId );
}
/**
* @param args
* @throws Exception
*/
public static void main( String[] args ) throws Exception
{
if( args.length == 2 )
{
MetaCycExtracter.run( args[ 0 ], new File( args[ 1 ] ) );
}
else if( args.length == 3 )
{
MetaCycExtracter.run( args[ 0 ], new File( args[ 1 ] ), new File( args[ 2 ] ) );
}
}
} | mcisb/SuBliMinaLToolbox | src/main/java/org/mcisb/subliminal/metacyc/MetaCycExtracter.java | Java | mit | 7,913 |
'use strict';
/**
* @ngdoc directive
* @name SubSnoopApp.directive:pieChart
* @description
* # pieChart
*/
angular.module('SubSnoopApp')
.directive('donutChart', ['d3Service', '$window', '$document', 'subFactory', '$filter', 'moment', 'sentiMood', 'reaction',
function (d3Service, $window, $document, subFactory, $filter, moment, sentiMood, reaction) {
/*
Based on http://embed.plnkr.co/YICxe0/
*/
var windowWidth = $window.innerWidth;
var $win = angular.element($window);
return {
restrict: 'EA',
replace: true,
scope: true,
link: function(scope, element, attrs) {
scope.chartReady = false;
scope.loaderImg = '../images/103.gif';
var subname = scope.subreddit;
d3Service.d3().then(function(d3) {
/*
Set dimensions for pie charts
*/
var height;
if (attrs.type === 'sentiment' || attrs.type === 'reaction') {
height = 375;
} else {
height = 475;
}
function configChart(scope_chart, window_width) {
if (window_width < 700) {
scope_chart = setChartConfig(300);
} else {
scope_chart = setChartConfig(260);
}
return scope_chart;
}
/*
Default configuration for pie chart
*/
function setChartConfig(chart_width) {
return {
width: chart_width,
height: height,
thickness: 30,
grow: 10,
labelPadding: 35,
duration: 0,
margin: {
top: 50, right: 50, bottom: -50, left: 50
}
};
};
function init() {
// --------------------------------------------------------
/*
Get data to populate pie charts
*/
var user;
var chartData;
var d3ChartEl;
// --------------------------------------------------------
scope.getChart = function() {
d3ChartEl = d3.select(element[0]);
user = subFactory.getUser();
if (subname && attrs.type === 'sentiment') {
sentiMood.setSubData(subname, subFactory.getEntries(subname, null), user);
chartData = sentiMood.getData(subname);
} else if (subname && attrs.type === 'reaction') {
reaction.setSubData(subname, subFactory.getEntries(subname, null), user);
chartData = reaction.getData(subname);
}
scope.chartReady = true;
scope.chartConfig = configChart(scope.chartConfig, windowWidth);
var w = angular.element($window);
scope.getWindowDimensions = function () {
return {
'w': w.width()
};
};
try {
drawChart(chartData, scope.chartConfig);
w.bind('resize', function() {
scope.$apply();
drawChart(chartData, scope.chartConfig);
});
} catch(error) {
console.log(error);
}
}
}
/*
Draw the pie chart with center text and mouse over events
*/
function drawChart(chartData, chartConfig) {
var width = chartConfig.width,
height = chartConfig.height,
margin = chartConfig.margin,
grow = chartConfig.grow,
labelRadius,
radius,
duration = chartConfig.duration;
width = width - margin.left - margin.right;
height = height - margin.top - margin.bottom,
radius = Math.min(width, height) / 2,
labelRadius = radius + chartConfig.labelPadding;
var thickness = chartConfig.thickness || Math.floor(radius / 5);
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius - thickness);
var arcOver = d3.svg.arc()
.outerRadius(radius + grow)
.innerRadius(radius - thickness);
var pieFn = d3.layout.pie()
.sort(null)
.value(function(d) {
return d.value;
});
var centerValue = (!!chartData.center.value) ? chartData.center.value : '';
var centerValue2 = (!!chartData.center.value2) ? chartData.center.value2 : '';
var d3ChartEl = d3.select(element[0]);
d3ChartEl.select('svg').remove();
var gRoot = d3ChartEl.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g');
gRoot.attr('transform', 'translate(' + (width / 2 + margin.left) + ',' + (height / 2 + margin.top) + ')');
var middleCircle = gRoot.append('svg:circle')
.attr('cx', 0)
.attr('cy', 0)
.attr('r', radius)
.style('fill', '#1F2327');
/*
Display percentage and center text statistics when hovering over an arc
*/
scope.mouseOverPath = function(d) {
d3.select(this)
.transition()
.duration(duration)
.each("end", function(d) {
d3.select('.center-value-' + attrs.type).text(d.data.label);
var line1;
if (attrs.type === 'upvotes') {
line1 = 'Points: ' + $filter('number')(d.data.value);
} else {
line1 = 'Entries: ' + $filter('number')(d.data.value);
}
d3.select('.line-1-' + attrs.type)
.text(line1);
d3.selectAll('.arc-' + attrs.type + ' .legend .percent')
.transition()
.duration(duration)
.style('fill-opacity', 0);
d3.select(this.parentNode).select('.legend .percent')
.transition()
.duration(duration)
.style("fill-opacity", 1);
d3.selectAll('.arc-' + attrs.type).style('opacity', function(e) {
return e.data.label === d.data.label ? '1' : '0.3';
});
})
.attr("d", arcOver);
};
/*
Shrink the arc back to original width of pie chart ring
*/
scope.reduceArc = function(d) {
try {
if (d) {
d3.select(this)
.transition()
.attr("d", arc);
} else {
d3.selectAll('.arc-' + attrs.type + ' path')
.each(function() {
d3.select(this)
.transition()
.attr("d", arc);
});
}
} catch(error) {
console.log("Error: " + error);
}
}
/*
The state of the chart when the mouse is not hovered over it
*/
scope.restoreCircle = function() {
d3.selectAll('.arc-' + attrs.type).style('opacity', '1');
d3.select('.center-value-' + attrs.type).text(centerValue);
d3.select('.line-1-' + attrs.type).text(centerValue2);
d3.selectAll('.arc-' + attrs.type + ' .legend .percent')
.transition()
.duration(duration)
.style("fill-opacity", 0);
scope.reduceArc();
};
gRoot.on('mouseleave', function(e) {
if (!e) {
scope.restoreCircle();
}
});
middleCircle.on('mouseover', function() {
scope.restoreCircle();
});
var arcs = gRoot.selectAll('g.arc')
.data(pieFn(chartData.values))
.enter()
.append('g')
.attr('class', 'arc-' + attrs.type);
var partition = arcs.append('svg:path')
.style('fill', function(d) {
return chartData.colors[d.data.label];
})
.on("mouseover", scope.mouseOverPath)
.each(function() {
this._current = {
startAngle: 0,
endAngle: 0
};
})
.on("mouseleave", scope.reduceArc)
.attr('d', arc)
.transition()
.duration(duration)
.attrTween('d', function(d) {
try {
var interpolate = d3.interpolate(this._current, d);
this._current = interpolate(0);
return function(t) {
return arc(interpolate(t));
};
} catch(error) {
console.log(e);
}
});
/*
Set up center text for pie chart with name of chart and number of posts
*/
var centerText = gRoot.append('svg:text')
.attr('class', 'center-label');
var titleSize = '14px';
var dataSize = '14px';
centerText.append('tspan')
.text(centerValue)
.attr('x', 0)
.attr('dy', '0em')
.attr("text-anchor", "middle")
.attr("class", 'center-value-' + attrs.type)
.attr("font-size", titleSize)
.attr("fill", "#fff")
.attr("font-weight", "bold");
centerText.append('tspan')
.text(centerValue2)
.attr('x', 0)
.attr('dy', '1em')
.attr("text-anchor", "middle")
.attr("class", 'line-1-' + attrs.type)
.attr("font-size", dataSize)
.attr("fill", "#9099A1")
.attr("font-weight", "400");
var percents = arcs.append("svg:text")
.style('fill-opacity', 0)
.attr('class', 'legend')
.attr("transform", function(d) {
var c = arc.centroid(d),
x = c[0],
y = c[1],
height = Math.sqrt(x * x + y * y);
return "translate(" + ((x-13) / height * labelRadius) + ',' +
((y+5) / height * labelRadius) + ")";
});
percents.append('tspan')
.attr('class', 'percent')
.attr('x', 0)
.attr('font-size', '13px')
.attr('font-weight', '400')
.attr('fill', '#fff')
.style("fill-opacity", 0)
.text(function(d, i) {
return d.data.percent + '%';
});
var legend = gRoot.append('g')
.attr('class', 'legend')
.selectAll('text')
.data(chartData.values)
.enter();
/*
Displays legend indicating what color represents what category
*/
legend.append('rect')
.attr('height', 10)
.attr('width', 10)
.attr('x', function(d) {
if (attrs.type === 'sentiment' || attrs.type === 'reaction') {
return 0 - radius - 35;
} else {
return 0 - radius - 20;
}
})
.attr('y', function(d, i) {
if (attrs.type === 'sentiment' || attrs.type === 'reaction') {
return (20 * (i + 1) - 210);
} else {
return (20 * (i + 1)) - 260;
}
})
.on('mouseover', function(d, i) {
var sel = d3.selectAll('.arc-' + attrs.type).filter(function(d) {
return d.data.id === i;
});
scope.mouseOverPath.call(sel.select('path')[0][0], sel.datum());
})
.style('fill', function(d) {
return chartData.colors[d.label];
});
legend.append('text')
.attr('x', function(d) {
if (attrs.type === 'sentiment' || attrs.type === 'reaction') {
return 0 - radius - 15;
} else {
return 0 - radius;
}
})
.attr('y', function(d, i) {
if (attrs.type === 'sentiment' || attrs.type === 'reaction') {
return (20 * (i + 1) - 200);
} else {
return (20 * (i + 1)) - 250;
}
})
.attr('font-size', '12px')
.attr('fill', '#9099A1')
.on('mouseover', function(d, i) {
var sel = d3.selectAll('.arc-' + attrs.type).filter(function(d) {
return d.data.id === i;
});
scope.mouseOverPath.call(sel.select('path')[0][0], sel.datum());
})
.text(function(d) { return d.label; });
}
init();
$document.ready(function() {
var chart = angular.element('#piecharts-' + subname);
var donutElem = element.parent().parent().parent();
var prevElem = donutElem[0].previousElementSibling;
var idName = '#' + prevElem.id + ' .graph';
// If no activity in the last year, there will be no charts, get top entries instead
if (prevElem.id.length == 0) {
var prevElem = prevElem.previousElementSibling;
if (angular.element('#top-post-' + subname).length > 0) {
idName = '#' + prevElem.id + ' .post-content';
} else {
idName = '#' + prevElem.id + ' .post-body';
}
}
var winHeight = $win.innerHeight();
var listener = scope.$watch(function() { return angular.element(idName).height() > 0 }, function() {
var e = angular.element(idName);
if (!scope.chartReady && e.length > 0 && e[0].clientHeight > 0) {
var boxTop = chart[0].offsetTop - winHeight + 100;
$win.on('scroll', function (e) {
var scrollY = $win.scrollTop();
if (!scope.chartReady && (scrollY >= boxTop)) {
scope.getChart();
scope.$apply();
return;
}
});
}
});
});
});
}
};
}]);
| sharibarboza/SubSnoop | app/scripts/directives/donutchart.js | JavaScript | mit | 14,247 |
package com.stuffwithstuff.magpie.interpreter.builtin;
import com.stuffwithstuff.magpie.interpreter.Interpreter;
import com.stuffwithstuff.magpie.interpreter.Obj;
public interface BuiltInCallable {
Obj invoke(Interpreter interpreter, Obj thisObj, Obj arg);
}
| munificent/magpie-optionally-typed | src/com/stuffwithstuff/magpie/interpreter/builtin/BuiltInCallable.java | Java | mit | 263 |
class UserAgentsController < ApplicationController
before_action :set_user_agent, only: [:show, :update, :destroy]
# GET /user_agents
# GET /user_agents.json
def index
@user_agents = UserAgent.all
render json: @user_agents
end
# GET /user_agents/1
# GET /user_agents/1.json
def show
render json: @user_agent
end
# POST /user_agents
# POST /user_agents.json
def create
@user_agent = UserAgent.new(user_agent_params)
if @user_agent.save
render json: @user_agent, status: :created, location: @user_agent
else
render json: @user_agent.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /user_agents/1
# PATCH/PUT /user_agents/1.json
def update
@user_agent = UserAgent.find(params[:id])
if @user_agent.update(user_agent_params)
head :no_content
else
render json: @user_agent.errors, status: :unprocessable_entity
end
end
# DELETE /user_agents/1
# DELETE /user_agents/1.json
def destroy
@user_agent.destroy
head :no_content
end
private
def set_user_agent
@user_agent = UserAgent.find(params[:id])
end
def user_agent_params
params.require(:user_agent).permit(:user_id, :user_agent, :editor, :version, :os, :last_seen)
end
end
| deangiberson/myWakatimeApi | app/controllers/user_agents_controller.rb | Ruby | mit | 1,286 |
module RotpRails
VERSION = '0.0.1'
end
| steakknife/rotp_rails | lib/rotp_rails/version.rb | Ruby | mit | 41 |
"""Device tracker for Synology SRM routers."""
from __future__ import annotations
import logging
import synology_srm
import voluptuous as vol
from homeassistant.components.device_tracker import (
DOMAIN,
PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA,
DeviceScanner,
)
from homeassistant.const import (
CONF_HOST,
CONF_PASSWORD,
CONF_PORT,
CONF_SSL,
CONF_USERNAME,
CONF_VERIFY_SSL,
)
from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.typing import ConfigType
_LOGGER = logging.getLogger(__name__)
DEFAULT_USERNAME = "admin"
DEFAULT_PORT = 8001
DEFAULT_SSL = True
DEFAULT_VERIFY_SSL = False
PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean,
vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean,
}
)
ATTRIBUTE_ALIAS = {
"band": None,
"connection": None,
"current_rate": None,
"dev_type": None,
"hostname": None,
"ip6_addr": None,
"ip_addr": None,
"is_baned": "is_banned",
"is_beamforming_on": None,
"is_guest": None,
"is_high_qos": None,
"is_low_qos": None,
"is_manual_dev_type": None,
"is_manual_hostname": None,
"is_online": None,
"is_parental_controled": "is_parental_controlled",
"is_qos": None,
"is_wireless": None,
"mac": None,
"max_rate": None,
"mesh_node_id": None,
"rate_quality": None,
"signalstrength": "signal_strength",
"transferRXRate": "transfer_rx_rate",
"transferTXRate": "transfer_tx_rate",
}
def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None:
"""Validate the configuration and return Synology SRM scanner."""
scanner = SynologySrmDeviceScanner(config[DOMAIN])
return scanner if scanner.success_init else None
class SynologySrmDeviceScanner(DeviceScanner):
"""This class scans for devices connected to a Synology SRM router."""
def __init__(self, config):
"""Initialize the scanner."""
self.client = synology_srm.Client(
host=config[CONF_HOST],
port=config[CONF_PORT],
username=config[CONF_USERNAME],
password=config[CONF_PASSWORD],
https=config[CONF_SSL],
)
if not config[CONF_VERIFY_SSL]:
self.client.http.disable_https_verify()
self.devices = []
self.success_init = self._update_info()
_LOGGER.info("Synology SRM scanner initialized")
def scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
self._update_info()
return [device["mac"] for device in self.devices]
def get_extra_attributes(self, device) -> dict:
"""Get the extra attributes of a device."""
device = next(
(result for result in self.devices if result["mac"] == device), None
)
filtered_attributes: dict[str, str] = {}
if not device:
return filtered_attributes
for attribute, alias in ATTRIBUTE_ALIAS.items():
if (value := device.get(attribute)) is None:
continue
attr = alias or attribute
filtered_attributes[attr] = value
return filtered_attributes
def get_device_name(self, device):
"""Return the name of the given device or None if we don't know."""
filter_named = [
result["hostname"] for result in self.devices if result["mac"] == device
]
if filter_named:
return filter_named[0]
return None
def _update_info(self):
"""Check the router for connected devices."""
_LOGGER.debug("Scanning for connected devices")
try:
self.devices = self.client.core.get_network_nsm_device({"is_online": True})
except synology_srm.http.SynologyException as ex:
_LOGGER.error("Error with the Synology SRM: %s", ex)
return False
_LOGGER.debug("Found %d device(s) connected to the router", len(self.devices))
return True
| rohitranjan1991/home-assistant | homeassistant/components/synology_srm/device_tracker.py | Python | mit | 4,397 |
import * as _ from 'lodash';
import { data } from './data';
import { extendFramework } from './extendedFramework';
// Note: nugetTarget is empty for the XBox framework.
export const processedData = data
.filter(p => p.nugetTarget)
.map(p => ({
...p,
frameworks: p.frameworks.map(extendFramework)
}));
| StephenClearyApps/pcltargets | src/logic/processedData.ts | TypeScript | mit | 331 |
// Description:
// There are two lists of different length. The first one consists of keys,
// the second one consists of values. Write a function
//createDict(keys, values) that returns a dictionary created from keys and
// values. If there are not enough values, the rest of keys should have a
//None (JS null)value. If there not enough keys, just ignore the rest of values.
// Example 1:
// keys = ['a', 'b', 'c', 'd']
// values = [1, 2, 3]
// createDict(keys, values) // returns {'a': 1, 'b': 2, 'c': 3, 'd': null}
// Example 2:
// keys = ['a', 'b', 'c']
// values = [1, 2, 3, 4]
// createDict(keys, values) // returns {'a': 1, 'b': 2, 'c': 3}
function createDict(keys, values){
var result = {};
for(var i = 0;i<keys.length;i++){
result[keys[i]] = values[i]!=undefined ? values[i] : null;
}
return result;
}
| kanor1306/scrapyard | CodeWars Katas/7kyu/DictionaryTwoLists.js | JavaScript | mit | 832 |
"use strict";
const { ParserError } = require("../util/errors");
const yaml = require("js-yaml");
module.exports = {
/**
* The order that this parser will run, in relation to other parsers.
*
* @type {number}
*/
order: 200,
/**
* Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects.
*
* @type {boolean}
*/
allowEmpty: true,
/**
* Determines whether this parser can parse a given file reference.
* Parsers that match will be tried, in order, until one successfully parses the file.
* Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case
* every parser will be tried.
*
* @type {RegExp|string[]|function}
*/
canParse: [".yaml", ".yml", ".json"], // JSON is valid YAML
/**
* Parses the given file as YAML
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
* @returns {Promise}
*/
async parse (file) { // eslint-disable-line require-await
let data = file.data;
if (Buffer.isBuffer(data)) {
data = data.toString();
}
if (typeof data === "string") {
try {
return yaml.load(data);
}
catch (e) {
throw new ParserError(e.message, file.url);
}
}
else {
// data is already a JavaScript value (object, array, number, null, NaN, etc.)
return data;
}
}
};
| BigstickCarpet/json-schema-ref-parser | lib/parsers/yaml.js | JavaScript | mit | 1,730 |
package lol4j.protocol.dto.champion;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* Created by Aaron Corley on 12/10/13.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class ChampionDto {
private boolean active;
private boolean botEnabled;
private boolean botMmEnabled;
private boolean freeToPlay;
private long id;
private boolean rankedPlayEnabled;
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public boolean isBotEnabled() {
return botEnabled;
}
public void setBotEnabled(boolean botEnabled) {
this.botEnabled = botEnabled;
}
public boolean isBotMmEnabled() {
return botMmEnabled;
}
public void setBotMmEnabled(boolean botMmEnabled) {
this.botMmEnabled = botMmEnabled;
}
public boolean isFreeToPlay() {
return freeToPlay;
}
public void setFreeToPlay(boolean freeToPlay) {
this.freeToPlay = freeToPlay;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public boolean isRankedPlayEnabled() {
return rankedPlayEnabled;
}
public void setRankedPlayEnabled(boolean rankedPlayEnabled) {
this.rankedPlayEnabled = rankedPlayEnabled;
}
}
| aaryn101/lol4j | src/main/java/lol4j/protocol/dto/champion/ChampionDto.java | Java | mit | 1,387 |
<?php
if (! function_exists('array_set_defaults')) {
/**
* Set default key => value in an array, it's useful to prevent unseted array keys
* but you'd use that in next code.
*
* @param array $field An array that will recieve default key
* @param array $defaults Array of keys which be default key of $field
* Array must be associative array, which have
* key and value. Key used as default key and
* Value used as default value for $field param
* @return array
*/
function array_set_defaults(array $array, array $defaults) {
foreach ($defaults as $key => $val) {
if (!array_key_exists($key, $array) AND !isset($array[$key])) {
$array[$key] = $val;
}
}
return $array;
}
}
| projek-xyz/ci-common | mod/helpers/App_array_helper.php | PHP | mit | 902 |
package pl.garciapl.banknow.service;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import pl.garciapl.banknow.model.Transaction;
import pl.garciapl.banknow.service.exceptions.GenericBankNowException;
import pl.garciapl.banknow.service.exceptions.InsufficientFundsException;
/**
* TransactionService - interface for TransactionServiceImpl
*
* @author lukasz
*/
public interface TransactionService {
List<Transaction> getAllTransactions();
void makeDeposit(BigInteger account, BigDecimal amount);
void makeTransfer(BigInteger sender, BigInteger recipient, BigDecimal amount)
throws InsufficientFundsException, GenericBankNowException;
}
| GarciaPL/BankNow | src/main/java/pl/garciapl/banknow/service/TransactionService.java | Java | mit | 703 |
define([
'jquery',
'underscore',
'backbone',
'collections/users/students',
'collections/users/classes',
'collections/users/streams',
'text!templates/students/studentnew.html',
'text!templates/students/classes.html',
'text!templates/students/streams.html',
'jqueryui',
'bootstrap'
], function($, _, Backbone, Students, Classes, Streams, StudentTpl, classesTpl, streamsTpl){
var NewStudent = Backbone.View.extend({
tagName: 'div',
title: "New Student - Student Information System",
events: {
'submit form#new-student' : 'addStudent',
'change #class_id' : 'getStreams'
},
template: _.template(StudentTpl),
classesTpl: _.template(classesTpl),
streamsTpl: _.template(streamsTpl),
initialize: function(){
$("title").html(this.title);
//fetch list of all classes for this class from the database
var self = this;
Classes.fetch({
data: $.param({
token: tokenString
}),
success: function(data){
self.setClasses();
}
});
//fetch list of all streams for this client from the database
Streams.fetch({
data: $.param({
token: tokenString
})
});
},
render: function(){
this.$el.html(this.template());
this.$classes = this.$("#classes-list");
this.$streams = this.$("#streams-list");
return this;
},
addStudent: function(evt){
evt.preventDefault();
var student = {
reg_number: $("#reg_number").val(),
first_name: $("#first_name").val(),
middle_name: $("#middle_name").val(),
last_name: $("#last_name").val(),
dob: $("#dob").val(),
pob: $("#pob").val(),
bcn: $("#bcn").val(),
sex: $("#sex").val(),
nationality: $("#nationality").val(),
doa: $("#doa").val(),
class_id: $("#class_id").val(),
stream_id: ($("#stream_id").val()) ? $("#stream_id").val() : '',
address: $("#address").val(),
code: $("#code").val(),
town: $("#town").val(),
pg_f_name: $("#pg_f_name").val(),
pg_l_name: $("#pg_l_name").val(),
pg_email: $("#pg_email").val(),
pg_phone: $("#pg_phone").val()
};
$(".submit-button").html("Please wait...");
$(".error-message").hide(200);
$(".success-message").hide(200);
Students.create(student, {
url: baseURL + 'students/students?token=' + tokenString,
success: function(){
$(".success-message").html("Student added successfully!").show(400);
$(".submit-button").html('<i class="fa fa-fw fa-check"></i>Save');
//empty the form
$("#reg_number").val(''),
$("#first_name").val(''),
$("#middle_name").val(''),
$("#last_name").val(''),
$("#dob").val(''),
$("#pob").val(''),
$("#bcn").val(''),
$("#sex").val(''),
$("#nationality").val(''),
$("#doa").val(''),
$("#class_id").val(''),
$("#stream_id").val(''),
$("#address").val(''),
$("#code").val(''),
$("#town").val(''),
$("#pg_f_name").val(''),
$("#pg_l_name").val(''),
$("#pg_email").val(''),
$("#pg_phone").val('')
},
error : function(jqXHR, textStatus, errorThrown) {
if(textStatus.status != 401 && textStatus.status != 403) {
$(".error-message").html("Please check the errors below!").show(400);
$(".submit-button").html('<i class="fa fa-fw fa-check"></i>Save');
}
}
});
},
setClasses: function(){
this.$classes.empty();
var regClasses = [];
Classes.each(function(oneClass){
regClasses.push(oneClass.toJSON());
}, this);
this.$classes.html(this.classesTpl({
regClasses: regClasses
}));
},
getStreams: function(){
var classID = $("#class_id").val();
var regStreams = [];
var streams = Streams.where({
class_id: classID
});
$.each(streams, function(key, oneStream){
regStreams.push(oneStream.toJSON());
});
this.$streams.html(this.streamsTpl({
regStreams: regStreams
}));
}
});
return NewStudent;
}); | geoffreybans/student-is | public/js/views/students/studentnew.js | JavaScript | mit | 3,985 |
<?php
namespace Gsandbox\Action;
use Gsandbox\Model\DataRetrievalPolicy;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
class GetDataRetrievalPolicyAction
{
public function __invoke(Request $req, Response $res, $args = [])
{
$policy = new DataRetrievalPolicy();
$ruleset = $policy->get();
return $res->withJson($policy->get(), 200, JSON_PRETTY_PRINT);
}
}
| sebcode/gsandbox | src/Action/GetDataRetrievalPolicyAction.php | PHP | mit | 457 |
<?php
/* Smarty version 3.1.28, created on 2016-04-29 19:20:04
from "C:\xampp\htdocs\monitoring\application\views\admin\parent\list.tpl" */
if ($_smarty_tpl->smarty->ext->_validateCompiled->decodeProperties($_smarty_tpl, array (
'has_nocache_code' => false,
'version' => '3.1.28',
'unifunc' => 'content_572397c4638617_08448648',
'file_dependency' =>
array (
'323cb364cb7db1b3e0e77127bc5abfbab64cb3f3' =>
array (
0 => 'C:\\xampp\\htdocs\\monitoring\\application\\views\\admin\\parent\\list.tpl',
1 => 1461950156,
2 => 'file',
),
),
'includes' =>
array (
'file:admin/master_layout.tpl' => 1,
'file:admin/nav_bar.tpl' => 1,
'file:admin/parent/breadcum.tpl' => 1,
'file:admin/parent/sidebar.tpl' => 1,
'file:admin/top_notif.tpl' => 1,
),
),false)) {
function content_572397c4638617_08448648 ($_smarty_tpl) {
if (!is_callable('smarty_function_base_url')) require_once 'C:\\xampp\\htdocs\\monitoring\\application\\third_party\\smarty\\libs\\plugins\\function.base_url.php';
$_smarty_tpl->ext->_inheritance->init($_smarty_tpl, true);
?>
<?php
$_smarty_tpl->ext->_inheritance->processBlock($_smarty_tpl, 0, 'navbar', array (
0 => 'block_1862572397c45d6b79_68289653',
1 => false,
3 => 0,
2 => 0,
));
?>
<?php
$_smarty_tpl->ext->_inheritance->processBlock($_smarty_tpl, 0, 'breadcrumb', array (
0 => 'block_7431572397c45de882_92110023',
1 => false,
3 => 0,
2 => 0,
));
?>
<?php
$_smarty_tpl->ext->_inheritance->processBlock($_smarty_tpl, 0, 'sidebar', array (
0 => 'block_11828572397c45e6585_97163777',
1 => false,
3 => 0,
2 => 0,
));
?>
<?php
$_smarty_tpl->ext->_inheritance->processBlock($_smarty_tpl, 0, 'content', array (
0 => 'block_13405572397c45ea406_61986431',
1 => false,
3 => 0,
2 => 0,
));
?>
<?php $_smarty_tpl->ext->_inheritance->endChild($_smarty_tpl);
$_smarty_tpl->smarty->ext->_subtemplate->render($_smarty_tpl, "file:admin/master_layout.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 2, false);
}
/* {block 'navbar'} file:admin\parent\list.tpl */
function block_1862572397c45d6b79_68289653($_smarty_tpl, $_blockParentStack) {
?>
<?php $_smarty_tpl->smarty->ext->_subtemplate->render($_smarty_tpl, "file:admin/nav_bar.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array('active'=>'parents'), 0, false);
?>
<?php
}
/* {/block 'navbar'} */
/* {block 'breadcrumb'} file:admin\parent\list.tpl */
function block_7431572397c45de882_92110023($_smarty_tpl, $_blockParentStack) {
?>
<?php $_smarty_tpl->smarty->ext->_subtemplate->render($_smarty_tpl, "file:admin/parent/breadcum.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array('active'=>'home'), 0, false);
?>
<?php
}
/* {/block 'breadcrumb'} */
/* {block 'sidebar'} file:admin\parent\list.tpl */
function block_11828572397c45e6585_97163777($_smarty_tpl, $_blockParentStack) {
?>
<?php $_smarty_tpl->smarty->ext->_subtemplate->render($_smarty_tpl, "file:admin/parent/sidebar.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array('active'=>'list'), 0, false);
?>
<?php
}
/* {/block 'sidebar'} */
/* {block 'content'} file:admin\parent\list.tpl */
function block_13405572397c45ea406_61986431($_smarty_tpl, $_blockParentStack) {
?>
<div class="col-md-10" style="min-height:515px;">
<?php $_smarty_tpl->smarty->ext->_subtemplate->render($_smarty_tpl, "file:admin/top_notif.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 0, false);
?>
<h2>Parent List</h2>
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$_from = $_smarty_tpl->tpl_vars['parents']->value;
if (!is_array($_from) && !is_object($_from)) {
settype($_from, 'array');
}
$__foreach_parent_0_saved_item = isset($_smarty_tpl->tpl_vars['parent']) ? $_smarty_tpl->tpl_vars['parent'] : false;
$__foreach_parent_0_saved_key = isset($_smarty_tpl->tpl_vars['key']) ? $_smarty_tpl->tpl_vars['key'] : false;
$_smarty_tpl->tpl_vars['parent'] = new Smarty_Variable();
$__foreach_parent_0_total = $_smarty_tpl->smarty->ext->_foreach->count($_from);
if ($__foreach_parent_0_total) {
$_smarty_tpl->tpl_vars['key'] = new Smarty_Variable();
foreach ($_from as $_smarty_tpl->tpl_vars['key']->value => $_smarty_tpl->tpl_vars['parent']->value) {
$__foreach_parent_0_saved_local_item = $_smarty_tpl->tpl_vars['parent'];
?>
<tr>
<td><?php echo $_smarty_tpl->tpl_vars['parent']->value->full_name;?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['parent']->value->email;?>
</td>
<td><?php if ($_smarty_tpl->tpl_vars['parent']->value->status == 1) {
echo 'Active';
} else {
echo 'Non-Active';
}?></td>
<td>
<a href="<?php echo smarty_function_base_url(array('url'=>'admin/parent','src'=>$_smarty_tpl->tpl_vars['parent']->value->id),$_smarty_tpl);?>
" class="btn btn-success btn-xs">Detail</a>
<a href="<?php echo smarty_function_base_url(array('url'=>'admin/parent/edit','src'=>$_smarty_tpl->tpl_vars['parent']->value->id),$_smarty_tpl);?>
" class="btn btn-primary btn-xs">Edit</a>
<a href="<?php echo smarty_function_base_url(array('url'=>'admin/parent/delete','src'=>$_smarty_tpl->tpl_vars['parent']->value->id),$_smarty_tpl);?>
" class="btn btn-danger btn-xs" onclick="return confirm('Are you sure?')">Hapus</a>
</td>
</tr>
<?php
$_smarty_tpl->tpl_vars['parent'] = $__foreach_parent_0_saved_local_item;
}
}
if ($__foreach_parent_0_saved_item) {
$_smarty_tpl->tpl_vars['parent'] = $__foreach_parent_0_saved_item;
}
if ($__foreach_parent_0_saved_key) {
$_smarty_tpl->tpl_vars['key'] = $__foreach_parent_0_saved_key;
}
?>
</tbody>
</table>
</div>
</div>
<?php
}
/* {/block 'content'} */
}
| uzumakitensho/simongarsis | application/third_party/smarty/templates_c/323cb364cb7db1b3e0e77127bc5abfbab64cb3f3_0.file.list.tpl.php | PHP | mit | 5,965 |
<?php
/**
* (c) Vespolina Project http://www.vespolina-project.org
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Vespolina\CommerceBundle\Process;
use Symfony\Component\DependencyInjection\ContainerAware;
/**
* @author Daniel Kucharski <daniel@xerias.be>
*/
class ProcessManager extends ContainerAware implements ProcessManagerInterface
{
protected $classMap;
protected $session;
public function __construct($dm, $session) {
$this->classMap = $this->getClassMap();
$this->session = $session;
}
public function createProcess($name, $owner = null)
{
$baseClass = $this->getProcessClass($name);
$process = new $baseClass($this->container);
$process->setId(uniqid());
return $process;
}
public function loadProcessFromContext($name, $context) {
$baseClass = $this->getProcessClass($name);
$process = new $baseClass($this->container, $context);
$process->setId($context->get('id'));
$process->init(false);
return $process;
}
public function findProcessById($processId)
{
$processContextFound = null;
//For now we just use the session
$processes = $this->session->get('processes', array());
foreach($processes as $processName => $processContext) {
if ($processContext->get('id') == $processId) {
return $this->loadProcessFromContext($processName, $processContext);
}
}
}
public function getActiveProcessByOwner($name, $owner)
{
$process = null;
if ($owner == $this->session->getId()) {
$openProcesses = $this->session->get('processes', array());
foreach ($openProcesses as $processName => $processContext) {
if ($processName == $name) {
$process = $this->loadProcessFromContext($processName, $processContext);
}
}
}
if (null != $process && !$process->isCompleted()) {
return $process;
}
}
public function updateProcess(ProcessInterface $process)
{
//For now we persist only the context into the session
$processes = $this->session->get('processes', array());
$processes[$process->getName()] = $process->getContext();
$this->session->set('processes', $processes);
}
public function getProcessClass($name) {
return $this->classMap[$name];
}
protected function getClassMap()
{
return array(
'checkout_b2c' => 'Vespolina\CommerceBundle\ProcessScenario\Checkout\CheckoutProcessB2C'
);
}
}
| vespolina/VespolinaCommerceBundle | Process/ProcessManager.php | PHP | mit | 2,761 |
require "erubis"
module Sliar
class Controller
def initialize(env)
@env = env
end
def env
@env
end
def render(view_name, locales = {})
filename = File.join("app","views", controller_name, "#{view_name}.html.erb")
template = File.read filename
eruby = Erubis::Eruby.new(template)
eruby.result locales.merge(:env => env)
end
def controller_name
klass = self.class
klass = klass.to_s.gsub /Controller$/, ""
Sliar.to_underscore klass
end
end
end
| joeltaylor/Sliar | lib/sliar/controller.rb | Ruby | mit | 536 |
<?php
namespace Oro\Bundle\WorkflowBundle\Tests\Unit\Acl\Extension;
use Oro\Bundle\WorkflowBundle\Acl\Extension\WorkflowMaskBuilder;
class WorkflowMaskBuilderTest extends \PHPUnit\Framework\TestCase
{
public function testViewWorkflowGroup()
{
$this->assertEquals(
WorkflowMaskBuilder::GROUP_VIEW_WORKFLOW,
WorkflowMaskBuilder::MASK_VIEW_WORKFLOW_BASIC
+ WorkflowMaskBuilder::MASK_VIEW_WORKFLOW_LOCAL
+ WorkflowMaskBuilder::MASK_VIEW_WORKFLOW_DEEP
+ WorkflowMaskBuilder::MASK_VIEW_WORKFLOW_GLOBAL
+ WorkflowMaskBuilder::MASK_VIEW_WORKFLOW_SYSTEM
);
}
public function testPerformTransitionsGroup()
{
$this->assertEquals(
WorkflowMaskBuilder::GROUP_PERFORM_TRANSITIONS,
WorkflowMaskBuilder::MASK_PERFORM_TRANSITIONS_BASIC
+ WorkflowMaskBuilder::MASK_PERFORM_TRANSITIONS_LOCAL
+ WorkflowMaskBuilder::MASK_PERFORM_TRANSITIONS_DEEP
+ WorkflowMaskBuilder::MASK_PERFORM_TRANSITIONS_GLOBAL
+ WorkflowMaskBuilder::MASK_PERFORM_TRANSITIONS_SYSTEM
);
}
public function testAllGroup()
{
$this->assertEquals(
WorkflowMaskBuilder::GROUP_ALL,
WorkflowMaskBuilder::GROUP_VIEW_WORKFLOW + WorkflowMaskBuilder::GROUP_PERFORM_TRANSITIONS
);
}
public function testRemoveServiceBits()
{
$this->assertEquals(
WorkflowMaskBuilder::REMOVE_SERVICE_BITS,
WorkflowMaskBuilder::GROUP_ALL
);
}
public function testServiceBits()
{
$this->assertEquals(
WorkflowMaskBuilder::SERVICE_BITS,
~WorkflowMaskBuilder::REMOVE_SERVICE_BITS
);
}
public function testGetEmptyPattern()
{
$builder = new WorkflowMaskBuilder();
$this->assertEquals(
'(PV) system:.. global:.. deep:.. local:.. basic:..',
$builder->getPattern()
);
}
public function testGetPatternViewBasic()
{
$builder = new WorkflowMaskBuilder();
$builder->add(WorkflowMaskBuilder::MASK_VIEW_WORKFLOW_BASIC);
$this->assertEquals(
'(PV) system:.. global:.. deep:.. local:.. basic:.V',
$builder->getPattern()
);
}
public function testGetPatternPerformBasic()
{
$builder = new WorkflowMaskBuilder();
$builder->add(WorkflowMaskBuilder::MASK_PERFORM_TRANSITIONS_BASIC);
$this->assertEquals(
'(PV) system:.. global:.. deep:.. local:.. basic:P.',
$builder->getPattern()
);
}
public function testGetPatternBasic()
{
$builder = new WorkflowMaskBuilder();
$builder->add(WorkflowMaskBuilder::GROUP_BASIC);
$this->assertEquals(
'(PV) system:.. global:.. deep:.. local:.. basic:PV',
$builder->getPattern()
);
}
public function testGetPatternViewLocal()
{
$builder = new WorkflowMaskBuilder();
$builder->add(WorkflowMaskBuilder::MASK_VIEW_WORKFLOW_LOCAL);
$this->assertEquals(
'(PV) system:.. global:.. deep:.. local:.V basic:..',
$builder->getPattern()
);
}
public function testGetPatternPerformLocal()
{
$builder = new WorkflowMaskBuilder();
$builder->add(WorkflowMaskBuilder::MASK_PERFORM_TRANSITIONS_LOCAL);
$this->assertEquals(
'(PV) system:.. global:.. deep:.. local:P. basic:..',
$builder->getPattern()
);
}
public function testGetPatternLocal()
{
$builder = new WorkflowMaskBuilder();
$builder->add(WorkflowMaskBuilder::GROUP_LOCAL);
$this->assertEquals(
'(PV) system:.. global:.. deep:.. local:PV basic:..',
$builder->getPattern()
);
}
public function testGetPatternViewDeep()
{
$builder = new WorkflowMaskBuilder();
$builder->add(WorkflowMaskBuilder::MASK_VIEW_WORKFLOW_DEEP);
$this->assertEquals(
'(PV) system:.. global:.. deep:.V local:.. basic:..',
$builder->getPattern()
);
}
public function testGetPatternPerformDeep()
{
$builder = new WorkflowMaskBuilder();
$builder->add(WorkflowMaskBuilder::MASK_PERFORM_TRANSITIONS_DEEP);
$this->assertEquals(
'(PV) system:.. global:.. deep:P. local:.. basic:..',
$builder->getPattern()
);
}
public function testGetPatternDeep()
{
$builder = new WorkflowMaskBuilder();
$builder->add(WorkflowMaskBuilder::GROUP_DEEP);
$this->assertEquals(
'(PV) system:.. global:.. deep:PV local:.. basic:..',
$builder->getPattern()
);
}
public function testGetPatternViewGlobal()
{
$builder = new WorkflowMaskBuilder();
$builder->add(WorkflowMaskBuilder::MASK_VIEW_WORKFLOW_GLOBAL);
$this->assertEquals(
'(PV) system:.. global:.V deep:.. local:.. basic:..',
$builder->getPattern()
);
}
public function testGetPatternPerformGlobal()
{
$builder = new WorkflowMaskBuilder();
$builder->add(WorkflowMaskBuilder::MASK_PERFORM_TRANSITIONS_GLOBAL);
$this->assertEquals(
'(PV) system:.. global:P. deep:.. local:.. basic:..',
$builder->getPattern()
);
}
public function testGetPatternGlobal()
{
$builder = new WorkflowMaskBuilder();
$builder->add(WorkflowMaskBuilder::GROUP_GLOBAL);
$this->assertEquals(
'(PV) system:.. global:PV deep:.. local:.. basic:..',
$builder->getPattern()
);
}
public function testGetPatternViewSystem()
{
$builder = new WorkflowMaskBuilder();
$builder->add(WorkflowMaskBuilder::MASK_VIEW_WORKFLOW_SYSTEM);
$this->assertEquals(
'(PV) system:.V global:.. deep:.. local:.. basic:..',
$builder->getPattern()
);
}
public function testGetPatternPerformSystem()
{
$builder = new WorkflowMaskBuilder();
$builder->add(WorkflowMaskBuilder::MASK_PERFORM_TRANSITIONS_SYSTEM);
$this->assertEquals(
'(PV) system:P. global:.. deep:.. local:.. basic:..',
$builder->getPattern()
);
}
public function testGetPatternSystem()
{
$builder = new WorkflowMaskBuilder();
$builder->add(WorkflowMaskBuilder::GROUP_SYSTEM);
$this->assertEquals(
'(PV) system:PV global:.. deep:.. local:.. basic:..',
$builder->getPattern()
);
}
}
| orocrm/platform | src/Oro/Bundle/WorkflowBundle/Tests/Unit/Acl/Extension/WorkflowMaskBuilderTest.php | PHP | mit | 6,731 |
package eg.utils;
import java.io.File;
import java.awt.Toolkit;
/**
* Static system properties
*/
public class SystemParams {
/**
* True if the OS is Windows, false otherwise */
public static final boolean IS_WINDOWS;
/**
* The Java version */
public static final String JAVA_VERSION;
/**
* True if the Java version is higher than 8, false otherwise */
public static final boolean IS_JAVA_9_OR_HIGHER;
/**
* True if the Java version is 13 or higher, false otherwise */
public static final boolean IS_JAVA_13_OR_HIGHER;
/**
* The modifier mask for menu shortcuts */
public static final int MODIFIER_MASK;
/**
* The path to the '.eadgyth' directory in the user home
* directory */
public static final String EADGYTH_DATA_DIR;
static {
String os = System.getProperty("os.name").toLowerCase();
IS_WINDOWS = os.contains("win");
String userHome = System.getProperty("user.home");
EADGYTH_DATA_DIR = userHome + File.separator + ".eadgyth";
JAVA_VERSION = System.getProperty("java.version");
IS_JAVA_9_OR_HIGHER = !JAVA_VERSION.startsWith("1.8");
IS_JAVA_13_OR_HIGHER = IS_JAVA_9_OR_HIGHER
&& "13".compareTo(JAVA_VERSION) <= 0;
//
// up to Java 9:
MODIFIER_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
//
// as of Java 10:
//MODIFIER_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx();
}
/**
* Returns if the Eadgyth data directory '.eadgyth' exists
* in the user home directory
*
* @return true if the directory exists, false otherwise
* @see #EADGYTH_DATA_DIR
*/
public static boolean existsEadgythDataDir() {
return new File(EADGYTH_DATA_DIR).exists();
}
//
//--private--/
//
private SystemParams() {}
}
| Eadgyth/Java-Programming-Editor | src/eg/utils/SystemParams.java | Java | mit | 1,846 |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
// ORIGINAL HEADER FROM C++ source which was converted to C# by Ted Dunsford 2/24/2010
/******************************************************************************
* $Id: hfatype.cpp, v 1.11 2006/05/07 04:04:03 fwarmerdam Exp $
*
* Project: Erdas Imagine (.img) Translator
* Purpose: Implementation of the HFAType class, for managing one type
* defined in the HFA data dictionary. Managed by HFADictionary.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 1999, Intergraph Corporation
*
* 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.
******************************************************************************
*
* $Log: hfatype.cpp, v $
* Revision 1.11 2006/05/07 04:04:03 fwarmerdam
* fixed serious multithreading issue with ExtractInstValue (bug 1132)
*
* Revision 1.10 2005/05/13 02:45:16 fwarmerdam
* fixed GetInstCount() error return
*
* Revision 1.9 2005/05/10 00:55:30 fwarmerdam
* Added GetInstCount method
*
* Revision 1.8 2004/01/26 18:28:51 warmerda
* added error recover after corrupt/unrecognised entries - bug 411
*
* Revision 1.7 2003/04/22 19:40:36 warmerda
* fixed email address
*
* Revision 1.6 2003/02/21 15:40:58 dron
* Added support for writing large (>4 GB) Erdas Imagine files.
*
* Revision 1.5 2001/07/18 04:51:57 warmerda
* added CPL_CVSID
*
* Revision 1.4 2000/12/29 16:37:32 warmerda
* Use GUInt32 for all file offsets
*
* Revision 1.3 2000/09/29 21:42:38 warmerda
* preliminary write support implemented
*
* Revision 1.2 1999/01/22 17:36:47 warmerda
* Added GetInstBytes(), track unknown sizes properly
*
* Revision 1.1 1999/01/04 22:52:10 warmerda
* New
*
*/
using System.Collections.Generic;
using System.IO;
namespace DotSpatial.Data
{
/// <summary>
/// HfaType
/// </summary>
public class HfaType
{
#region Properties
/// <summary>
/// Gets or sets the number of fields.
/// </summary>
public int FieldCount { get; set; }
/// <summary>
/// Gets or sets the list of fields
/// </summary>
public List<HfaField> Fields { get; set; }
/// <summary>
/// Gets or sets the number of bytes.
/// </summary>
public int NumBytes { get; set; }
/// <summary>
/// Gets or sets the type name.
/// </summary>
public string TypeName { get; set; }
#endregion
#region Methods
/// <summary>
/// Completes the defenition of this type based on the existing dictionary.
/// </summary>
/// <param name="dictionary">Dictionary used for completion.</param>
public void CompleteDefn(HfaDictionary dictionary)
{
// This may already be done, if an earlier object required this
// object (as a field), and forced and early computation of the size
if (NumBytes != 0) return;
// Complete each fo the fields, totaling up the sizes. This
// isn't really accurate for objects with variable sized
// subobjects.
foreach (HfaField field in Fields)
{
field.CompleteDefn(dictionary);
if (field.NumBytes < 0 || NumBytes == -1)
{
NumBytes = -1;
}
else
{
NumBytes += field.NumBytes;
}
}
}
/// <summary>
/// This function writes content to the file for this entire type by writing
/// the type name and number of bytes, followed by cycling through and writing each
/// of the fields.
/// </summary>
/// <param name="stream">Stream to write to.</param>
public void Dump(Stream stream)
{
StreamWriter sw = new StreamWriter(stream);
sw.Write("HFAType " + TypeName + "/" + NumBytes + "\n");
foreach (HfaField field in Fields)
{
field.Dump(stream);
}
}
/// <summary>
/// Triggers a dump on all the fields of this type.
/// </summary>
/// <param name="fpOut">The output stream.</param>
/// <param name="data">The data.</param>
/// <param name="dataOffset">The offset to start from.</param>
/// <param name="dataSize">The data size.</param>
/// <param name="pszPrefix">The prefix.</param>
public void DumpInstValue(Stream fpOut, byte[] data, long dataOffset, int dataSize, string pszPrefix)
{
foreach (HfaField field in Fields)
{
field.DumpInstValue(fpOut, data, dataOffset, dataSize, pszPrefix);
int nInstBytes = field.GetInstBytes(data, dataOffset);
dataOffset += nInstBytes;
dataSize -= nInstBytes;
}
}
/// <summary>
/// Extracts the value form the byte array.
/// </summary>
/// <param name="fieldPath">The field path.</param>
/// <param name="data">The data.</param>
/// <param name="dataOffset">The offset to start from.</param>
/// <param name="dataSize">The data size.</param>
/// <param name="reqType">The req type.</param>
/// <param name="reqReturn">The req return.</param>
/// <returns>True, if the value could be extracted.</returns>
public bool ExtractInstValue(string fieldPath, byte[] data, long dataOffset, int dataSize, char reqType, out object reqReturn)
{
reqReturn = null;
int arrayIndex, byteOffset, extraOffset;
string remainder;
HfaField field = ParseFieldPath(fieldPath, data, dataOffset, out remainder, out arrayIndex, out byteOffset);
return field != null && field.ExtractInstValue(remainder, arrayIndex, data, dataOffset + byteOffset, dataSize - byteOffset, reqType, out reqReturn, out extraOffset);
}
/// <summary>
/// Gets the number of bytes for this type by adding up the byte contribution from each of its fields.
/// </summary>
/// <param name="data">The array of bytes to scan.</param>
/// <param name="dataOffset">The integer index in the array where scanning should begin.</param>
/// <returns>The integer count.</returns>
public int GetInstBytes(byte[] data, long dataOffset)
{
if (NumBytes >= 0)
{
return NumBytes;
}
int nTotal = 0;
foreach (HfaField field in Fields)
{
nTotal += field.GetInstBytes(data, dataOffset + nTotal);
}
return nTotal;
}
/// <summary>
/// Attempts to find the specified field in the field path and extracts the count of the specified field.
/// </summary>
/// <param name="fieldPath">The field path.</param>
/// <param name="data">The data.</param>
/// <param name="dataOffset">The data offset.</param>
/// <param name="dataSize">The data size.</param>
/// <returns>The count for a particular instance of a field.</returns>
public int GetInstCount(string fieldPath, byte[] data, long dataOffset, int dataSize)
{
int arrayIndex, byteOffset;
string remainder;
HfaField field = ParseFieldPath(fieldPath, data, dataOffset, out remainder, out arrayIndex, out byteOffset);
if (field != null) return field.GetInstCount(data, dataOffset + byteOffset);
return -1;
}
/// <summary>
/// Originally Initialize
/// </summary>
/// <param name="input">The input string that contains content for this type</param>
/// <returns>The remaining string content, unless this fails in which case this may return null</returns>
public string Intialize(string input)
{
if (!input.Contains("{")) return null;
string partialInput = input.SkipTo("{");
while (partialInput != null && partialInput[0] != '}')
{
HfaField fld = new HfaField();
// If the initialize fails, the return string is null.
partialInput = fld.Initialize(partialInput);
if (partialInput == null) continue;
if (Fields == null) Fields = new List<HfaField>();
Fields.Add(fld);
FieldCount++;
}
// If we have run out of content, we can't complete the type.
if (partialInput == null) return null;
// Get the name
int start = 0;
TypeName = partialInput.ExtractTo(ref start, ",");
return partialInput.Substring(start, partialInput.Length - start);
}
/// <summary>
/// Sets the value.
/// </summary>
/// <param name="fieldPath">The field path.</param>
/// <param name="data">The data.</param>
/// <param name="dataOffset">The data offset.</param>
/// <param name="dataSize">The data size.</param>
/// <param name="reqType">The req type.</param>
/// <param name="value">The value.</param>
public void SetInstValue(string fieldPath, byte[] data, long dataOffset, int dataSize, char reqType, object value)
{
int arrayIndex, byteOffset;
string remainder;
HfaField field = ParseFieldPath(fieldPath, data, dataOffset, out remainder, out arrayIndex, out byteOffset);
field.SetInstValue(remainder, arrayIndex, data, dataOffset + byteOffset, dataSize - byteOffset, reqType, value);
}
private HfaField ParseFieldPath(string fieldPath, byte[] data, long dataOffset, out string remainder, out int arrayIndex, out int byteOffset)
{
arrayIndex = 0;
string name;
remainder = null;
if (fieldPath.Contains("["))
{
// In the array case we have the format: name[2].subname
// so only read up to the [ for the name but we also need to read the integer after that bracket.
string arrayVal;
name = fieldPath.ExtractTo("[", out arrayVal);
arrayIndex = arrayVal.ExtractInteger();
// Finally, we still need the subname after the period, but we can ignore the return value and just use the remainder.
fieldPath.ExtractTo(".", out remainder);
}
else if (fieldPath.Contains("."))
{
// This is separating name.subname into two separate parts, even if there are many further sub-divisions of the name.
name = fieldPath.ExtractTo(".", out remainder);
}
else
{
name = fieldPath;
}
// Find the field within this type, if possible
byteOffset = 0;
foreach (HfaField field in Fields)
{
if (field.FieldName == name)
{
return field;
}
byteOffset += field.GetInstBytes(data, dataOffset + byteOffset);
}
return null;
}
#endregion
}
} | CGX-GROUP/DotSpatial | Source/DotSpatial.Data/HfaType.cs | C# | mit | 12,977 |
var express = require('express');
var user = require('../model/user');
var jsonReturn = require('../common/jsonReturn');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
user.getUsers(function(err, rows, fields){
res.render('users', { users : rows } );
})
});
router.post('/getUsers', function (req, res, next) {
if(req.body.username){
user.getUsers(function(err, rows, fields){
res.json(jsonReturn({ users : rows } ));
})
}
});
module.exports = router;
| Justinidlerz/react-and-express | controller/users.js | JavaScript | mit | 535 |
# This is a user's notification settings, really. Might have been a better name for this, in retrospect.
class Notification < ActiveRecord::Base
belongs_to :user
has_many :pending_notifications
belongs_to :reply_to_comment, :foreign_key => :reply_to_comment,
:class_name => 'NotificationFrequency'
belongs_to :comment_on_my_profile, :foreign_key => :comment_on_my_profile,
:class_name => 'NotificationFrequency'
belongs_to :comment_on_my_contribution, :foreign_key => :comment_on_my_contribution,
:class_name => 'NotificationFrequency'
belongs_to :comment_on_my_collection, :foreign_key => :comment_on_my_collection,
:class_name => 'NotificationFrequency'
belongs_to :comment_on_my_community, :foreign_key => :comment_on_my_community,
:class_name => 'NotificationFrequency'
belongs_to :made_me_a_manager, :foreign_key => :made_me_a_manager,
:class_name => 'NotificationFrequency'
belongs_to :member_joined_my_community, :foreign_key => :member_joined_my_community,
:class_name => 'NotificationFrequency'
belongs_to :comment_on_my_watched_item, :foreign_key => :comment_on_my_watched_item,
:class_name => 'NotificationFrequency'
belongs_to :curation_on_my_watched_item, :foreign_key => :curation_on_my_watched_item,
:class_name => 'NotificationFrequency'
belongs_to :new_data_on_my_watched_item, :foreign_key => :new_data_on_my_watched_item,
:class_name => 'NotificationFrequency'
belongs_to :changes_to_my_watched_collection, :foreign_key => :changes_to_my_watched_collection,
:class_name => 'NotificationFrequency'
belongs_to :changes_to_my_watched_community, :foreign_key => :changes_to_my_watched_community,
:class_name => 'NotificationFrequency'
# This one is a misnomer. It should be "member joined a community where I am a member." Sorry.
belongs_to :member_joined_my_watched_community, :foreign_key => :member_joined_my_watched_community,
:class_name => 'NotificationFrequency'
belongs_to :member_left_my_community, :foreign_key => :member_left_my_community,
:class_name => 'NotificationFrequency'
belongs_to :new_manager_in_my_community, :foreign_key => :new_manager_in_my_community,
:class_name => 'NotificationFrequency'
belongs_to :i_am_being_watched, :foreign_key => :i_am_being_watched,
:class_name => 'NotificationFrequency'
validates_presence_of :user
# NOTE - there's a relationship here to the PendingNotification class, which actually references the literal name of
# the field. THUS (!) if you create a new field on this table, note that you are limited to 64 characters or less.
# I think that's a reasonable limit. ;)
def self.types_to_show_in_activity_feeds
return [ :i_collected_something, :i_modified_a_community, :i_commented_on_something, :i_curated_something, :i_created_something ]
end
def self.queue_notifications(notification_recipient_objects, target)
notification_queue = notification_recipient_objects.select {|o| self.acceptable_notifications(o, target) }
notification_queue.each do |h|
PendingNotification.create(:user => h[:user], :notification_frequency => h[:frequency], :target => target,
:reason => h[:notification_type].to_s)
end
begin
Resque.enqueue(PrepareAndSendNotifications) unless notification_queue.empty?
rescue => e
logger.error("** #queue_notifications ERROR: '#{e.message}'; ignoring...")
end
notification_queue
end
def self.acceptable_notifications(object, target)
object.class == Hash && # Passed in something you shouldn't have.
object[:user] && # Only users receive notifications.
object[:user].class == User &&
target.user_id != object[:user].id && # Users are never notified about their own action.
object[:frequency] != NotificationFrequency.never && # User doesn't want any notification at all
object[:frequency] != NotificationFrequency.newsfeed_only && # User doesn't want email for this
! object[:user].disable_email_notifications && # User doesn't want any email at all.
! (target.class == CuratorActivityLog && target.activity == Activity.crop) # We don't send emails about image crops.
end
end
| DanielZhangQingLong/eol4 | app/models/notification.rb | Ruby | mit | 4,227 |
/* Generated by ../bin/opendds_idl version 3.6 (ACE version 6.2a_p7) running on input file DdsDcpsInfoUtils.idl*/
#include "DCPS/DdsDcps_pch.h"
#include "DdsDcpsInfoUtilsTypeSupportImpl.h"
#include <cstring>
#include <stdexcept>
#include "dds/DCPS/FilterEvaluator.h"
#include "dds/CorbaSeq/OctetSeqTypeSupportImpl.h"
#include "dds/DdsDcpsGuidTypeSupportImpl.h"
#include "dds/DdsDcpsInfrastructureTypeSupportImpl.h"
/* Begin MODULE: OpenDDS */
/* Begin MODULE: DCPS */
/* Begin TYPEDEF: RepoId */
/* End TYPEDEF: RepoId */
/* Begin TYPEDEF: TransportBLOB */
/* End TYPEDEF: TransportBLOB */
/* Begin STRUCT: TransportLocator */
namespace OpenDDS { namespace DCPS {
void gen_find_size(const OpenDDS::DCPS::TransportLocator& stru, size_t& size, size_t& padding)
{
ACE_UNUSED_ARG(stru);
ACE_UNUSED_ARG(size);
ACE_UNUSED_ARG(padding);
find_size_ulong(size, padding);
size += ACE_OS::strlen(stru.transport_type) + 1;
gen_find_size(stru.data, size, padding);
}
bool operator<<(Serializer& strm, const OpenDDS::DCPS::TransportLocator& stru)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(stru);
return (strm << stru.transport_type)
&& (strm << stru.data);
}
bool operator>>(Serializer& strm, OpenDDS::DCPS::TransportLocator& stru)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(stru);
return (strm >> stru.transport_type.out())
&& (strm >> stru.data);
}
} }
#ifndef OPENDDS_NO_CONTENT_SUBSCRIPTION_PROFILE
namespace OpenDDS { namespace DCPS {
template<>
struct MetaStructImpl<OpenDDS::DCPS::TransportLocator> : MetaStruct {
typedef OpenDDS::DCPS::TransportLocator T;
void* allocate() const { return new T; }
void deallocate(void* stru) const { delete static_cast<T*>(stru); }
size_t numDcpsKeys() const { return 0; }
Value getValue(const void* stru, const char* field) const
{
const OpenDDS::DCPS::TransportLocator& typed = *static_cast<const OpenDDS::DCPS::TransportLocator*>(stru);
if (std::strcmp(field, "transport_type") == 0) {
return typed.transport_type.in();
}
ACE_UNUSED_ARG(typed);
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::TransportLocator)");
}
Value getValue(Serializer& ser, const char* field) const
{
if (std::strcmp(field, "transport_type") == 0) {
TAO::String_Manager val;
if (!(ser >> val.out())) {
throw std::runtime_error("Field 'transport_type' could not be deserialized");
}
return val;
} else {
ACE_CDR::ULong len;
if (!(ser >> len)) {
throw std::runtime_error("String 'transport_type' length could not be deserialized");
}
ser.skip(len);
}
gen_skip_over(ser, static_cast<OpenDDS::DCPS::TransportBLOB*>(0));
if (!field[0]) {
return 0;
}
throw std::runtime_error("Field " + std::string(field) + " not valid for struct OpenDDS::DCPS::TransportLocator");
}
ComparatorBase::Ptr create_qc_comparator(const char* field, ComparatorBase::Ptr next) const
{
ACE_UNUSED_ARG(next);
if (std::strcmp(field, "transport_type") == 0) {
return make_field_cmp(&T::transport_type, next);
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::TransportLocator)");
}
const char** getFieldNames() const
{
static const char* names[] = {"transport_type", "data", 0};
return names;
}
const void* getRawField(const void* stru, const char* field) const
{
if (std::strcmp(field, "transport_type") == 0) {
return &static_cast<const T*>(stru)->transport_type;
}
if (std::strcmp(field, "data") == 0) {
return &static_cast<const T*>(stru)->data;
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::TransportLocator)");
}
void assign(void* lhs, const char* field, const void* rhs,
const char* rhsFieldSpec, const MetaStruct& rhsMeta) const
{
ACE_UNUSED_ARG(lhs);
ACE_UNUSED_ARG(field);
ACE_UNUSED_ARG(rhs);
ACE_UNUSED_ARG(rhsFieldSpec);
ACE_UNUSED_ARG(rhsMeta);
if (std::strcmp(field, "transport_type") == 0) {
static_cast<T*>(lhs)->transport_type = *static_cast<const TAO::String_Manager*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
if (std::strcmp(field, "data") == 0) {
static_cast<T*>(lhs)->data = *static_cast<const OpenDDS::DCPS::TransportBLOB*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::TransportLocator)");
}
bool compare(const void* lhs, const void* rhs, const char* field) const
{
ACE_UNUSED_ARG(lhs);
ACE_UNUSED_ARG(field);
ACE_UNUSED_ARG(rhs);
if (std::strcmp(field, "transport_type") == 0) {
return 0 == ACE_OS::strcmp(static_cast<const T*>(lhs)->transport_type, static_cast<const T*>(rhs)->transport_type);
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::TransportLocator)");
}
};
template<>
const MetaStruct& getMetaStruct<OpenDDS::DCPS::TransportLocator>()
{
static MetaStructImpl<OpenDDS::DCPS::TransportLocator> msi;
return msi;
}
void gen_skip_over(Serializer& ser, OpenDDS::DCPS::TransportLocator*)
{
ACE_UNUSED_ARG(ser);
MetaStructImpl<OpenDDS::DCPS::TransportLocator>().getValue(ser, "");
}
} }
#endif
/* End STRUCT: TransportLocator */
/* Begin TYPEDEF: TransportLocatorSeq */
namespace OpenDDS { namespace DCPS {
void gen_find_size(const OpenDDS::DCPS::TransportLocatorSeq& seq, size_t& size, size_t& padding)
{
ACE_UNUSED_ARG(seq);
ACE_UNUSED_ARG(size);
ACE_UNUSED_ARG(padding);
find_size_ulong(size, padding);
if (seq.length() == 0) {
return;
}
for (CORBA::ULong i = 0; i < seq.length(); ++i) {
gen_find_size(seq[i], size, padding);
}
}
bool operator<<(Serializer& strm, const OpenDDS::DCPS::TransportLocatorSeq& seq)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(seq);
const CORBA::ULong length = seq.length();
if (!(strm << length)) {
return false;
}
if (length == 0) {
return true;
}
for (CORBA::ULong i = 0; i < length; ++i) {
if (!(strm << seq[i])) {
return false;
}
}
return true;
}
bool operator>>(Serializer& strm, OpenDDS::DCPS::TransportLocatorSeq& seq)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(seq);
CORBA::ULong length;
if (!(strm >> length)) {
return false;
}
seq.length(length);
for (CORBA::ULong i = 0; i < length; ++i) {
if (!(strm >> seq[i])) {
return false;
}
}
return true;
}
} }
#ifndef OPENDDS_NO_CONTENT_SUBSCRIPTION_PROFILE
namespace OpenDDS { namespace DCPS {
void gen_skip_over(Serializer& ser, OpenDDS::DCPS::TransportLocatorSeq*)
{
ACE_UNUSED_ARG(ser);
ACE_CDR::ULong length;
ser >> length;
for (ACE_CDR::ULong i = 0; i < length; ++i) {
gen_skip_over(ser, static_cast<OpenDDS::DCPS::TransportLocator*>(0));
}
}
} }
#endif
/* End TYPEDEF: TransportLocatorSeq */
/* Begin STRUCT: IncompatibleQosStatus */
namespace OpenDDS { namespace DCPS {
void gen_find_size(const OpenDDS::DCPS::IncompatibleQosStatus& stru, size_t& size, size_t& padding)
{
ACE_UNUSED_ARG(stru);
ACE_UNUSED_ARG(size);
ACE_UNUSED_ARG(padding);
if ((size + padding) % 4) {
padding += 4 - ((size + padding) % 4);
}
size += gen_max_marshaled_size(stru.total_count);
if ((size + padding) % 4) {
padding += 4 - ((size + padding) % 4);
}
size += gen_max_marshaled_size(stru.count_since_last_send);
if ((size + padding) % 4) {
padding += 4 - ((size + padding) % 4);
}
size += gen_max_marshaled_size(stru.last_policy_id);
gen_find_size(stru.policies, size, padding);
}
bool operator<<(Serializer& strm, const OpenDDS::DCPS::IncompatibleQosStatus& stru)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(stru);
return (strm << stru.total_count)
&& (strm << stru.count_since_last_send)
&& (strm << stru.last_policy_id)
&& (strm << stru.policies);
}
bool operator>>(Serializer& strm, OpenDDS::DCPS::IncompatibleQosStatus& stru)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(stru);
return (strm >> stru.total_count)
&& (strm >> stru.count_since_last_send)
&& (strm >> stru.last_policy_id)
&& (strm >> stru.policies);
}
} }
#ifndef OPENDDS_NO_CONTENT_SUBSCRIPTION_PROFILE
namespace OpenDDS { namespace DCPS {
template<>
struct MetaStructImpl<OpenDDS::DCPS::IncompatibleQosStatus> : MetaStruct {
typedef OpenDDS::DCPS::IncompatibleQosStatus T;
void* allocate() const { return new T; }
void deallocate(void* stru) const { delete static_cast<T*>(stru); }
size_t numDcpsKeys() const { return 0; }
Value getValue(const void* stru, const char* field) const
{
const OpenDDS::DCPS::IncompatibleQosStatus& typed = *static_cast<const OpenDDS::DCPS::IncompatibleQosStatus*>(stru);
if (std::strcmp(field, "total_count") == 0) {
return typed.total_count;
}
if (std::strcmp(field, "count_since_last_send") == 0) {
return typed.count_since_last_send;
}
if (std::strcmp(field, "last_policy_id") == 0) {
return typed.last_policy_id;
}
ACE_UNUSED_ARG(typed);
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::IncompatibleQosStatus)");
}
Value getValue(Serializer& ser, const char* field) const
{
if (std::strcmp(field, "total_count") == 0) {
ACE_CDR::Long val;
if (!(ser >> val)) {
throw std::runtime_error("Field 'total_count' could not be deserialized");
}
return val;
} else {
ser.skip(1, 4);
}
if (std::strcmp(field, "count_since_last_send") == 0) {
ACE_CDR::Long val;
if (!(ser >> val)) {
throw std::runtime_error("Field 'count_since_last_send' could not be deserialized");
}
return val;
} else {
ser.skip(1, 4);
}
if (std::strcmp(field, "last_policy_id") == 0) {
ACE_CDR::Long val;
if (!(ser >> val)) {
throw std::runtime_error("Field 'last_policy_id' could not be deserialized");
}
return val;
} else {
ser.skip(1, 4);
}
gen_skip_over(ser, static_cast<DDS::QosPolicyCountSeq*>(0));
if (!field[0]) {
return 0;
}
throw std::runtime_error("Field " + std::string(field) + " not valid for struct OpenDDS::DCPS::IncompatibleQosStatus");
}
ComparatorBase::Ptr create_qc_comparator(const char* field, ComparatorBase::Ptr next) const
{
ACE_UNUSED_ARG(next);
if (std::strcmp(field, "total_count") == 0) {
return make_field_cmp(&T::total_count, next);
}
if (std::strcmp(field, "count_since_last_send") == 0) {
return make_field_cmp(&T::count_since_last_send, next);
}
if (std::strcmp(field, "last_policy_id") == 0) {
return make_field_cmp(&T::last_policy_id, next);
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::IncompatibleQosStatus)");
}
const char** getFieldNames() const
{
static const char* names[] = {"total_count", "count_since_last_send", "last_policy_id", "policies", 0};
return names;
}
const void* getRawField(const void* stru, const char* field) const
{
if (std::strcmp(field, "total_count") == 0) {
return &static_cast<const T*>(stru)->total_count;
}
if (std::strcmp(field, "count_since_last_send") == 0) {
return &static_cast<const T*>(stru)->count_since_last_send;
}
if (std::strcmp(field, "last_policy_id") == 0) {
return &static_cast<const T*>(stru)->last_policy_id;
}
if (std::strcmp(field, "policies") == 0) {
return &static_cast<const T*>(stru)->policies;
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::IncompatibleQosStatus)");
}
void assign(void* lhs, const char* field, const void* rhs,
const char* rhsFieldSpec, const MetaStruct& rhsMeta) const
{
ACE_UNUSED_ARG(lhs);
ACE_UNUSED_ARG(field);
ACE_UNUSED_ARG(rhs);
ACE_UNUSED_ARG(rhsFieldSpec);
ACE_UNUSED_ARG(rhsMeta);
if (std::strcmp(field, "total_count") == 0) {
static_cast<T*>(lhs)->total_count = *static_cast<const CORBA::Long*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
if (std::strcmp(field, "count_since_last_send") == 0) {
static_cast<T*>(lhs)->count_since_last_send = *static_cast<const CORBA::Long*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
if (std::strcmp(field, "last_policy_id") == 0) {
static_cast<T*>(lhs)->last_policy_id = *static_cast<const DDS::QosPolicyId_t*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
if (std::strcmp(field, "policies") == 0) {
static_cast<T*>(lhs)->policies = *static_cast<const DDS::QosPolicyCountSeq*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::IncompatibleQosStatus)");
}
bool compare(const void* lhs, const void* rhs, const char* field) const
{
ACE_UNUSED_ARG(lhs);
ACE_UNUSED_ARG(field);
ACE_UNUSED_ARG(rhs);
if (std::strcmp(field, "total_count") == 0) {
return static_cast<const T*>(lhs)->total_count == static_cast<const T*>(rhs)->total_count;
}
if (std::strcmp(field, "count_since_last_send") == 0) {
return static_cast<const T*>(lhs)->count_since_last_send == static_cast<const T*>(rhs)->count_since_last_send;
}
if (std::strcmp(field, "last_policy_id") == 0) {
return static_cast<const T*>(lhs)->last_policy_id == static_cast<const T*>(rhs)->last_policy_id;
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::IncompatibleQosStatus)");
}
};
template<>
const MetaStruct& getMetaStruct<OpenDDS::DCPS::IncompatibleQosStatus>()
{
static MetaStructImpl<OpenDDS::DCPS::IncompatibleQosStatus> msi;
return msi;
}
void gen_skip_over(Serializer& ser, OpenDDS::DCPS::IncompatibleQosStatus*)
{
ACE_UNUSED_ARG(ser);
MetaStructImpl<OpenDDS::DCPS::IncompatibleQosStatus>().getValue(ser, "");
}
} }
#endif
/* End STRUCT: IncompatibleQosStatus */
/* Begin STRUCT: AddDomainStatus */
namespace OpenDDS { namespace DCPS {
void gen_find_size(const OpenDDS::DCPS::AddDomainStatus& stru, size_t& size, size_t& padding)
{
ACE_UNUSED_ARG(stru);
ACE_UNUSED_ARG(size);
ACE_UNUSED_ARG(padding);
gen_find_size(stru.id, size, padding);
size += gen_max_marshaled_size(ACE_OutputCDR::from_boolean(stru.federated));
}
bool operator<<(Serializer& strm, const OpenDDS::DCPS::AddDomainStatus& stru)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(stru);
return (strm << stru.id)
&& (strm << ACE_OutputCDR::from_boolean(stru.federated));
}
bool operator>>(Serializer& strm, OpenDDS::DCPS::AddDomainStatus& stru)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(stru);
return (strm >> stru.id)
&& (strm >> ACE_InputCDR::to_boolean(stru.federated));
}
} }
#ifndef OPENDDS_NO_CONTENT_SUBSCRIPTION_PROFILE
namespace OpenDDS { namespace DCPS {
template<>
struct MetaStructImpl<OpenDDS::DCPS::AddDomainStatus> : MetaStruct {
typedef OpenDDS::DCPS::AddDomainStatus T;
void* allocate() const { return new T; }
void deallocate(void* stru) const { delete static_cast<T*>(stru); }
size_t numDcpsKeys() const { return 0; }
Value getValue(const void* stru, const char* field) const
{
const OpenDDS::DCPS::AddDomainStatus& typed = *static_cast<const OpenDDS::DCPS::AddDomainStatus*>(stru);
if (std::strncmp(field, "id.", 3) == 0) {
return getMetaStruct<OpenDDS::DCPS::RepoId>().getValue(&typed.id, field + 3);
}
if (std::strcmp(field, "federated") == 0) {
return typed.federated;
}
ACE_UNUSED_ARG(typed);
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::AddDomainStatus)");
}
Value getValue(Serializer& ser, const char* field) const
{
if (std::strncmp(field, "id.", 3) == 0) {
return getMetaStruct<OpenDDS::DCPS::RepoId>().getValue(ser, field + 3);
} else {
gen_skip_over(ser, static_cast<OpenDDS::DCPS::RepoId*>(0));
}
if (std::strcmp(field, "federated") == 0) {
ACE_CDR::Boolean val;
if (!(ser >> ACE_InputCDR::to_boolean(val))) {
throw std::runtime_error("Field 'federated' could not be deserialized");
}
return val;
} else {
ser.skip(1, 1);
}
if (!field[0]) {
return 0;
}
throw std::runtime_error("Field " + std::string(field) + " not valid for struct OpenDDS::DCPS::AddDomainStatus");
}
ComparatorBase::Ptr create_qc_comparator(const char* field, ComparatorBase::Ptr next) const
{
ACE_UNUSED_ARG(next);
if (std::strncmp(field, "id.", 3) == 0) {
return make_struct_cmp(&T::id, getMetaStruct<OpenDDS::DCPS::RepoId>().create_qc_comparator(field + 3, 0), next);
}
if (std::strcmp(field, "federated") == 0) {
return make_field_cmp(&T::federated, next);
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::AddDomainStatus)");
}
const char** getFieldNames() const
{
static const char* names[] = {"id", "federated", 0};
return names;
}
const void* getRawField(const void* stru, const char* field) const
{
if (std::strcmp(field, "id") == 0) {
return &static_cast<const T*>(stru)->id;
}
if (std::strcmp(field, "federated") == 0) {
return &static_cast<const T*>(stru)->federated;
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::AddDomainStatus)");
}
void assign(void* lhs, const char* field, const void* rhs,
const char* rhsFieldSpec, const MetaStruct& rhsMeta) const
{
ACE_UNUSED_ARG(lhs);
ACE_UNUSED_ARG(field);
ACE_UNUSED_ARG(rhs);
ACE_UNUSED_ARG(rhsFieldSpec);
ACE_UNUSED_ARG(rhsMeta);
if (std::strcmp(field, "id") == 0) {
static_cast<T*>(lhs)->id = *static_cast<const OpenDDS::DCPS::RepoId*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
if (std::strcmp(field, "federated") == 0) {
static_cast<T*>(lhs)->federated = *static_cast<const CORBA::Boolean*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::AddDomainStatus)");
}
bool compare(const void* lhs, const void* rhs, const char* field) const
{
ACE_UNUSED_ARG(lhs);
ACE_UNUSED_ARG(field);
ACE_UNUSED_ARG(rhs);
if (std::strcmp(field, "federated") == 0) {
return static_cast<const T*>(lhs)->federated == static_cast<const T*>(rhs)->federated;
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::AddDomainStatus)");
}
};
template<>
const MetaStruct& getMetaStruct<OpenDDS::DCPS::AddDomainStatus>()
{
static MetaStructImpl<OpenDDS::DCPS::AddDomainStatus> msi;
return msi;
}
void gen_skip_over(Serializer& ser, OpenDDS::DCPS::AddDomainStatus*)
{
ACE_UNUSED_ARG(ser);
MetaStructImpl<OpenDDS::DCPS::AddDomainStatus>().getValue(ser, "");
}
} }
#endif
/* End STRUCT: AddDomainStatus */
/* Begin ENUM: TopicStatus */
namespace OpenDDS { namespace DCPS {
bool operator<<(Serializer& strm, const OpenDDS::DCPS::TopicStatus& enumval)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(enumval);
return strm << static_cast<CORBA::ULong>(enumval);
}
bool operator>>(Serializer& strm, OpenDDS::DCPS::TopicStatus& enumval)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(enumval);
CORBA::ULong temp = 0;
if (strm >> temp) {
enumval = static_cast<OpenDDS::DCPS::TopicStatus>(temp);
return true;
}
return false;
}
} }
#ifndef OPENDDS_NO_CONTENT_SUBSCRIPTION_PROFILE
namespace OpenDDS { namespace DCPS {
const char* gen_OpenDDS_DCPS_TopicStatus_names[] = {
"CREATED",
"ENABLED",
"FOUND",
"NOT_FOUND",
"REMOVED",
"CONFLICTING_TYPENAME",
"PRECONDITION_NOT_MET",
"INTERNAL_ERROR"
};
} }
#endif
/* End ENUM: TopicStatus */
/* Begin STRUCT: WriterAssociation */
namespace OpenDDS { namespace DCPS {
void gen_find_size(const OpenDDS::DCPS::WriterAssociation& stru, size_t& size, size_t& padding)
{
ACE_UNUSED_ARG(stru);
ACE_UNUSED_ARG(size);
ACE_UNUSED_ARG(padding);
gen_find_size(stru.writerTransInfo, size, padding);
gen_find_size(stru.writerId, size, padding);
gen_find_size(stru.pubQos, size, padding);
gen_find_size(stru.writerQos, size, padding);
}
bool operator<<(Serializer& strm, const OpenDDS::DCPS::WriterAssociation& stru)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(stru);
return (strm << stru.writerTransInfo)
&& (strm << stru.writerId)
&& (strm << stru.pubQos)
&& (strm << stru.writerQos);
}
bool operator>>(Serializer& strm, OpenDDS::DCPS::WriterAssociation& stru)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(stru);
return (strm >> stru.writerTransInfo)
&& (strm >> stru.writerId)
&& (strm >> stru.pubQos)
&& (strm >> stru.writerQos);
}
} }
#ifndef OPENDDS_NO_CONTENT_SUBSCRIPTION_PROFILE
namespace OpenDDS { namespace DCPS {
template<>
struct MetaStructImpl<OpenDDS::DCPS::WriterAssociation> : MetaStruct {
typedef OpenDDS::DCPS::WriterAssociation T;
void* allocate() const { return new T; }
void deallocate(void* stru) const { delete static_cast<T*>(stru); }
size_t numDcpsKeys() const { return 0; }
Value getValue(const void* stru, const char* field) const
{
const OpenDDS::DCPS::WriterAssociation& typed = *static_cast<const OpenDDS::DCPS::WriterAssociation*>(stru);
if (std::strncmp(field, "writerId.", 9) == 0) {
return getMetaStruct<OpenDDS::DCPS::RepoId>().getValue(&typed.writerId, field + 9);
}
if (std::strncmp(field, "pubQos.", 7) == 0) {
return getMetaStruct<DDS::PublisherQos>().getValue(&typed.pubQos, field + 7);
}
if (std::strncmp(field, "writerQos.", 10) == 0) {
return getMetaStruct<DDS::DataWriterQos>().getValue(&typed.writerQos, field + 10);
}
ACE_UNUSED_ARG(typed);
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::WriterAssociation)");
}
Value getValue(Serializer& ser, const char* field) const
{
gen_skip_over(ser, static_cast<OpenDDS::DCPS::TransportLocatorSeq*>(0));
if (std::strncmp(field, "writerId.", 9) == 0) {
return getMetaStruct<OpenDDS::DCPS::RepoId>().getValue(ser, field + 9);
} else {
gen_skip_over(ser, static_cast<OpenDDS::DCPS::RepoId*>(0));
}
if (std::strncmp(field, "pubQos.", 7) == 0) {
return getMetaStruct<DDS::PublisherQos>().getValue(ser, field + 7);
} else {
gen_skip_over(ser, static_cast<DDS::PublisherQos*>(0));
}
if (std::strncmp(field, "writerQos.", 10) == 0) {
return getMetaStruct<DDS::DataWriterQos>().getValue(ser, field + 10);
} else {
gen_skip_over(ser, static_cast<DDS::DataWriterQos*>(0));
}
if (!field[0]) {
return 0;
}
throw std::runtime_error("Field " + std::string(field) + " not valid for struct OpenDDS::DCPS::WriterAssociation");
}
ComparatorBase::Ptr create_qc_comparator(const char* field, ComparatorBase::Ptr next) const
{
ACE_UNUSED_ARG(next);
if (std::strncmp(field, "writerId.", 9) == 0) {
return make_struct_cmp(&T::writerId, getMetaStruct<OpenDDS::DCPS::RepoId>().create_qc_comparator(field + 9, 0), next);
}
if (std::strncmp(field, "pubQos.", 7) == 0) {
return make_struct_cmp(&T::pubQos, getMetaStruct<DDS::PublisherQos>().create_qc_comparator(field + 7, 0), next);
}
if (std::strncmp(field, "writerQos.", 10) == 0) {
return make_struct_cmp(&T::writerQos, getMetaStruct<DDS::DataWriterQos>().create_qc_comparator(field + 10, 0), next);
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::WriterAssociation)");
}
const char** getFieldNames() const
{
static const char* names[] = {"writerTransInfo", "writerId", "pubQos", "writerQos", 0};
return names;
}
const void* getRawField(const void* stru, const char* field) const
{
if (std::strcmp(field, "writerTransInfo") == 0) {
return &static_cast<const T*>(stru)->writerTransInfo;
}
if (std::strcmp(field, "writerId") == 0) {
return &static_cast<const T*>(stru)->writerId;
}
if (std::strcmp(field, "pubQos") == 0) {
return &static_cast<const T*>(stru)->pubQos;
}
if (std::strcmp(field, "writerQos") == 0) {
return &static_cast<const T*>(stru)->writerQos;
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::WriterAssociation)");
}
void assign(void* lhs, const char* field, const void* rhs,
const char* rhsFieldSpec, const MetaStruct& rhsMeta) const
{
ACE_UNUSED_ARG(lhs);
ACE_UNUSED_ARG(field);
ACE_UNUSED_ARG(rhs);
ACE_UNUSED_ARG(rhsFieldSpec);
ACE_UNUSED_ARG(rhsMeta);
if (std::strcmp(field, "writerTransInfo") == 0) {
static_cast<T*>(lhs)->writerTransInfo = *static_cast<const OpenDDS::DCPS::TransportLocatorSeq*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
if (std::strcmp(field, "writerId") == 0) {
static_cast<T*>(lhs)->writerId = *static_cast<const OpenDDS::DCPS::RepoId*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
if (std::strcmp(field, "pubQos") == 0) {
static_cast<T*>(lhs)->pubQos = *static_cast<const DDS::PublisherQos*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
if (std::strcmp(field, "writerQos") == 0) {
static_cast<T*>(lhs)->writerQos = *static_cast<const DDS::DataWriterQos*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::WriterAssociation)");
}
bool compare(const void* lhs, const void* rhs, const char* field) const
{
ACE_UNUSED_ARG(lhs);
ACE_UNUSED_ARG(field);
ACE_UNUSED_ARG(rhs);
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::WriterAssociation)");
}
};
template<>
const MetaStruct& getMetaStruct<OpenDDS::DCPS::WriterAssociation>()
{
static MetaStructImpl<OpenDDS::DCPS::WriterAssociation> msi;
return msi;
}
void gen_skip_over(Serializer& ser, OpenDDS::DCPS::WriterAssociation*)
{
ACE_UNUSED_ARG(ser);
MetaStructImpl<OpenDDS::DCPS::WriterAssociation>().getValue(ser, "");
}
} }
#endif
/* End STRUCT: WriterAssociation */
/* Begin STRUCT: ReaderAssociation */
namespace OpenDDS { namespace DCPS {
void gen_find_size(const OpenDDS::DCPS::ReaderAssociation& stru, size_t& size, size_t& padding)
{
ACE_UNUSED_ARG(stru);
ACE_UNUSED_ARG(size);
ACE_UNUSED_ARG(padding);
gen_find_size(stru.readerTransInfo, size, padding);
gen_find_size(stru.readerId, size, padding);
gen_find_size(stru.subQos, size, padding);
gen_find_size(stru.readerQos, size, padding);
find_size_ulong(size, padding);
size += ACE_OS::strlen(stru.filterExpression) + 1;
gen_find_size(stru.exprParams, size, padding);
}
bool operator<<(Serializer& strm, const OpenDDS::DCPS::ReaderAssociation& stru)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(stru);
return (strm << stru.readerTransInfo)
&& (strm << stru.readerId)
&& (strm << stru.subQos)
&& (strm << stru.readerQos)
&& (strm << stru.filterExpression)
&& (strm << stru.exprParams);
}
bool operator>>(Serializer& strm, OpenDDS::DCPS::ReaderAssociation& stru)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(stru);
return (strm >> stru.readerTransInfo)
&& (strm >> stru.readerId)
&& (strm >> stru.subQos)
&& (strm >> stru.readerQos)
&& (strm >> stru.filterExpression.out())
&& (strm >> stru.exprParams);
}
} }
#ifndef OPENDDS_NO_CONTENT_SUBSCRIPTION_PROFILE
namespace OpenDDS { namespace DCPS {
template<>
struct MetaStructImpl<OpenDDS::DCPS::ReaderAssociation> : MetaStruct {
typedef OpenDDS::DCPS::ReaderAssociation T;
void* allocate() const { return new T; }
void deallocate(void* stru) const { delete static_cast<T*>(stru); }
size_t numDcpsKeys() const { return 0; }
Value getValue(const void* stru, const char* field) const
{
const OpenDDS::DCPS::ReaderAssociation& typed = *static_cast<const OpenDDS::DCPS::ReaderAssociation*>(stru);
if (std::strncmp(field, "readerId.", 9) == 0) {
return getMetaStruct<OpenDDS::DCPS::RepoId>().getValue(&typed.readerId, field + 9);
}
if (std::strncmp(field, "subQos.", 7) == 0) {
return getMetaStruct<DDS::SubscriberQos>().getValue(&typed.subQos, field + 7);
}
if (std::strncmp(field, "readerQos.", 10) == 0) {
return getMetaStruct<DDS::DataReaderQos>().getValue(&typed.readerQos, field + 10);
}
if (std::strcmp(field, "filterExpression") == 0) {
return typed.filterExpression.in();
}
ACE_UNUSED_ARG(typed);
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::ReaderAssociation)");
}
Value getValue(Serializer& ser, const char* field) const
{
gen_skip_over(ser, static_cast<OpenDDS::DCPS::TransportLocatorSeq*>(0));
if (std::strncmp(field, "readerId.", 9) == 0) {
return getMetaStruct<OpenDDS::DCPS::RepoId>().getValue(ser, field + 9);
} else {
gen_skip_over(ser, static_cast<OpenDDS::DCPS::RepoId*>(0));
}
if (std::strncmp(field, "subQos.", 7) == 0) {
return getMetaStruct<DDS::SubscriberQos>().getValue(ser, field + 7);
} else {
gen_skip_over(ser, static_cast<DDS::SubscriberQos*>(0));
}
if (std::strncmp(field, "readerQos.", 10) == 0) {
return getMetaStruct<DDS::DataReaderQos>().getValue(ser, field + 10);
} else {
gen_skip_over(ser, static_cast<DDS::DataReaderQos*>(0));
}
if (std::strcmp(field, "filterExpression") == 0) {
TAO::String_Manager val;
if (!(ser >> val.out())) {
throw std::runtime_error("Field 'filterExpression' could not be deserialized");
}
return val;
} else {
ACE_CDR::ULong len;
if (!(ser >> len)) {
throw std::runtime_error("String 'filterExpression' length could not be deserialized");
}
ser.skip(len);
}
gen_skip_over(ser, static_cast<DDS::StringSeq*>(0));
if (!field[0]) {
return 0;
}
throw std::runtime_error("Field " + std::string(field) + " not valid for struct OpenDDS::DCPS::ReaderAssociation");
}
ComparatorBase::Ptr create_qc_comparator(const char* field, ComparatorBase::Ptr next) const
{
ACE_UNUSED_ARG(next);
if (std::strncmp(field, "readerId.", 9) == 0) {
return make_struct_cmp(&T::readerId, getMetaStruct<OpenDDS::DCPS::RepoId>().create_qc_comparator(field + 9, 0), next);
}
if (std::strncmp(field, "subQos.", 7) == 0) {
return make_struct_cmp(&T::subQos, getMetaStruct<DDS::SubscriberQos>().create_qc_comparator(field + 7, 0), next);
}
if (std::strncmp(field, "readerQos.", 10) == 0) {
return make_struct_cmp(&T::readerQos, getMetaStruct<DDS::DataReaderQos>().create_qc_comparator(field + 10, 0), next);
}
if (std::strcmp(field, "filterExpression") == 0) {
return make_field_cmp(&T::filterExpression, next);
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::ReaderAssociation)");
}
const char** getFieldNames() const
{
static const char* names[] = {"readerTransInfo", "readerId", "subQos", "readerQos", "filterExpression", "exprParams", 0};
return names;
}
const void* getRawField(const void* stru, const char* field) const
{
if (std::strcmp(field, "readerTransInfo") == 0) {
return &static_cast<const T*>(stru)->readerTransInfo;
}
if (std::strcmp(field, "readerId") == 0) {
return &static_cast<const T*>(stru)->readerId;
}
if (std::strcmp(field, "subQos") == 0) {
return &static_cast<const T*>(stru)->subQos;
}
if (std::strcmp(field, "readerQos") == 0) {
return &static_cast<const T*>(stru)->readerQos;
}
if (std::strcmp(field, "filterExpression") == 0) {
return &static_cast<const T*>(stru)->filterExpression;
}
if (std::strcmp(field, "exprParams") == 0) {
return &static_cast<const T*>(stru)->exprParams;
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::ReaderAssociation)");
}
void assign(void* lhs, const char* field, const void* rhs,
const char* rhsFieldSpec, const MetaStruct& rhsMeta) const
{
ACE_UNUSED_ARG(lhs);
ACE_UNUSED_ARG(field);
ACE_UNUSED_ARG(rhs);
ACE_UNUSED_ARG(rhsFieldSpec);
ACE_UNUSED_ARG(rhsMeta);
if (std::strcmp(field, "readerTransInfo") == 0) {
static_cast<T*>(lhs)->readerTransInfo = *static_cast<const OpenDDS::DCPS::TransportLocatorSeq*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
if (std::strcmp(field, "readerId") == 0) {
static_cast<T*>(lhs)->readerId = *static_cast<const OpenDDS::DCPS::RepoId*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
if (std::strcmp(field, "subQos") == 0) {
static_cast<T*>(lhs)->subQos = *static_cast<const DDS::SubscriberQos*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
if (std::strcmp(field, "readerQos") == 0) {
static_cast<T*>(lhs)->readerQos = *static_cast<const DDS::DataReaderQos*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
if (std::strcmp(field, "filterExpression") == 0) {
static_cast<T*>(lhs)->filterExpression = *static_cast<const TAO::String_Manager*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
if (std::strcmp(field, "exprParams") == 0) {
static_cast<T*>(lhs)->exprParams = *static_cast<const DDS::StringSeq*>(rhsMeta.getRawField(rhs, rhsFieldSpec));
return;
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::ReaderAssociation)");
}
bool compare(const void* lhs, const void* rhs, const char* field) const
{
ACE_UNUSED_ARG(lhs);
ACE_UNUSED_ARG(field);
ACE_UNUSED_ARG(rhs);
if (std::strcmp(field, "filterExpression") == 0) {
return 0 == ACE_OS::strcmp(static_cast<const T*>(lhs)->filterExpression, static_cast<const T*>(rhs)->filterExpression);
}
throw std::runtime_error("Field " + std::string(field) + " not found or its type is not supported (in struct OpenDDS::DCPS::ReaderAssociation)");
}
};
template<>
const MetaStruct& getMetaStruct<OpenDDS::DCPS::ReaderAssociation>()
{
static MetaStructImpl<OpenDDS::DCPS::ReaderAssociation> msi;
return msi;
}
void gen_skip_over(Serializer& ser, OpenDDS::DCPS::ReaderAssociation*)
{
ACE_UNUSED_ARG(ser);
MetaStructImpl<OpenDDS::DCPS::ReaderAssociation>().getValue(ser, "");
}
} }
#endif
/* End STRUCT: ReaderAssociation */
/* Begin TYPEDEF: WriterIdSeq */
namespace OpenDDS { namespace DCPS {
void gen_find_size(const OpenDDS::DCPS::WriterIdSeq& seq, size_t& size, size_t& padding)
{
ACE_UNUSED_ARG(seq);
ACE_UNUSED_ARG(size);
ACE_UNUSED_ARG(padding);
find_size_ulong(size, padding);
if (seq.length() == 0) {
return;
}
for (CORBA::ULong i = 0; i < seq.length(); ++i) {
gen_find_size(seq[i], size, padding);
}
}
bool operator<<(Serializer& strm, const OpenDDS::DCPS::WriterIdSeq& seq)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(seq);
const CORBA::ULong length = seq.length();
if (!(strm << length)) {
return false;
}
if (length == 0) {
return true;
}
for (CORBA::ULong i = 0; i < length; ++i) {
if (!(strm << seq[i])) {
return false;
}
}
return true;
}
bool operator>>(Serializer& strm, OpenDDS::DCPS::WriterIdSeq& seq)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(seq);
CORBA::ULong length;
if (!(strm >> length)) {
return false;
}
seq.length(length);
for (CORBA::ULong i = 0; i < length; ++i) {
if (!(strm >> seq[i])) {
return false;
}
}
return true;
}
} }
#ifndef OPENDDS_NO_CONTENT_SUBSCRIPTION_PROFILE
namespace OpenDDS { namespace DCPS {
void gen_skip_over(Serializer& ser, OpenDDS::DCPS::WriterIdSeq*)
{
ACE_UNUSED_ARG(ser);
ACE_CDR::ULong length;
ser >> length;
for (ACE_CDR::ULong i = 0; i < length; ++i) {
gen_skip_over(ser, static_cast<OpenDDS::DCPS::RepoId*>(0));
}
}
} }
#endif
/* End TYPEDEF: WriterIdSeq */
/* Begin TYPEDEF: ReaderIdSeq */
namespace OpenDDS { namespace DCPS {
void gen_find_size(const OpenDDS::DCPS::ReaderIdSeq& seq, size_t& size, size_t& padding)
{
ACE_UNUSED_ARG(seq);
ACE_UNUSED_ARG(size);
ACE_UNUSED_ARG(padding);
find_size_ulong(size, padding);
if (seq.length() == 0) {
return;
}
for (CORBA::ULong i = 0; i < seq.length(); ++i) {
gen_find_size(seq[i], size, padding);
}
}
bool operator<<(Serializer& strm, const OpenDDS::DCPS::ReaderIdSeq& seq)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(seq);
const CORBA::ULong length = seq.length();
if (!(strm << length)) {
return false;
}
if (length == 0) {
return true;
}
for (CORBA::ULong i = 0; i < length; ++i) {
if (!(strm << seq[i])) {
return false;
}
}
return true;
}
bool operator>>(Serializer& strm, OpenDDS::DCPS::ReaderIdSeq& seq)
{
ACE_UNUSED_ARG(strm);
ACE_UNUSED_ARG(seq);
CORBA::ULong length;
if (!(strm >> length)) {
return false;
}
seq.length(length);
for (CORBA::ULong i = 0; i < length; ++i) {
if (!(strm >> seq[i])) {
return false;
}
}
return true;
}
} }
#ifndef OPENDDS_NO_CONTENT_SUBSCRIPTION_PROFILE
namespace OpenDDS { namespace DCPS {
void gen_skip_over(Serializer& ser, OpenDDS::DCPS::ReaderIdSeq*)
{
ACE_UNUSED_ARG(ser);
ACE_CDR::ULong length;
ser >> length;
for (ACE_CDR::ULong i = 0; i < length; ++i) {
gen_skip_over(ser, static_cast<OpenDDS::DCPS::RepoId*>(0));
}
}
} }
#endif
/* End TYPEDEF: ReaderIdSeq */
/* End MODULE: DCPS */
/* End MODULE: OpenDDS */
| binary42/OCI | dds/DdsDcpsInfoUtilsTypeSupportImpl.cpp | C++ | mit | 38,722 |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using XSerializer.Encryption;
namespace XSerializer
{
internal static class SerializationExtensions
{
internal const string ReadOnlyDictionary = "System.Collections.ObjectModel.ReadOnlyDictionary`2, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
internal const string IReadOnlyDictionary = "System.Collections.Generic.IReadOnlyDictionary`2, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
internal const string IReadOnlyCollection = "System.Collections.Generic.IReadOnlyCollection`1, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
internal const string IReadOnlyList = "System.Collections.Generic.IReadOnlyList`1, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
private static readonly Type[] _readOnlyCollections = new[] { Type.GetType(IReadOnlyCollection), Type.GetType(IReadOnlyList), typeof(ReadOnlyCollection<>) }.Where(t => t != null).ToArray();
private static readonly ConcurrentDictionary<Tuple<Type, Type>, Func<object, object>> _convertFuncs = new ConcurrentDictionary<Tuple<Type, Type>, Func<object, object>>();
private static readonly Dictionary<Type, string> _typeToXsdTypeMap = new Dictionary<Type, string>();
private static readonly Dictionary<string, Type> _xsdTypeToTypeMap = new Dictionary<string, Type>();
private static readonly ConcurrentDictionary<int, Type> _xsdTypeToTypeCache = new ConcurrentDictionary<int, Type>();
static SerializationExtensions()
{
_typeToXsdTypeMap.Add(typeof(bool), "xsd:boolean");
_typeToXsdTypeMap.Add(typeof(byte), "xsd:unsignedByte");
_typeToXsdTypeMap.Add(typeof(sbyte), "xsd:byte");
_typeToXsdTypeMap.Add(typeof(short), "xsd:short");
_typeToXsdTypeMap.Add(typeof(ushort), "xsd:unsignedShort");
_typeToXsdTypeMap.Add(typeof(int), "xsd:int");
_typeToXsdTypeMap.Add(typeof(uint), "xsd:unsignedInt");
_typeToXsdTypeMap.Add(typeof(long), "xsd:long");
_typeToXsdTypeMap.Add(typeof(ulong), "xsd:unsignedLong");
_typeToXsdTypeMap.Add(typeof(float), "xsd:float");
_typeToXsdTypeMap.Add(typeof(double), "xsd:double");
_typeToXsdTypeMap.Add(typeof(decimal), "xsd:decimal");
_typeToXsdTypeMap.Add(typeof(DateTime), "xsd:dateTime");
_typeToXsdTypeMap.Add(typeof(string), "xsd:string");
foreach (var typeToXsdType in _typeToXsdTypeMap)
{
_xsdTypeToTypeMap.Add(typeToXsdType.Value, typeToXsdType.Key);
}
}
public static string SerializeObject(
this IXmlSerializerInternal serializer,
object instance,
Encoding encoding,
Formatting formatting,
ISerializeOptions options)
{
options = options.WithNewSerializationState();
var sb = new StringBuilder();
using (var stringWriter = new StringWriterWithEncoding(sb, encoding ?? Encoding.UTF8))
{
using (var xmlWriter = new XSerializerXmlTextWriter(stringWriter, options))
{
xmlWriter.Formatting = formatting;
serializer.SerializeObject(xmlWriter, instance, options);
}
}
return sb.ToString();
}
public static void SerializeObject(
this IXmlSerializerInternal serializer,
Stream stream,
object instance,
Encoding encoding,
Formatting formatting,
ISerializeOptions options)
{
options = options.WithNewSerializationState();
StreamWriter streamWriter = null;
try
{
streamWriter = new StreamWriter(stream, encoding ?? Encoding.UTF8);
var xmlWriter = new XSerializerXmlTextWriter(streamWriter, options)
{
Formatting = formatting
};
serializer.SerializeObject(xmlWriter, instance, options);
xmlWriter.Flush();
}
finally
{
if (streamWriter != null)
{
streamWriter.Flush();
}
}
}
public static void SerializeObject(
this IXmlSerializerInternal serializer,
TextWriter writer,
object instance,
Formatting formatting,
ISerializeOptions options)
{
options = options.WithNewSerializationState();
var xmlWriter = new XSerializerXmlTextWriter(writer, options)
{
Formatting = formatting
};
serializer.SerializeObject(xmlWriter, instance, options);
xmlWriter.Flush();
}
public static object DeserializeObject(this IXmlSerializerInternal serializer, string xml, ISerializeOptions options)
{
options = options.WithNewSerializationState();
using (var stringReader = new StringReader(xml))
{
using (var xmlReader = new XmlTextReader(stringReader))
{
using (var reader = new XSerializerXmlReader(xmlReader, options.GetEncryptionMechanism(), options.EncryptKey, options.SerializationState))
{
return serializer.DeserializeObject(reader, options);
}
}
}
}
public static object DeserializeObject(this IXmlSerializerInternal serializer, Stream stream, ISerializeOptions options)
{
options = options.WithNewSerializationState();
var xmlReader = new XmlTextReader(stream);
var reader = new XSerializerXmlReader(xmlReader, options.GetEncryptionMechanism(), options.EncryptKey, options.SerializationState);
return serializer.DeserializeObject(reader, options);
}
public static object DeserializeObject(this IXmlSerializerInternal serializer, TextReader textReader, ISerializeOptions options)
{
options = options.WithNewSerializationState();
var xmlReader = new XmlTextReader(textReader);
var reader = new XSerializerXmlReader(xmlReader, options.GetEncryptionMechanism(), options.EncryptKey, options.SerializationState);
return serializer.DeserializeObject(reader, options);
}
private static ISerializeOptions WithNewSerializationState(this ISerializeOptions serializeOptions)
{
return new SerializeOptions
{
EncryptionMechanism = serializeOptions.EncryptionMechanism,
EncryptKey = serializeOptions.EncryptKey,
Namespaces = serializeOptions.Namespaces,
SerializationState = new SerializationState(),
ShouldAlwaysEmitTypes = serializeOptions.ShouldAlwaysEmitTypes,
ShouldEmitNil = serializeOptions.ShouldEmitNil,
ShouldEncrypt = serializeOptions.ShouldEncrypt,
ShouldRedact = serializeOptions.ShouldRedact,
ShouldIgnoreCaseForEnum = serializeOptions.ShouldIgnoreCaseForEnum,
ShouldSerializeCharAsInt = serializeOptions.ShouldSerializeCharAsInt
};
}
private class SerializeOptions : ISerializeOptions
{
public XmlSerializerNamespaces Namespaces { get; set; }
public bool ShouldAlwaysEmitTypes { get; set; }
public bool ShouldRedact { get; set; }
public bool ShouldEncrypt { get; set; }
public bool ShouldEmitNil { get; set; }
public IEncryptionMechanism EncryptionMechanism { get; set; }
public object EncryptKey { get; set; }
public SerializationState SerializationState { get; set; }
public bool ShouldIgnoreCaseForEnum { get; set; }
public bool ShouldSerializeCharAsInt { get; set; }
}
/// <summary>
/// Maybe sets the <see cref="XSerializerXmlTextWriter.IsEncryptionEnabled"/> property of
/// <paramref name="writer"/> to true. Returns true if the value was changed to true, false
/// if it was not changed to true.
/// </summary>
internal static bool MaybeSetIsEncryptionEnabledToTrue(this XSerializerXmlTextWriter writer, EncryptAttribute encryptAttribute, ISerializeOptions options)
{
if (options.ShouldEncrypt && encryptAttribute != null && !writer.IsEncryptionEnabled)
{
writer.IsEncryptionEnabled = true;
return true;
}
return false;
}
/// <summary>
/// Maybe sets the <see cref="XSerializerXmlTextWriter.IsEncryptionEnabled"/> property of
/// <paramref name="reader"/> to true. Returns true if the value was changed to true, false
/// if it was not changed to true.
/// </summary>
internal static bool MaybeSetIsDecryptionEnabledToTrue(this XSerializerXmlReader reader,
EncryptAttribute encryptAttribute, ISerializeOptions options)
{
if (options.ShouldEncrypt && encryptAttribute != null && !reader.IsDecryptionEnabled)
{
reader.IsDecryptionEnabled = true;
return true;
}
return false;
}
internal static bool HasDefaultConstructor(this Type type)
{
return type.GetConstructor(Type.EmptyTypes) != null;
}
public static bool IsSerializable(this PropertyInfo property, IEnumerable<ParameterInfo> constructorParameters)
{
if (property.DeclaringType.IsAnonymous())
{
return true;
}
if (Attribute.IsDefined(property, typeof(XmlIgnoreAttribute)))
{
return false;
}
var isSerializable = property.GetIndexParameters().Length == 0 && (property.IsReadWriteProperty() || property.IsSerializableReadOnlyProperty(constructorParameters));
return isSerializable;
}
public static bool IsJsonSerializable(this PropertyInfo property, IEnumerable<ParameterInfo> constructorParameters)
{
if (property.DeclaringType.IsAnonymous())
{
return true;
}
if (Attribute.IsDefined(property, typeof(JsonIgnoreAttribute))
|| Attribute.GetCustomAttributes(property).Any(attribute =>
attribute.GetType().FullName == "Newtonsoft.Json.JsonIgnoreAttribute"))
{
return false;
}
var isSerializable = property.GetIndexParameters().Length == 0 && (property.IsReadWriteProperty() || property.IsJsonSerializableReadOnlyProperty(constructorParameters));
return isSerializable;
}
internal static string GetName(this PropertyInfo property)
{
var jsonPropertyAttribute = (JsonPropertyAttribute)Attribute.GetCustomAttribute(property, typeof(JsonPropertyAttribute));
if (jsonPropertyAttribute != null && !string.IsNullOrEmpty(jsonPropertyAttribute.Name))
{
return jsonPropertyAttribute.Name;
}
var newtonsoftJsonPropertyAttribute =
Attribute.GetCustomAttributes(property).FirstOrDefault(attribute =>
attribute.GetType().FullName == "Newtonsoft.Json.JsonPropertyAttribute");
if (newtonsoftJsonPropertyAttribute != null)
{
var propertyNameProperty = newtonsoftJsonPropertyAttribute.GetType().GetProperty("PropertyName");
if (propertyNameProperty != null
&& propertyNameProperty.PropertyType == typeof(string))
{
var propertyName = (string)propertyNameProperty.GetValue(newtonsoftJsonPropertyAttribute, new object[0]);
if (!string.IsNullOrEmpty(propertyName))
{
return propertyName;
}
}
}
return property.Name;
}
internal static bool IsReadWriteProperty(this PropertyInfo property)
{
var isReadWriteProperty = property.HasPublicGetter() && property.HasPublicSetter();
return isReadWriteProperty;
}
internal static bool IsSerializableReadOnlyProperty(this PropertyInfo property, IEnumerable<ParameterInfo> constructorParameters = null)
{
return
property.IsReadOnlyProperty()
&&
!IsConditionalProperty(property, constructorParameters)
&&
(
((constructorParameters ?? Enumerable.Empty<ParameterInfo>()).Any(p => p.Name.ToLower() == property.Name.ToLower() && p.ParameterType == property.PropertyType))
||
(property.PropertyType.IsAnyKindOfDictionary() && property.PropertyType != typeof(ExpandoObject))
||
(property.PropertyType.IsAssignableToGenericIEnumerable() && property.PropertyType.HasAddMethodOfType(property.PropertyType.GetGenericIEnumerableType().GetGenericArguments()[0]))
||
(property.PropertyType.IsAssignableToNonGenericIEnumerable() && property.PropertyType.HasAddMethod())
||
(property.PropertyType.IsReadOnlyCollection())
||
(property.PropertyType.IsArray && property.PropertyType.GetArrayRank() == 1)
||
(property.PropertyType.IsReadOnlyDictionary())
); // TODO: add additional serializable types?
}
internal static bool IsJsonSerializableReadOnlyProperty(this PropertyInfo propertyInfo, IEnumerable<ParameterInfo> constructorParameters = null)
{
if (!propertyInfo.IsReadOnlyProperty())
{
return false;
}
if (constructorParameters != null && constructorParameters.Any(p => string.Equals(p.Name, propertyInfo.Name, StringComparison.OrdinalIgnoreCase)))
{
return true;
}
if (typeof(IDictionary).IsAssignableFrom(propertyInfo.PropertyType)
|| propertyInfo.PropertyType.IsAssignableToGenericIDictionary())
{
return true;
}
if (propertyInfo.PropertyType.IsArray)
{
return false;
}
if (typeof(IList).IsAssignableFrom(propertyInfo.PropertyType)
|| propertyInfo.PropertyType.IsAssignableToGenericICollection())
{
return true;
}
return false;
}
internal static object ConvertIfNecessary(this object instance, Type targetType)
{
if (instance == null)
{
return null;
}
var instanceType = instance.GetType();
if (targetType.IsAssignableFrom(instanceType))
{
return instance;
}
var convertFunc =
_convertFuncs.GetOrAdd(
Tuple.Create(instanceType, targetType),
tuple => CreateConvertFunc(tuple.Item1, tuple.Item2));
return convertFunc(instance);
}
private static Func<object, object> CreateConvertFunc(Type instanceType, Type targetType)
{
if (instanceType.IsGenericType && instanceType.GetGenericTypeDefinition() == typeof(List<>))
{
if (targetType.IsArray)
{
return CreateToArrayFunc(targetType.GetElementType());
}
if (targetType.IsReadOnlyCollection())
{
var collectionType = targetType.GetReadOnlyCollectionType();
return CreateAsReadOnlyFunc(collectionType.GetGenericArguments()[0]);
}
}
// Oh well, we were gonna throw anyway. Just let it happen...
return x => x;
}
private static Func<object, object> CreateToArrayFunc(Type itemType)
{
var toArrayMethod =
typeof(Enumerable)
.GetMethod("ToArray", BindingFlags.Static | BindingFlags.Public)
.MakeGenericMethod(itemType);
var sourceParameter = Expression.Parameter(typeof(object), "source");
var lambda =
Expression.Lambda<Func<object, object>>(
Expression.Call(
toArrayMethod,
Expression.Convert(sourceParameter, typeof(IEnumerable<>).MakeGenericType(itemType))),
sourceParameter);
return lambda.Compile();
}
private static Func<object, object> CreateAsReadOnlyFunc(Type itemType)
{
var listType = typeof (List<>).MakeGenericType(itemType);
var asReadOnlyMethod = listType.GetMethod("AsReadOnly", BindingFlags.Instance | BindingFlags.Public);
var instanceParameter = Expression.Parameter(typeof(object), "instance");
var lambda =
Expression.Lambda<Func<object, object>>(
Expression.Call(
Expression.Convert(instanceParameter, listType),
asReadOnlyMethod),
instanceParameter);
return lambda.Compile();
}
internal static bool IsReadOnlyCollection(this Type type)
{
var openGenerics = GetOpenGenerics(type);
foreach (var openGeneric in openGenerics)
{
if (openGeneric == typeof(ReadOnlyCollection<>))
{
return true;
}
switch (openGeneric.AssemblyQualifiedName)
{
case IReadOnlyCollection:
case IReadOnlyList:
return true;
}
}
return false;
}
internal static Type GetReadOnlyCollectionType(this Type type)
{
if (IsReadOnlyCollectionType(type))
{
return type;
}
var interfaceType = type.GetInterfaces().FirstOrDefault(IsReadOnlyCollectionType);
if (interfaceType != null)
{
return interfaceType;
}
do
{
type = type.BaseType;
if (type == null)
{
return null;
}
if (IsReadOnlyCollectionType(type))
{
return type;
}
} while (true);
}
private static bool IsReadOnlyCollectionType(Type i)
{
if (i.IsGenericType)
{
var genericTypeDefinition = i.GetGenericTypeDefinition();
if (_readOnlyCollections.Any(readOnlyCollectionType => genericTypeDefinition == readOnlyCollectionType))
{
return true;
}
}
return false;
}
internal static bool IsReadOnlyDictionary(this Type type)
{
var openGenerics = GetOpenGenerics(type);
foreach (var openGeneric in openGenerics)
{
switch (openGeneric.AssemblyQualifiedName)
{
case IReadOnlyDictionary:
case ReadOnlyDictionary:
return true;
}
}
return false;
}
internal static Type GetIReadOnlyDictionaryInterface(this Type type)
{
var iReadOnlyDictionaryType = Type.GetType(IReadOnlyDictionary);
if (type.IsGenericType && type.GetGenericTypeDefinition() == iReadOnlyDictionaryType)
{
return type;
}
return
type.GetInterfaces()
.FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == iReadOnlyDictionaryType);
}
private static IEnumerable<Type> GetOpenGenerics(Type type)
{
if (type.IsGenericType)
{
yield return type.GetGenericTypeDefinition();
}
foreach (var interfaceType in type.GetInterfaces())
{
if (interfaceType.IsGenericType)
{
yield return interfaceType;
}
}
while (true)
{
type = type.BaseType;
if (type == null)
{
yield break;
}
if (type.IsGenericType)
{
yield return type.GetGenericTypeDefinition();
}
}
}
private static bool IsConditionalProperty(PropertyInfo property, IEnumerable<ParameterInfo> constructorParameters)
{
if (property.Name.EndsWith("Specified"))
{
var otherPropertyName = property.Name.Substring(0, property.Name.LastIndexOf("Specified"));
return property.DeclaringType.GetProperties().Any(p => p.Name == otherPropertyName);
}
return false;
}
internal static bool HasAddMethodOfType(this Type type, Type addMethodType)
{
return type.GetMethod("Add", new[] { addMethodType }) != null;
}
internal static bool HasAddMethod(this Type type)
{
return type.GetMethods().Any(m => m.Name == "Add" && m.GetParameters().Length == 1);
}
internal static bool IsAnyKindOfDictionary(this Type type)
{
return type.IsAssignableToNonGenericIDictionary() || type.IsAssignableToGenericIDictionary();
}
internal static bool IsReadOnlyProperty(this PropertyInfo property)
{
var canCallGetter = property.HasPublicGetter();
var canCallSetter = property.HasPublicSetter();
return canCallGetter && !canCallSetter;
}
internal static bool IsAssignableToNonGenericIDictionary(this Type type)
{
var isAssignableToIDictionary = typeof(IDictionary).IsAssignableFrom(type);
return isAssignableToIDictionary;
}
internal static bool IsGenericIDictionary(this Type type)
{
return type.IsInterface
&& type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(IDictionary<,>);
}
internal static bool IsAssignableToGenericIDictionary(this Type type)
{
var isAssignableToGenericIDictionary =
(type.IsInterface && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>))
|| type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>));
return isAssignableToGenericIDictionary;
}
internal static bool IsAssignableToGenericIDictionaryWithKeyOrValueOfTypeObject(this Type type)
{
var isAssignableToGenericIDictionary = type.IsAssignableToGenericIDictionary();
if (!isAssignableToGenericIDictionary)
{
return false;
}
Type iDictionaryType;
if (type.IsInterface && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>))
{
iDictionaryType = type;
}
else
{
iDictionaryType = type.GetInterfaces().Single(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>));
}
return iDictionaryType.GetGenericArguments()[0] == typeof(object) || iDictionaryType.GetGenericArguments()[1] == typeof(object);
}
internal static bool IsAssignableToGenericIDictionaryOfStringToAnything(this Type type)
{
if (type.IsAssignableToGenericIDictionary())
{
var dictionaryType = type.GetGenericIDictionaryType();
var args = dictionaryType.GetGenericArguments();
return args[0] == typeof(string);
}
return false;
}
internal static bool IsAssignableToNonGenericIEnumerable(this Type type)
{
var isAssignableToIEnumerable = typeof(IEnumerable).IsAssignableFrom(type);
return isAssignableToIEnumerable;
}
internal static bool IsGenericIEnumerable(this Type type)
{
return type.IsInterface
&& type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(IEnumerable<>);
}
internal static bool IsAssignableToGenericIEnumerable(this Type type)
{
var isAssignableToGenericIEnumerable =
type.IsGenericIEnumerable()
|| type.GetInterfaces().Any(i => i.IsGenericIEnumerable());
return isAssignableToGenericIEnumerable;
}
internal static bool IsAssignableToGenericIEnumerableOfTypeObject(this Type type)
{
var isAssignableToGenericIEnumerable = type.IsAssignableToGenericIEnumerable();
if (!isAssignableToGenericIEnumerable)
{
return false;
}
var iEnumerableType =
type.IsGenericIEnumerable()
? type
: type.GetInterfaces().Single(i => i.IsGenericIEnumerable());
return iEnumerableType.GetGenericArguments()[0] == typeof(object);
}
internal static bool IsGenericICollection(this Type type)
{
return type.IsInterface
&& type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(ICollection<>);
}
internal static bool IsAssignableToGenericICollection(this Type type)
{
var isAssignableToGenericICollection =
type.IsGenericICollection()
|| type.GetInterfaces().Any(i => i.IsGenericICollection());
return isAssignableToGenericICollection;
}
internal static Type GetGenericIDictionaryType(this Type type)
{
if (type.IsInterface && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>))
{
return type;
}
return type.GetInterfaces().First(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>));
}
internal static Type GetGenericIEnumerableType(this Type type)
{
if (type.IsGenericIEnumerable())
{
return type;
}
return type.GetInterfaces().First(i => i.IsGenericIEnumerable());
}
internal static Type GetGenericICollectionType(this Type type)
{
if (type.IsGenericICollection())
{
return type;
}
return type.GetInterfaces().First(i => i.IsGenericICollection());
}
private static bool HasPublicGetter(this PropertyInfo property)
{
if (!property.CanRead)
{
return false;
}
var getMethod = property.GetGetMethod();
return getMethod != null && getMethod.IsPublic;
}
private static bool HasPublicSetter(this PropertyInfo property)
{
if (!property.CanWrite)
{
return false;
}
var setMethod = property.GetSetMethod();
return setMethod != null && setMethod.IsPublic;
}
internal static bool ReadIfNeeded(this XSerializerXmlReader reader, bool shouldRead)
{
if (shouldRead)
{
return reader.Read();
}
return true;
}
internal static bool IsNil(this XSerializerXmlReader reader)
{
var nilFound = false;
while (reader.MoveToNextAttribute())
{
if (reader.LocalName == "nil" && reader.NamespaceURI == "http://www.w3.org/2001/XMLSchema-instance")
{
nilFound = true;
break;
}
}
reader.MoveToElement();
return nilFound;
}
internal static void WriteNilAttribute(this XmlWriter writer)
{
writer.WriteAttributeString("xsi", "nil", null, "true");
}
internal static bool IsPrimitiveLike(this Type type)
{
return
type.IsPrimitive
|| type.IsEnum
|| type == typeof(string)
|| type == typeof(decimal)
|| type == typeof(DateTime)
|| type == typeof(Guid)
|| type == typeof(TimeSpan)
|| type == typeof(DateTimeOffset);
}
internal static bool IsNullablePrimitiveLike(this Type type)
{
return
type.IsNullableType()
&& type.GetGenericArguments()[0].IsPrimitiveLike();
}
internal static bool IsNullableType(this Type type)
{
return type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
internal static bool IsReferenceType(this Type type)
{
return !type.IsValueType;
}
internal static object GetUninitializedObject(this Type type)
{
return FormatterServices.GetUninitializedObject(type);
}
public static bool IsAnonymous(this object instance)
{
if (instance == null)
{
return false;
}
return instance.GetType().IsAnonymous();
}
public static bool IsAnonymous(this Type type)
{
return
type.Namespace == null
&& type.IsClass
&& type.IsNotPublic
&& type.IsSealed
&& type.DeclaringType == null
&& type.BaseType == typeof(object)
&& (type.Name.StartsWith("<>", StringComparison.OrdinalIgnoreCase) || type.Name.StartsWith("VB$", StringComparison.OrdinalIgnoreCase))
&& type.Name.Contains("AnonymousType")
&& Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute));
}
public static string GetElementName(this Type type)
{
if (type.IsGenericType)
{
return type.Name.Substring(0, type.Name.IndexOf("`")) + "Of" + string.Join("_", type.GetGenericArguments().Select(x => x.GetElementName()));
}
if (type.IsArray)
{
return "ArrayOf" + type.GetElementType().Name;
}
return type.Name;
}
public static string GetXsdType(this Type type)
{
string xsdType;
if (_typeToXsdTypeMap.TryGetValue(type, out xsdType))
{
return xsdType;
}
return type.Name;
}
public static Type GetXsdType<T>(this XSerializerXmlReader reader, Type[] extraTypes)
{
string typeName = null;
while (reader.MoveToNextAttribute())
{
if (reader.LocalName == "type" && reader.LookupNamespace(reader.Prefix) == "http://www.w3.org/2001/XMLSchema-instance")
{
typeName = reader.Value;
break;
}
}
reader.MoveToElement();
if (typeName == null)
{
return null;
}
Type typeFromXsdType;
if (_xsdTypeToTypeMap.TryGetValue(typeName, out typeFromXsdType))
{
return typeFromXsdType;
}
return _xsdTypeToTypeCache.GetOrAdd(
CreateTypeCacheKey<T>(typeName),
_ =>
{
Type type = null;
//// try REAL hard to get the type. (holy crap, this is UUUUUGLY!!!!)
if (extraTypes != null)
{
var matchingExtraTypes = extraTypes.Where(t => t.Name == typeName && typeof(T).IsAssignableFrom(t)).ToList();
if (matchingExtraTypes.Count == 1)
{
type = matchingExtraTypes[0];
}
}
if (type == null)
{
var typeNameWithPossibleNamespace = typeName;
if (!typeName.Contains('.'))
{
typeNameWithPossibleNamespace = typeof(T).Namespace + "." + typeName;
}
var checkPossibleNamespace = typeName != typeNameWithPossibleNamespace;
type = Type.GetType(typeName);
type = typeof(T).IsAssignableFrom(type) ? type : null;
if (type == null)
{
type = checkPossibleNamespace ? Type.GetType(typeNameWithPossibleNamespace) : null;
type = typeof(T).IsAssignableFrom(type) ? type : null;
if (type == null)
{
type = typeof(T).Assembly.GetType(typeName);
type = typeof(T).IsAssignableFrom(type) ? type : null;
if (type == null)
{
type = checkPossibleNamespace ? typeof(T).Assembly.GetType(typeNameWithPossibleNamespace) : null;
type = typeof(T).IsAssignableFrom(type) ? type : null;
if (type == null)
{
var matches = typeof(T).Assembly.GetTypes().Where(t => t.Name == typeName && typeof(T).IsAssignableFrom(t)).ToList();
if (matches.Count == 1)
{
type = matches.Single();
}
var entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null)
{
type = entryAssembly.GetType(typeName);
type = typeof(T).IsAssignableFrom(type) ? type : null;
if (type == null)
{
type = checkPossibleNamespace ? entryAssembly.GetType(typeNameWithPossibleNamespace) : null;
type = typeof(T).IsAssignableFrom(type) ? type : null;
}
if (type == null)
{
matches = entryAssembly.GetTypes().Where(t => t.Name == typeName && typeof(T).IsAssignableFrom(t)).ToList();
if (matches.Count == 1)
{
type = matches.Single();
}
}
}
if (type == null)
{
matches = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a =>
{
try
{
return a.GetTypes();
}
catch
{
return Enumerable.Empty<Type>();
}
}).Where(t => t.Name == typeName && typeof(T).IsAssignableFrom(t)).ToList();
if (matches.Count == 1)
{
type = matches.Single();
}
else if (matches.Count > 1)
{
throw new SerializationException(string.Format("More than one type matches '{0}'. Consider decorating your type with the XmlIncludeAttribute, or pass in the type into the serializer as an extra type.", typeName));
}
}
}
}
}
}
}
if (type == null)
{
throw new SerializationException(string.Format("No suitable type matches '{0}'. Consider decorating your type with the XmlIncludeAttribute, or pass in the type into the serializer as an extra type.", typeName));
}
return type;
});
}
private static int CreateTypeCacheKey<T>(string typeName)
{
unchecked
{
var key = typeof(T).GetHashCode();
key = (key * 397) ^ typeName.GetHashCode();
return key;
}
}
}
} | rlyczynski/XSerializer | XSerializer/SerializationExtensions.cs | C# | mit | 39,564 |
'''
utils.py: helper functions for DLP api
Copyright (c) 2017 Vanessa Sochat
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.
'''
from som.logger import bot
import os
import sys
def paginate_items(items,size=100):
'''paginate_items will return a list of lists, each of a particular max
size
'''
groups = []
for idx in range(0, len(items), size):
group = items[idx:idx+size]
groups.append(group)
return groups
def clean_text(text,findings):
'''clean_text will remove phi findings from a text object
:param text: the original text sent to the content.inspect DLP endpoint
:param findings: the full response for the text.
'''
if 'findings' in findings:
for finding in findings['findings']:
label = "**%s**" %finding['infoType']['name']
# Note sure if this is best strategy, we can start with it
text = text.replace(finding['quote'],label)
return text
| radinformatics/som-tools | som/api/google/dlp/utils.py | Python | mit | 1,944 |
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
// import org.apache.commons.cli.*;
class Dumper {
private static FileOutputStream fstream;
public Dumper(String filename) {
try {
fstream = new FileOutputStream(filename);
} catch (FileNotFoundException ex) {
Logger.getLogger(Dumper.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Dump byte array to a file
*
* @param dump byte array
* @param filename
*/
static void dump(byte[] dump, String filename) {
if (dump == null) {
return;
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filename);
} catch (FileNotFoundException ex) {
Logger.getLogger(ST_decrypt.class.getName()).log(Level.SEVERE, null, ex);
}
try {
fos.write(dump, 0, dump.length);
fos.flush();
fos.close();
} catch (IOException ex) {
Logger.getLogger(ST_decrypt.class.getName()).log(Level.SEVERE, null, ex);
}
}
void append(byte[] b) {
try {
fstream.write(b);
} catch (IOException ex) {
Logger.getLogger(Dumper.class.getName()).log(Level.SEVERE, null, ex);
}
}
void close() {
try {
fstream.close();
} catch (IOException ex) {
Logger.getLogger(Dumper.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class Crypto {
private static int d(final int n) {
final long n2 = n & 0xFFFFFFFFL;
return (int) ((n2 & 0x7F7F7F7FL) << 1 ^ ((n2 & 0xFFFFFFFF80808080L) >> 7) * 27L);
}
private static int a(final int n, final int n2) {
final long n3 = n & 0xFFFFFFFFL;
return (int) (n3 >> n2 * 8 | n3 << 32 - n2 * 8);
}
static int polynom2(int n) {
final int d3;
final int d2;
final int d = d(d2 = d(d3 = d(n)));
n ^= d;
return d3 ^ (d2 ^ d ^ a(d3 ^ n, 3) ^ a(d2 ^ n, 2) ^ a(n, 1));
}
static int polynom(int n) {
return (d(n) ^ a(n ^ d(n), 3) ^ a(n, 2) ^ a(n, 1));
}
}
public class ST_decrypt {
/**
* Encrypt or decrypt input file
*/
private static boolean encrypt;
private static String encryptionKey;
private static Dumper dumper;
public static void main(String[] args) {
// CommandLineParser parser = new DefaultParser();
// Options options = new Options();
// String help = "st_decrypt.jar [-e] -k <key> -i <input> -o <output>";
// options.addOption("k", "key", true, "encryption key");
// options.addOption("e", "encrypt", false, "encrypt binary");
// options.addOption("i", "input", true, "input file");
// options.addOption("o", "output", true, "output file");
// HelpFormatter formatter = new HelpFormatter();
// CommandLine opts = null;
// try {
// opts = parser.parse(options, args);
// if (opts.hasOption("key")
// && opts.hasOption("input")
// && opts.hasOption("output")) {
// encryptionKey = opts.getOptionValue("key");
// } else {
// formatter.printHelp(help, options);
// System.exit(1);
// }
// encrypt = opts.hasOption("encrypt");
// } catch (ParseException exp) {
// System.out.println(exp.getMessage());
// formatter.printHelp(help, options);
// System.exit(1);
// }
// String output = "/home/jonathan/stm_jig/usb_sniff/f2_5_dec_java.bin";
// String input = "/home/jonathan/stm_jig/usb_sniff/f2_5.bin";
// String output = "/home/jonathan/stm_jig/usb_sniff/16_encrypted";
// String input = "/home/jonathan/stm_jig/usb_sniff/16_unencrypted";
// String output = "/home/jonathan/stm_jig/usb_sniff/f2_5_dec_java_enc.bin";
// String input = "/home/jonathan/stm_jig/usb_sniff/f2_5_dec_java.bin";
// encryptionKey = "I am a key, wawawa";
// // encryptionKey = unHex("496CDB76964E46637CC0237ED87B6B7F");
// // encryptionKey = unHex("E757D2F9F122DEB3FB883ECC1AF4C688");
// // encryptionKey = unHex("8DBDA2460CD8069682D3E9BB755B7FB9");
// encryptionKey = unHex("5F4946053BD9896E8F4CE917A6D2F21A");
// encrypt=true;
encryptionKey = "best performance";
int dataLength = 30720;//(int)getFileLen("/home/jonathan/stm_jig/provisioning-jig/fw_update/fw_upgrade/f2_1.bin");
byte[] fw = new byte[dataLength];
byte[] key = new byte[16];//encryptionKey.getBytes();
byte[] data = new byte[dataLength];// {0xF7, 0x72, 0x44, 0xB3, 0xFC, 0x86, 0xE0, 0xDC, 0x20, 0xE1, 0x74, 0x2D, 0x3A, 0x29, 0x0B, 0xD2};
str_to_arr(encryptionKey, key);
readFileIntoArr(System.getProperty("user.dir") + "/f2_1.bin", data);
decrypt(data, fw, key, dataLength);
System.out.println(dataLength);
System.out.println(toHexStr(fw).length());
// Write out the decrypted fw for debugging
String outf = "fw_decrypted.bin";
dumper = new Dumper(outf);
dumper.dump(fw, outf);
dumper.close();
// fw now contains our decrypted firmware
// Make a key from the first 4 and last 12 bytes returned by f308
encryptionKey = "I am key, wawawa";
byte[] newKey = new byte[16];
byte[] f308 = new byte[16];
str_to_arr(encryptionKey, key);
readFileIntoArr("f303_bytes_4_12.bin", f308);
encrypt(f308, newKey, key, 16);
System.out.print("Using key: ");
System.out.println(toHexStr(newKey));
System.out.print("From bytes: ");
System.out.println(toHexStr(f308));
byte[] enc_fw = new byte[dataLength];
encrypt(fw, enc_fw, newKey, dataLength);
// System.out.println(toHexStr(enc_fw));
// Now for real
String outfile = "fw_re_encrypted.bin";
dumper = new Dumper(outfile);
dumper.dump(enc_fw, outfile);
dumper.close();
byte[] a = new byte[16];
byte[] ans = new byte[16];
str_to_arr(unHex("ffffffffffffffffffffffffd32700a5"), a);
encrypt(a, ans, newKey, 16);
System.out.println("Final 16 bytes: " + toHexStr(ans));
outfile = "version_thingee_16.bin";
dumper = new Dumper(outfile);
dumper.dump(ans, outfile);
dumper.close();
// dumper = new Dumper(output);
// dump_fw(input);
// dumper.close();
// System.out.println("Done!");
}
// ***************** MY Code functions ***************** JW
static void readFileIntoArr(String file, byte[] data){
FileInputStream fis = null;
try {
File f = new File(file);
fis = new FileInputStream(f);
} catch (Exception ex) {
System.out.print(file);
System.out.println("Invalid file name");
System.exit(1);
}
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(fis)) {
long len = getFileLen(file);
bufferedInputStream.read(data);
} catch (IOException ex) {
Logger.getLogger(ST_decrypt.class.getName()).log(Level.SEVERE, null, ex);
}
}
static String toHexStr(byte[] B){
StringBuilder str = new StringBuilder();
for(int i = 0; i < B.length; i++){
str.append(String.format("%02x", B[i]));
}
return str.toString();
}
static String unHex(String arg) {
String str = "";
for(int i=0;i<arg.length();i+=2)
{
String s = arg.substring(i, (i + 2));
int decimal = Integer.parseInt(s, 16);
str = str + (char) decimal;
}
return str;
}
// *******************************************************
static long getFileLen(String file) {
long n2 = 0L;
FileInputStream fis = null;
try {
File f = new File(file);
fis = new FileInputStream(f);
} catch (Exception ex) {
}
try {
BufferedInputStream bufferedInputStream = new BufferedInputStream(fis);
while (true) {
int read;
try {
read = bufferedInputStream.read();
} catch (IOException ex) {
System.out.println("Failure opening file");
read = -1;
}
if (read == -1) {
break;
}
++n2;
}
bufferedInputStream.close();
} catch (IOException ex3) {
System.out.println("Failure getting firmware data");
}
return n2;
}
/**
*
* @param array firmware byte array
* @param n length
* @param n2 ??
* @return
*/
static long encodeAndWrite(final byte[] array, long n, final int n2) {
long a = 0L;
final byte[] array2 = new byte[4 * ((array.length + 3) / 4)]; // Clever hack to get multiple of fourwith padding
final byte[] array3 = new byte[16];
str_to_arr(encryptionKey, array3);
if (encrypt) {
encrypt(array, array2, array3, array.length);
} else {
decrypt(array, array2, array3, array.length);
}
/* Send chunk of data to device */
dumper.append(array2);
return a;
}
static long writeFirmware(final BufferedInputStream bufferedInputStream, final long n) {
long a = 0L;
final byte[] array = new byte[3072];
long n4 = 0L;
try {
while (n4 < n && a == 0L) {
final long n5;
if ((n5 = bufferedInputStream.read(array)) != -1L) {
encodeAndWrite(array, n4 + 134234112L, 3072);
n4 += n5;
}
}
} catch (IOException ex) {
System.out.println("Failure reading file: " + ex.getMessage());
System.exit(1);
}
return a;
}
static void dump_fw(String file) {
FileInputStream fis = null;
try {
File f = new File(file);
fis = new FileInputStream(f);
} catch (Exception ex) {
System.out.println("Invalid file name");
System.exit(1);
}
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(fis)) {
long len = getFileLen(file);
writeFirmware(bufferedInputStream, len);
} catch (IOException ex) {
Logger.getLogger(ST_decrypt.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static int pack_u32(final int n, final int n2, final int n3, final int n4) {
return (n << 24 & 0xFF000000) + (n2 << 16 & 0xFF0000) + (n3 << 8 & 0xFF00) + (n4 & 0xFF);
}
private static int u32(final int n) {
return n >>> 24;
}
private static int u16(final int n) {
return n >> 16 & 0xFF;
}
private static int u8(final int n) {
return n >> 8 & 0xFF;
}
/**
* Converts the key from String to byte array
*
* @param s input string
* @param array destination array
*/
public static void str_to_arr(final String s, final byte[] array) {
final char[] charArray = s.toCharArray();
for (int i = 0; i < 16; ++i) {
array[i] = (byte) charArray[i];
}
}
private static void key_decode(final byte[] array, final int[] array2) { // core.a.a(byte[], byte[])
final int[] array3 = new int[4];
for (int i = 0; i < 4; ++i) {
array2[i] = (array3[i] = ByteBuffer.wrap(array).order(ByteOrder.LITTLE_ENDIAN).getInt(4 * i));
}
for (int j = 0; j < 10;) {
array3[0] ^= (int) (pack_u32(aes_x[u16(array3[3])], aes_x[u8(array3[3])], aes_x[array3[3] & 0xFF], aes_x[u32(array3[3])]) ^ rcon[j++]);
array3[1] ^= array3[0];
array3[2] ^= array3[1];
array3[3] ^= array3[2];
System.arraycopy(array3, 0, array2, 4 * j, 4);
}
}
/**
* Encrypt firmware file
*/
static void encrypt(final byte[] src, final byte[] dest, byte[] key, int len) {
final byte[] array3 = new byte[16];
int n = 0;
key_decode(key, mystery_key);
while (len > 0) {
key = null;
int n2;
if (len >= 16) {
key = Arrays.copyOfRange(src, n, n + 16);
n2 = 16;
} else if ((n2 = len) > 0) {
final byte[] array4 = new byte[16];
for (int j = 0; j < len; ++j) {
array4[j] = src[n + j];
}
for (int k = len; k < 16; ++k) {
array4[k] = (byte) Double.doubleToLongBits(Math.random());
}
key = array4;
}
if (len > 0) {
final int[] a = mystery_key;
final int[] tmp = new int[4];
int n3 = 10;
int n4 = 0;
for (int l = 0; l < 4; ++l) {
tmp[l] = (ByteBuffer.wrap(key).order(ByteOrder.LITTLE_ENDIAN).getInt(4 * l) ^ a[l + 0]);
}
n4 += 4;
do {
final int a2 = pack_u32(aes_x[u32(tmp[0])], aes_x[u16(tmp[1])], aes_x[u8(tmp[2])], aes_x[tmp[3] & 0xFF]);
final int a3 = pack_u32(aes_x[u32(tmp[1])], aes_x[u16(tmp[2])], aes_x[u8(tmp[3])], aes_x[tmp[0] & 0xFF]);
final int a4 = pack_u32(aes_x[u32(tmp[2])], aes_x[u16(tmp[3])], aes_x[u8(tmp[0])], aes_x[tmp[1] & 0xFF]);
final int a5 = pack_u32(aes_x[u32(tmp[3])], aes_x[u16(tmp[0])], aes_x[u8(tmp[1])], aes_x[tmp[2] & 0xFF]);
tmp[0] = (Crypto.polynom(a2) ^ a[n4]);
tmp[1] = (Crypto.polynom(a3) ^ a[n4 + 1]);
tmp[2] = (Crypto.polynom(a4) ^ a[n4 + 2]);
tmp[3] = (Crypto.polynom(a5) ^ a[n4 + 3]);
n4 += 4;
} while (--n3 != 1);
final int a6 = pack_u32(aes_x[u32(tmp[0])], aes_x[u16(tmp[1])], aes_x[u8(tmp[2])], aes_x[tmp[3] & 0xFF]);
final int a7 = pack_u32(aes_x[u32(tmp[1])], aes_x[u16(tmp[2])], aes_x[u8(tmp[3])], aes_x[tmp[0] & 0xFF]);
final int a8 = pack_u32(aes_x[u32(tmp[2])], aes_x[u16(tmp[3])], aes_x[u8(tmp[0])], aes_x[tmp[1] & 0xFF]);
final int a9 = pack_u32(aes_x[u32(tmp[3])], aes_x[u16(tmp[0])], aes_x[u8(tmp[1])], aes_x[tmp[2] & 0xFF]);
final int n5 = a6 ^ a[n4];
final int n6 = a7 ^ a[n4 + 1];
final int n7 = a8 ^ a[n4 + 2];
final int n8 = a9 ^ a[n4 + 3];
ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(n5);
ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(4, n6);
ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(8, n7);
ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(12, n8);
}
for (int i = 0; i < 16; ++i) {
dest[n + i] = array3[i];
}
len -= n2;
n += n2;
}
}
/**
* Decrypt firmware file
*
* @param src firmware file
* @param dest destination array
* @param key key
* @param len array.length
*/
static void decrypt(final byte[] src, final byte[] dest, byte[] key, int len) {
final byte[] array3 = new byte[16];
int n = 0;
key_decode(key, mystery_key);
while (len > 0) {
key = null;
int n2;
if (len >= 16) {
key = Arrays.copyOfRange(src, n, n + 16);
n2 = 16;
} else if ((n2 = len) > 0) {
final byte[] array4 = new byte[16];
for (int j = 0; j < len; ++j) {
array4[j] = src[n + j];
}
for (int k = len; k < 16; ++k) {
array4[k] = (byte) Double.doubleToLongBits(Math.random());
}
key = array4;
}
if (len > 0) {
final int[] a = mystery_key;
final int[] tmp = new int[4];
int n3 = 10;
int n4 = 40;
for (int l = 0; l < 4; ++l) {
tmp[l] = (ByteBuffer.wrap(key).order(ByteOrder.LITTLE_ENDIAN).getInt(4 * l) ^ a[l + 40]);
}
n4 -= 8;
do {
final int n5 = pack_u32(aes_y[u32(tmp[0])], aes_y[u16(tmp[3])], aes_y[u8(tmp[2])], aes_y[tmp[1] & 0xFF]) ^ a[n4 + 4];
final int n6 = pack_u32(aes_y[u32(tmp[1])], aes_y[u16(tmp[0])], aes_y[u8(tmp[3])], aes_y[tmp[2] & 0xFF]) ^ a[n4 + 5];
final int n7 = pack_u32(aes_y[u32(tmp[2])], aes_y[u16(tmp[1])], aes_y[u8(tmp[0])], aes_y[tmp[3] & 0xFF]) ^ a[n4 + 6];
final int n8 = pack_u32(aes_y[u32(tmp[3])], aes_y[u16(tmp[2])], aes_y[u8(tmp[1])], aes_y[tmp[0] & 0xFF]) ^ a[n4 + 7];
tmp[0] = Crypto.polynom2(n5);
tmp[1] = Crypto.polynom2(n6);
tmp[2] = Crypto.polynom2(n7);
tmp[3] = Crypto.polynom2(n8);
n4 -= 4;
} while (--n3 != 1);
final int n9 = pack_u32(aes_y[u32(tmp[0])], aes_y[u16(tmp[3])], aes_y[u8(tmp[2])], aes_y[tmp[1] & 0xFF]) ^ a[n4 + 4];
final int n10 = pack_u32(aes_y[u32(tmp[1])], aes_y[u16(tmp[0])], aes_y[u8(tmp[3])], aes_y[tmp[2] & 0xFF]) ^ a[n4 + 5];
final int n11 = pack_u32(aes_y[u32(tmp[2])], aes_y[u16(tmp[1])], aes_y[u8(tmp[0])], aes_y[tmp[3] & 0xFF]) ^ a[n4 + 6];
final int n12 = pack_u32(aes_y[u32(tmp[3])], aes_y[u16(tmp[2])], aes_y[u8(tmp[1])], aes_y[tmp[0] & 0xFF]) ^ a[n4 + 7];
ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(n9);
ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(4, n10);
ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(8, n11);
ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(12, n12);
}
for (int i = 0; i < n2; ++i) {
dest[n + i] = array3[i];
}
len -= n2;
n += n2;
}
}
static int[] mystery_key = new int[44];
static int[] aes_x = {
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B,
0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0,
0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26,
0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2,
0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0,
0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED,
0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F,
0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5,
0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC,
0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14,
0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C,
0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D,
0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F,
0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E,
0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11,
0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F,
0xB0, 0x54, 0xBB, 0x16
};
static int[] aes_y = {
0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E,
0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87,
0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32,
0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49,
0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16,
0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50,
0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05,
0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02,
0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41,
0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8,
0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89,
0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B,
0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59,
0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D,
0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D,
0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63,
0x55, 0x21, 0x0C, 0x7D
};
static long[] rcon = {
0x01000000L, 0x02000000L, 0x04000000L, 0x08000000L, 0x10000000L,
0x20000000L, 0x40000000L, 0xFFFFFFFF80000000L, 0x1B000000L, 0x36000000L
};
}
| UCT-White-Lab/provisioning-jig | fw_update/ST_decrypt.java | Java | mit | 22,664 |
import { createAction } from 'redux-actions';
import { APP_LAYOUT_CHANGE, APP_LAYOUT_INIT } from './constants';
// 选中菜单列表项
const appLayoutInit = createAction(APP_LAYOUT_INIT);
export const onAppLayoutInit = (key) => {
return (dispatch) => {
dispatch(appLayoutInit(key));
};
};
const appLayoutChange = createAction(APP_LAYOUT_CHANGE);
export const onAppLayoutChange = (key) => {
return (dispatch) => {
dispatch(appLayoutChange(key));
};
};
| dunwu/react-app | codes/src/view/general/setting/redux/actions.js | JavaScript | mit | 471 |
using TORSHIA.App.Models.Binding;
using TORSHIA.Domain;
namespace TORSHIA.Services.Contracts
{
public interface IUsersService
{
void CreateUser(RegisterUserBindingModel registerUserBindingModel);
User GetUserByUsername(string username);
}
}
| MihailDobrev/SoftUni | C# Web/C# Web Development Basics/Exam Preparation II - Mish Mash/Apps/TORSHIA.Services/Contracts/IUsersService.cs | C# | mit | 274 |
/**
* Copyright (c) 2013 Andre Ricardo Schaffer
*
* 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.
*/
package com.github.wiselenium.elements.component;
import java.util.List;
/**
* Represents a HTML Multiple Select.
*
* @author Andre Ricardo Schaffer
* @since 0.3.0
*/
public interface MultiSelect extends Component<MultiSelect> {
/**
* Deselects all options.
*
* @return This select instance to allow chain calls.
* @since 0.3.0
*/
MultiSelect deselectAll();
/**
* Deselects all options at the given indexes. This is done by examing the "index" attribute of
* an element, and not merely by counting.
*
* @param indexes The option at this index will be selected.
* @return This select element to allow chain calls.
* @since 0.3.0
*/
MultiSelect deselectByIndex(int... indexes);
/**
* Deselects all options that have a value matching the argument. That is, when given "foo" this
* would select an option like: <option value="foo">Bar</option>
*
* @param values The values to match against.
* @return This select element to allow chain calls.
* @since 0.3.0
*/
MultiSelect deselectByValue(String... values);
/**
* Deselects all options that display text matching the argument. That is, when given "Bar" this
* would select an option like: <option value="foo">Bar</option>
*
* @param texts The visible texts to match against.
* @return This select element to allow chain calls.
* @since 0.3.0
*/
MultiSelect deselectByVisibleText(String... texts);
/**
* Deselects some options of this select if not already deselected.
*
* @param options The options to be deselected.
* @return This select instance in order to allow chain calls.
* @since 0.3.0
*/
MultiSelect deselectOptions(Option... options);
/**
* Gets the options of this select.
*
* @return The options of this select.
* @since 0.3.0
*/
List<Option> getOptions();
/**
* Returns the selected options.
*
* @return The selected options.
* @since 0.3.0
*/
List<Option> getSelectedOptions();
/**
* Returns the selected values.
*
* @return The selected values.
* @since 0.3.0
*/
List<String> getSelectedValues();
/**
* Returns the selected visible texts.
*
* @return The selected visible texts.
* @since 0.3.0
*/
List<String> getSelectedVisibleTexts();
/**
* Selects all options.
*
* @return This select instance to allow chain calls.
* @since 0.3.0
*/
MultiSelect selectAll();
/**
* Selects all options at the given indexes. This is done by examing the "index" attribute of an
* element, and not merely by counting.
*
* @param indexes The option at this index will be selected.
* @return This select element to allow chain calls.
* @since 0.3.0
*/
MultiSelect selectByIndex(int... indexes);
/**
* Selects all options that have a value matching the argument. That is, when given "foo" this
* would select an option like: <option value="foo">Bar</option>
*
* @param values The values to match against.
* @return This select element to allow chain calls.
* @since 0.3.0
*/
MultiSelect selectByValue(String... values);
/**
* Selects all options that display text matching the argument. That is, when given "Bar" this
* would select an option like: <option value="foo">Bar</option>
*
* @param texts The visible texts to match against.
* @return This select element to allow chain calls.
* @since 0.3.0
*/
MultiSelect selectByVisibleText(String... texts);
/**
* Selects some options of this select if not already selected.
*
* @param options The options to be selected.
* @return This select instance in order to allow chain calls.
* @since 0.3.0
*/
MultiSelect selectOptions(Option... options);
}
| wiselenium/wiselenium | wiselenium-elements/src/main/java/com/github/wiselenium/elements/component/MultiSelect.java | Java | mit | 4,862 |
<?php
namespace Kendo\Dataviz\UI;
class DiagramShapeDefaultsConnectorDefaultsHoverStroke extends \Kendo\SerializableObject {
//>> Properties
/**
* Defines the hover stroke color.
* @param string $value
* @return \Kendo\Dataviz\UI\DiagramShapeDefaultsConnectorDefaultsHoverStroke
*/
public function color($value) {
return $this->setProperty('color', $value);
}
/**
* The dash type of the hover stroke.
* @param string $value
* @return \Kendo\Dataviz\UI\DiagramShapeDefaultsConnectorDefaultsHoverStroke
*/
public function dashType($value) {
return $this->setProperty('dashType', $value);
}
/**
* Defines the thickness or width of the shape connectors stroke on hover.
* @param float $value
* @return \Kendo\Dataviz\UI\DiagramShapeDefaultsConnectorDefaultsHoverStroke
*/
public function width($value) {
return $this->setProperty('width', $value);
}
//<< Properties
}
?>
| deviffy/laravel-kendo-ui | wrappers/php/lib/Kendo/Dataviz/UI/DiagramShapeDefaultsConnectorDefaultsHoverStroke.php | PHP | mit | 982 |
using Raccoon.Graphics;
namespace Raccoon.Fonts {
public class TextShaderParameters : IShaderParameters, IFontSizeShaderParameter {
#region Private Members
private float? _fontSize;
#endregion Private Members
#region Constructors
public TextShaderParameters(Font font) {
Font = font;
}
#endregion Constructors
#region Public Properties
public Font Font { get; set; }
public float FontSize {
get {
if (_fontSize.HasValue) {
return _fontSize.Value;
} else if (Font.ShaderParameters != null
&& Font.ShaderParameters is IFontSizeShaderParameter fontSizeShaderParameter
) {
return fontSizeShaderParameter.FontSize;
}
return 0.0f;
}
set {
if (value <= 0.0f) {
_fontSize = null;
return;
}
_fontSize = value;
}
}
public float FontScale { get; set; } = 1.0f;
/// <summary>
/// A special kind of scale which only applies to font resolution size itself.
///
/// Some methods, such as MTSDF, can use a dynamic font scaling and any kind of view scaling which works as a transformation matrix, which we can't retrieve it's numeric value (e.g zoom) to properly calculate font size, should be applied here. Using it don't mess anything related to position or vertices scale, only font resolution.
/// </summary>
public float FontResolutionScale { get; set; } = 1.0f;
#endregion Public Properties
#region Public Methods
public void ApplyParameters(Shader shader) {
if (shader == null) {
throw new System.ArgumentNullException(nameof(shader));
}
if (Font == null || Font.ShaderParameters == null) {
return;
}
if (Font.ShaderParameters is FontMTSDFShaderParameters fontMTSDFShaderParameters) {
if (!(shader is FontMTSDFShader fontMTSDFShader)) {
throw new System.ArgumentException($"Expected '{nameof(FontMTSDFShader)}', but got '{shader.GetType().Name}' instead. (Because font shader parameters is '{nameof(FontMTSDFShaderParameters)}')");
}
fontMTSDFShaderParameters.ApplyParameters(shader);
fontMTSDFShader.ScreenPixelRange =
fontMTSDFShaderParameters.CalculateScreenPixelRange(FontSize, FontScale);
} else if (Font.ShaderParameters != null) {
Font.ShaderParameters.ApplyParameters(shader);
}
}
public IShaderParameters Clone() {
return new TextShaderParameters(Font) {
_fontSize = _fontSize,
FontScale = FontScale
};
}
public bool IsSafeFontScale(float fontSize, float fontScale) {
if (Font == null || Font.ShaderParameters == null) {
throw new System.InvalidOperationException($"{nameof(Font.ShaderParameters)} isn't defined.");
}
if (!(Font.ShaderParameters is IFontSizeShaderParameter fontSizeShaderParameter)) {
throw new System.InvalidOperationException($"Current {nameof(Font.ShaderParameters)} doesn't implements {nameof(IFontSizeShaderParameter)}.");
}
return fontSizeShaderParameter.IsSafeFontScale(fontSize, fontScale);
}
public void SafeSetFontScale(float fontScale) {
if (Font == null || Font.ShaderParameters == null) {
throw new System.InvalidOperationException($"{nameof(Font.ShaderParameters)} isn't defined.");
}
if (!(Font.ShaderParameters is IFontSizeShaderParameter fontSizeShaderParameter)) {
throw new System.InvalidOperationException($"Current {nameof(Font.ShaderParameters)} doesn't implements {nameof(IFontSizeShaderParameter)}.");
}
if (fontSizeShaderParameter.IsSafeFontScale(FontSize, fontScale)) {
FontScale = fontScale;
}
}
public bool Equals(IShaderParameters other) {
return other != null
&& other is TextShaderParameters otherTextShaderParameters
&& otherTextShaderParameters.FontSize == FontSize
&& otherTextShaderParameters.FontScale == FontScale;
}
#endregion Public Methods
}
}
| lucas-miranda/Raccoon | Raccoon/Graphics/Fonts/Shaders/TextShaderParameters.cs | C# | mit | 4,637 |
namespace Cosmos.Logging.Core.LogFields {
public class TagsField : ILogField<string[]> {
public TagsField(params string[] tags) => Value = tags;
public LogFieldTypes Type => LogFieldTypes.Tags;
public string[] Value { get; }
public int Sort { get; set; } = 1;
}
} | CosmosProgramme/Cosmos.Core | Logging/src/Cosmos.Logging/Core/LogFields/LogFields.Tags.cs | C# | mit | 306 |
<?php if($this->session->userdata('nivel')==2) {?>
<body>
<?php if ($grupos!=FALSE){?>
<div class="container">
<h5>Ver Grupos</h5>
<form action="<?php echo base_url();?>index.php/Welcome/verGrupo" method="post">
<div class="input-field col s12">
<select id="grupo" name="grupo">
<?php echo form_error('grupo');?>
<option value="" disabled selected>Elige un Grupo</option>
<?php foreach($grupos->result() as $fila) { ?>
<option value="<?=$fila->idGrupo?>"><?=$fila ->nombre?></option><?php
}?>
</select>
</div>
<input type="submit" id="button" class="btn-flat" value="enviar" class="boton">
</form>
</div>
<?php }?>
<br>
<div class="container">
<h5>Dar de Alta un grupo</h5>
<form class="registro" action="<?php echo base_url();?>index.php/Welcome/ingresaGrupo" method="post">
<div class="campo">
<label for="nombre">Nombre del Grupo: </label>
<?php echo form_error('nombre');?>
<input type="text" id="nombre" name="nombre" placeholder="tu nombre">
</div>
<div class="campo">
<label for="numAlumnos">Número de Alumnos (capacidad): </label>
<?php echo form_error('numAlumnos');?>
<input type="number" id="numAlumnos" name="numAlumnos" placeholder="cantidad de alumnos">
</div>
<input type="submit" id="button" class="btn-flat" value="enviar" class="boton">
</form>
</div>
</body>
<?php }
else
redirect('/Welcome/index/', 'location');
?> | celli33/dictadosWeb | application/views/verGrupos.php | PHP | mit | 1,717 |
package lexek.wschat.db.dao;
import lexek.wschat.chat.e.EntityNotFoundException;
import lexek.wschat.chat.e.InvalidInputException;
import lexek.wschat.db.model.DataPage;
import lexek.wschat.db.model.UserData;
import lexek.wschat.db.model.UserDto;
import lexek.wschat.db.model.form.UserChangeSet;
import lexek.wschat.util.Pages;
import org.jooq.Condition;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.exception.DataAccessException;
import org.jooq.impl.DSL;
import org.jvnet.hk2.annotations.Service;
import javax.inject.Inject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static lexek.wschat.db.jooq.tables.User.USER;
import static lexek.wschat.db.jooq.tables.Userauth.USERAUTH;
@Service
public class UserDao {
private final DSLContext ctx;
@Inject
public UserDao(DSLContext ctx) {
this.ctx = ctx;
}
public boolean tryChangeName(long id, String newName, boolean ignoreCheck) {
try {
Condition condition = USER.ID.equal(id);
if (!ignoreCheck) {
condition.and(USER.RENAME_AVAILABLE.equal(true));
}
return ctx
.update(USER)
.set(USER.NAME, newName)
.set(USER.RENAME_AVAILABLE, false)
.where(condition)
.execute() == 1;
} catch (DataAccessException e) {
throw new InvalidInputException("name", "NAME_TAKEN");
}
}
public UserDto getByNameOrEmail(String name) {
Record record = ctx
.select()
.from(USER)
.where(
USER.EMAIL.isNotNull(),
USER.NAME.equal(name).or(USER.EMAIL.equal(name)),
USER.EMAIL_VERIFIED.isTrue()
)
.fetchOne();
return UserDto.fromRecord(record);
}
public UserDto getByName(String name) {
Record record = ctx
.select()
.from(USER)
.where(USER.NAME.equal(name))
.fetchOne();
return UserDto.fromRecord(record);
}
public UserDto getById(long id) {
Record record = ctx
.select()
.from(USER)
.where(USER.ID.equal(id))
.fetchOne();
return UserDto.fromRecord(record);
}
public UserDto update(long id, UserChangeSet changeSet) {
Map<org.jooq.Field<?>, Object> changeMap = new HashMap<>();
if (changeSet.getBanned() != null) {
changeMap.put(USER.BANNED, changeSet.getBanned());
}
if (changeSet.getRenameAvailable() != null) {
changeMap.put(USER.RENAME_AVAILABLE, changeSet.getRenameAvailable());
}
if (changeSet.getName() != null) {
changeMap.put(USER.NAME, changeSet.getName());
}
if (changeSet.getRole() != null) {
changeMap.put(USER.ROLE, changeSet.getRole().toString());
}
UserDto userDto = null;
boolean success = ctx
.update(USER)
.set(changeMap)
.where(USER.ID.equal(id))
.execute() == 1;
if (success) {
Record record = ctx
.selectFrom(USER)
.where(USER.ID.equal(id))
.fetchOne();
userDto = UserDto.fromRecord(record);
}
return userDto;
}
public void setColor(long id, String color) {
ctx
.update(USER)
.set(USER.COLOR, color)
.where(USER.ID.equal(id))
.execute();
}
public DataPage<UserData> getAllPaged(int page, int pageLength) {
List<UserData> data = ctx
.select(
USER.ID, USER.NAME, USER.ROLE, USER.COLOR, USER.BANNED, USER.RENAME_AVAILABLE,
USER.EMAIL, USER.EMAIL_VERIFIED, USER.CHECK_IP,
DSL.groupConcat(USERAUTH.SERVICE).as("authServices"),
DSL.groupConcat(DSL.coalesce(USERAUTH.AUTH_NAME, "")).as("authNames")
)
.from(USER.join(USERAUTH).on(USER.ID.equal(USERAUTH.USER_ID)))
.groupBy(USER.ID)
.orderBy(USER.ID)
.limit(page * pageLength, pageLength)
.fetch()
.stream()
.map(record -> new UserData(
UserDto.fromRecord(record),
collectAuthServices(
record.getValue("authServices", String.class),
record.getValue("authNames", String.class)
)
))
.collect(Collectors.toList());
return new DataPage<>(data, page, Pages.pageCount(pageLength, ctx.fetchCount(USER)));
}
public DataPage<UserData> searchPaged(Integer page, int pageLength, String nameParam) {
List<UserData> data = ctx
.select(USER.ID, USER.NAME, USER.ROLE, USER.COLOR, USER.BANNED, USER.CHECK_IP,
USER.RENAME_AVAILABLE, USER.EMAIL, USER.EMAIL_VERIFIED,
DSL.groupConcat(USERAUTH.SERVICE).as("authServices"),
DSL.groupConcat(DSL.coalesce(USERAUTH.AUTH_NAME, "")).as("authNames"))
.from(USER.join(USERAUTH).on(USER.ID.equal(USERAUTH.USER_ID)))
.where(USER.NAME.like(nameParam, '!'))
.groupBy(USER.ID)
.orderBy(USER.ID)
.limit(page * pageLength, pageLength)
.fetch()
.stream()
.map(record -> new UserData(
UserDto.fromRecord(record),
collectAuthServices(
record.getValue("authServices", String.class),
record.getValue("authNames", String.class)
)
))
.collect(Collectors.toList());
return new DataPage<>(data, page,
Pages.pageCount(pageLength, ctx.fetchCount(USER, USER.NAME.like(nameParam, '!'))));
}
public List<UserDto> searchSimple(int pageLength, String nameParam) {
return ctx
.selectFrom(USER)
.where(USER.NAME.like(nameParam, '!'))
.groupBy(USER.ID)
.orderBy(USER.ID)
.limit(pageLength)
.fetch()
.stream()
.map(UserDto::fromRecord)
.collect(Collectors.toList());
}
public boolean delete(UserDto user) {
return ctx
.delete(USER)
.where(USER.ID.equal(user.getId()))
.execute() == 1;
}
public boolean checkName(String username) {
return ctx
.selectOne()
.from(USER)
.where(USER.NAME.equal(username))
.fetchOne() == null;
}
public UserData fetchData(long id) {
UserData result = null;
Record record = ctx
.select(USER.ID, USER.NAME, USER.ROLE, USER.COLOR, USER.BANNED, USER.RENAME_AVAILABLE, USER.EMAIL,
USER.EMAIL_VERIFIED, USER.CHECK_IP,
DSL.groupConcat(USERAUTH.SERVICE).as("authServices"),
DSL.groupConcat(DSL.coalesce(USERAUTH.AUTH_NAME, "")).as("authNames"))
.from(USER.join(USERAUTH).on(USER.ID.equal(USERAUTH.USER_ID)))
.where(USER.ID.equal(id))
.groupBy(USER.ID)
.fetchOne();
if (record != null) {
result = new UserData(
UserDto.fromRecord(record),
collectAuthServices(
record.getValue("authServices", String.class),
record.getValue("authNames", String.class)
)
);
}
return result;
}
public List<UserDto> getAdmins() {
return ctx
.select()
.from(USER)
.where(USER.ROLE.in("ADMIN", "SUPERADMIN"))
.fetch()
.stream()
.map(UserDto::fromRecord)
.collect(Collectors.toList());
}
public void setCheckIp(UserDto user, boolean value) {
int rows = ctx
.update(USER)
.set(USER.CHECK_IP, value)
.where(USER.ID.equal(user.getId()))
.execute();
if (rows == 0) {
throw new EntityNotFoundException("user");
}
}
private Map<String, String> collectAuthServices(String servicesString, String namesString) {
String[] authServices = servicesString.split(",", -1);
String[] authNames = namesString.split(",", -1);
Map<String, String> result = new HashMap<>();
for (int i = 0; i < authServices.length; ++i) {
result.put(authServices[i], authNames[i]);
}
return result;
}
}
| lexek/chat | src/main/java/lexek/wschat/db/dao/UserDao.java | Java | mit | 8,668 |
<?php
class LayoutViewTest extends PHPUnit_Framework_TestCase {
public function setUp() {
$this->view = new \Slim\LayoutView();
$this->view->setTemplatesDirectory(__DIR__ . '/templates');
}
public function testRendersTemplateWrappedWithLayout() {
$output = $this->view->fetch('simple.php');
$this->assertEquals("<h1>Hello World\n</h1>", trim($output));
}
public function testDefaultLayoutFromAppConfiguration() {
\Slim\Environment::mock();
$this->app = new \Slim\Slim(array('layout' => 'layout_from_app.php'));
$output = $this->view->fetch('simple.php');
$this->assertEquals("<div>Hello World\n</div>", trim($output));
}
public function testLayoutFromData() {
$this->view->setData('layout', 'layout_from_data.php');
$output = $this->view->fetch('simple.php');
$this->assertEquals("<p>Hello World\n</p>", trim($output));
}
public function testRendersWithoutLayout() {
$this->view->setData('layout', false);
$output = $this->view->fetch('simple.php');
$this->assertEquals('Hello World', trim($output));
}
public function testLayoutSharesData() {
$output = $this->view->setData(array(
'title' => 'Hello',
'content' => 'World',
'layout' => 'layout_with_data.php'
));
$output = $this->view->fetch('template_with_data.php', array());
$this->assertEquals("<h1>Hello</h1>\n<p>World</p>", trim($output));
}
public function testAdditionalDataInFetch() {
$output = $this->view->fetch('template_with_data.php', array(
'title' => 'Hello',
'content' => 'World',
'layout' => 'layout_with_data.php'
));
$this->assertEquals("<h1>Hello</h1>\n<p>World</p>", trim($output));
}
}
| petebrowne/slim-layout-view | tests/LayoutViewTest.php | PHP | mit | 1,714 |
// Init express server
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var server = require('http').Server(app);
server.listen(3000);
console.log("started listenning on port 3000");
// Subscribe to lexa's router stream and update the LED accordingly
// var onoff = require('onoff');
// var Gpio = onoff.Gpio;
// var led = new Gpio(18, 'out');
var sio = require('socket.io-client');
var socket = sio.connect('http://lexa.tuscale.ro');
// socket.on('message', function(msg) {
// console.log('Got a new message from the router:', msg);
// var jMsg = JSON.parse(msg);
// var newLedState = jMsg.led;
// led.writeSync(newLedState);
// });
// Init firebase
var firebase = require('firebase');
var io = require('socket.io')(server);
var firebase_app = firebase.initializeApp({
apiKey: "AIzaSyB3ZvJDuZ2HD-UppgPvY2by-GI0KnessXw",
authDomain: "rlexa-9f1ca.firebaseapp.com",
databaseURL: "https://rlexa-9f1ca.firebaseio.com",
projectId: "rlexa-9f1ca",
storageBucket: "rlexa-9f1ca.appspot.com",
messagingSenderId: "161670508523"
});
var db = firebase.database();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Init NFC serial link
// var SerialPort = require('serialport');
// SerialPort.list(function (err, ports) {
// ports.forEach(function (port) {
// console.log(port.comName);
// });
// });
// var port = new SerialPort('/dev/ttyACM0', {
// baudRate: 9600,
// parser: SerialPort.parsers.readline("\r\n")
// });
// port.on('open', function () {
// console.log('open');
// });
// // Monitor NFC activity
// port.on('data', function (data) {
// var tagID = data.split(' ').join('');
// console.log(data.split(' '));
// tagID = tagID.substring(0, tagID.length - 1);
// console.log(tagID + " scanned ...");
// db.ref("card/" + tagID).once("value", function(cardOwnerSnap) {
// var cardOwnerName = cardOwnerSnap.child('name').val();
// if (cardOwnerName) {
// db.ref('authed').set(cardOwnerName);
// }
// });
// // Notify our web-clients that a tag was scanned
// io.sockets.emit('idscanned', { cardid: tagID });
// });
io.on('connection', function (socket) {
console.log('Web client connected.');
});
// Define web-facing endpoints for managing the users
app.post('/add_user', function (req, res) {
var currentUser = { name: req.body.name, led: req.body.led, id: req.body.id };
var updates = {};
updates['card/' + currentUser.id] = {
name: currentUser.name,
led: currentUser.led
};
updates['users/' + currentUser.name] = currentUser;
return firebase.database().ref().update(updates);
});
app.get('/get_users', function (req, res) {
firebase.database().ref().once('value', function (snap) {
var dataUsers = snap.child("users");
res.send(dataUsers);
});
});
app.get('/get_authed', function (req, res) {
db.ref().once('value', function (snap) {
var isUserLogged = snap.child("authed/Mike").val();
console.log(isUserLogged);
if (isUserLogged) {
var userData = snap.child("users/Mike/led")
console.log(parseInt(userData.val()));
}
})
var name = "BLAH";
name = name.toLowerCase();
name = name.charAt(0).toUpperCase() + name.slice(1);
res.send(name);
});
// Monitor process termination and do cleanups
// process.on('SIGINT', function () {
// led.writeSync(0);
// led.unexport();
// process.exit();
// });
// db.ref('authed').once('value', function (snap) {
// var lastScannedTagOwner = snap.val();
// if (lastScannedTagOwner) {
// // Valid tag present
// request({
// url: 'http://lexa.tuscale.ro/publish',
// method: 'POST',
// json: { led: (stateName === "on" ? 1 : 0) }
// },
// function (error, response, body) {
// if (error) {
// return console.error('upload failed:', error);
// }
// // Delete scanned tag and notify user of successfull op
// db.ref('authed').remove();
// that.emit(':tell', 'Hi ' + lastScannedTagOwner + '! Turning ' + stateName + ' the LED!');
// console.log('Upload successful! Server responded with:', body)
// }
// );
// } else {
// that.emit(':tell', 'Please scan your tag and try again.');
// }
// }); | JaxonDvl/lexa-piduino | serverlocal.js | JavaScript | mit | 4,714 |
import { AsyncIterableX } from '../../asynciterable/asynciterablex';
import { SkipAsyncIterable } from '../../asynciterable/operators/skip';
/**
* @ignore
*/
export function skipProto<T>(this: AsyncIterableX<T>, count: number): AsyncIterableX<T> {
return new SkipAsyncIterable<T>(this, count);
}
AsyncIterableX.prototype.skip = skipProto;
declare module '../../asynciterable/asynciterablex' {
interface AsyncIterableX<T> {
skip: typeof skipProto;
}
}
| ReactiveX/IxJS | src/add/asynciterable-operators/skip.ts | TypeScript | mit | 466 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="tr" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="14"/>
<source>About FlorijnCoin</source>
<translation>FlorijnCoin hakkında</translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="53"/>
<source><b>FlorijnCoin</b> version</source>
<translation><b>FlorijnCoin</b> sürüm</translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="97"/>
<source>Copyright © 2009-2012 FlorijnCoin Developers
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file license.txt or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>Telif hakkı © 2009-2012 FlorijnCoin geliştiricileri
Bu yazılım deneme safhasındadır.
MIT/X11 yazılım lisansı kapsamında yayınlanmıştır, license.txt dosyasına ya da http://www.opensource.org/licenses/mit-license.php sayfasına bakınız.
Bu ürün OpenSSL projesi tarafından OpenSSL araç takımı (http://www.openssl.org/) için geliştirilen yazılımlar, Eric Young (eay@cryptsoft.com) tarafından yazılmış şifreleme yazılımları ve Thomas Bernard tarafından programlanmış UPnP yazılımı içerir.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="14"/>
<source>Address Book</source>
<translation>Adres defteri</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="20"/>
<source>These are your FlorijnCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Bunlar, ödemeleri almak için FlorijnCoin adresleridir. Kimin ödeme yaptığını izleyebilmek için her ödeme yollaması gereken kişiye değişik bir adres verebilirsiniz.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="36"/>
<source>Double-click to edit address or label</source>
<translation>Adresi ya da etiketi düzenlemek için çift tıklayınız</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="63"/>
<source>Create a new address</source>
<translation>Yeni bir adres oluştur</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="77"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Şu anda seçili olan adresi panoya kopyalar</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="66"/>
<source>&New Address</source>
<translation>&Yeni adres</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="80"/>
<source>&Copy Address</source>
<translation>Adresi &kopyala</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="91"/>
<source>Show &QR Code</source>
<translation>&QR kodunu göster</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="102"/>
<source>Sign a message to prove you own this address</source>
<translation>Bu adresin sizin olduğunu ispatlamak için mesaj imzalayın</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="105"/>
<source>&Sign Message</source>
<translation>Mesaj &imzala</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="116"/>
<source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source>
<translation>Seçilen adresi listeden siler. Sadece gönderi adresleri silinebilir.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="119"/>
<source>&Delete</source>
<translation>&Sil</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="63"/>
<source>Copy &Label</source>
<translation>&Etiketi kopyala</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="65"/>
<source>&Edit</source>
<translation>&Düzenle</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="292"/>
<source>Export Address Book Data</source>
<translation>Adres defteri verilerini dışa aktar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="293"/>
<source>Comma separated file (*.csv)</source>
<translation>Virgülle ayrılmış değerler dosyası (*.csv)</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="306"/>
<source>Error exporting</source>
<translation>Dışa aktarımda hata oluştu</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="306"/>
<source>Could not write to file %1.</source>
<translation>%1 dosyasına yazılamadı.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="142"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="142"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="178"/>
<source>(no label)</source>
<translation>(boş etiket)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="26"/>
<source>Passphrase Dialog</source>
<translation>Parola diyaloğu</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="47"/>
<source>Enter passphrase</source>
<translation>Parolayı giriniz</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="61"/>
<source>New passphrase</source>
<translation>Yeni parola</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="75"/>
<source>Repeat new passphrase</source>
<translation>Yeni parolayı tekrarlayınız</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Cüzdanınız için yeni parolayı giriniz.<br/>Lütfen <b>10 ya da daha fazla rastgele karakter</b> veya <b>sekiz ya da daha fazla kelime</b> içeren bir parola seçiniz.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="34"/>
<source>Encrypt wallet</source>
<translation>Cüzdanı şifrele</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="37"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Bu işlem cüzdan kilidini açmak için cüzdan parolanızı gerektirir.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="42"/>
<source>Unlock wallet</source>
<translation>Cüzdan kilidini aç</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="45"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Bu işlem, cüzdan şifresini açmak için cüzdan parolasını gerektirir.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="50"/>
<source>Decrypt wallet</source>
<translation>Cüzdan şifresini aç</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="53"/>
<source>Change passphrase</source>
<translation>Parolayı değiştir</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="54"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Cüzdan için eski ve yeni parolaları giriniz.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="100"/>
<source>Confirm wallet encryption</source>
<translation>Cüzdan şifrelenmesini teyit eder</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="101"/>
<source>WARNING: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!
Are you sure you wish to encrypt your wallet?</source>
<translation>UYARI: Eğer cüzdanınızı şifrelerseniz ve parolanızı kaybederseniz, <b>TÜM BİTCOİNLERİNİZİ KAYBEDERSİNİZ</b>!
Cüzdanınızı şifrelemek istediğinizden emin misiniz?</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="110"/>
<location filename="../askpassphrasedialog.cpp" line="159"/>
<source>Wallet encrypted</source>
<translation>Cüzdan şifrelendi</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="111"/>
<source>FlorijnCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source>
<translation>Şifreleme işlemini tamamlamak için FlorijnCoin şimdi kapanacaktır. Cüzdanınızı şifrelemenin, FlorijnCoinlerinizin bilgisayara bulaşan kötücül bir yazılım tarafından çalınmaya karşı tamamen koruyamayacağını unutmayınız.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="207"/>
<location filename="../askpassphrasedialog.cpp" line="231"/>
<source>Warning: The Caps Lock key is on.</source>
<translation>Uyarı: Caps Lock tuşu etkin durumda.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="116"/>
<location filename="../askpassphrasedialog.cpp" line="123"/>
<location filename="../askpassphrasedialog.cpp" line="165"/>
<location filename="../askpassphrasedialog.cpp" line="171"/>
<source>Wallet encryption failed</source>
<translation>Cüzdan şifrelemesi başarısız oldu</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="117"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Dahili bir hata sebebiyle cüzdan şifrelemesi başarısız oldu. Cüzdanınız şifrelenmedi.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="124"/>
<location filename="../askpassphrasedialog.cpp" line="172"/>
<source>The supplied passphrases do not match.</source>
<translation>Girilen parolalar birbirleriyle uyumlu değil.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="135"/>
<source>Wallet unlock failed</source>
<translation>Cüzdan kilidinin açılması başarısız oldu</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="136"/>
<location filename="../askpassphrasedialog.cpp" line="147"/>
<location filename="../askpassphrasedialog.cpp" line="166"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Cüzdan şifresinin açılması için girilen parola yanlıştı.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="146"/>
<source>Wallet decryption failed</source>
<translation>Cüzdan şifresinin açılması başarısız oldu</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="160"/>
<source>Wallet passphrase was succesfully changed.</source>
<translation>Cüzdan parolası başarılı bir şekilde değiştirildi.</translation>
</message>
</context>
<context>
<name>FlorijnCoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="73"/>
<source>FlorijnCoin Wallet</source>
<translation>FlorijnCoin cüzdanı</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="215"/>
<source>Sign &message...</source>
<translation>&Mesaj imzala...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="248"/>
<source>Show/Hide &FlorijnCoin</source>
<translation>&FlorijnCoin'i Göster/Sakla</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="515"/>
<source>Synchronizing with network...</source>
<translation>Şebeke ile senkronizasyon...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="185"/>
<source>&Overview</source>
<translation>&Genel bakış</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="186"/>
<source>Show general overview of wallet</source>
<translation>Cüzdana genel bakışı gösterir</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="191"/>
<source>&Transactions</source>
<translation>&Muameleler</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="192"/>
<source>Browse transaction history</source>
<translation>Muamele tarihçesini tara</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="197"/>
<source>&Address Book</source>
<translation>&Adres defteri</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="198"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Saklanan adres ve etiket listesini düzenler</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="203"/>
<source>&Receive coins</source>
<translation>FlorijnCoin &al</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="204"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Ödeme alma adreslerinin listesini gösterir</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="209"/>
<source>&Send coins</source>
<translation>FlorijnCoin &yolla</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="216"/>
<source>Prove you control an address</source>
<translation>Bu adresin kontrolünüz altında olduğunu ispatlayın</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="235"/>
<source>E&xit</source>
<translation>&Çık</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="236"/>
<source>Quit application</source>
<translation>Uygulamadan çıkar</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="239"/>
<source>&About %1</source>
<translation>%1 &hakkında</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="240"/>
<source>Show information about FlorijnCoin</source>
<translation>FlorijnCoin hakkında bilgi gösterir</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="242"/>
<source>About &Qt</source>
<translation>&Qt hakkında</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="243"/>
<source>Show information about Qt</source>
<translation>Qt hakkında bilgi görüntüler</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="245"/>
<source>&Options...</source>
<translation>&Seçenekler...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="252"/>
<source>&Encrypt Wallet...</source>
<translation>Cüzdanı &şifrele...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="255"/>
<source>&Backup Wallet...</source>
<translation>Cüzdanı &yedekle...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="257"/>
<source>&Change Passphrase...</source>
<translation>Parolayı &değiştir...</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="517"/>
<source>~%n block(s) remaining</source>
<translation><numerusform>~%n blok kaldı</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="528"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation>Muamele tarihçesinden %1 blok indirildi (toplam %2 blok, %%3 tamamlandı).</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="250"/>
<source>&Export...</source>
<translation>&Dışa aktar...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="210"/>
<source>Send coins to a FlorijnCoin address</source>
<translation>Bir FlorijnCoin adresine FlorijnCoin yollar</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="246"/>
<source>Modify configuration options for FlorijnCoin</source>
<translation>FlorijnCoin seçeneklerinin yapılandırmasını değiştirir</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="249"/>
<source>Show or hide the FlorijnCoin window</source>
<translation>FlorijnCoin penceresini göster ya da sakla</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="251"/>
<source>Export the data in the current tab to a file</source>
<translation>Güncel sekmedeki verileri bir dosyaya aktar</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="253"/>
<source>Encrypt or decrypt wallet</source>
<translation>Cüzdanı şifreler ya da şifreyi açar</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="256"/>
<source>Backup wallet to another location</source>
<translation>Cüzdanı diğer bir konumda yedekle</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="258"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Cüzdan şifrelemesi için kullanılan parolayı değiştirir</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="259"/>
<source>&Debug window</source>
<translation>&Hata ayıklama penceresi</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="260"/>
<source>Open debugging and diagnostic console</source>
<translation>Hata ayıklama ve teşhis penceresini aç</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="261"/>
<source>&Verify message...</source>
<translation>&Mesaj kontrol et...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="262"/>
<source>Verify a message signature</source>
<translation>Mesaj imzasını kontrol et</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="286"/>
<source>&File</source>
<translation>&Dosya</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="296"/>
<source>&Settings</source>
<translation>&Ayarlar</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="302"/>
<source>&Help</source>
<translation>&Yardım</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="311"/>
<source>Tabs toolbar</source>
<translation>Sekme araç çubuğu</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="322"/>
<source>Actions toolbar</source>
<translation>Faaliyet araç çubuğu</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="334"/>
<location filename="../bitcoingui.cpp" line="343"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="343"/>
<location filename="../bitcoingui.cpp" line="399"/>
<source>FlorijnCoin client</source>
<translation>FlorijnCoin istemcisi</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="492"/>
<source>%n active connection(s) to FlorijnCoin network</source>
<translation><numerusform>FlorijnCoin şebekesine %n etkin bağlantı</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="540"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>Muamele tarihçesinin %1 adet bloku indirildi.</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="555"/>
<source>%n second(s) ago</source>
<translation><numerusform>%n saniye önce</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="559"/>
<source>%n minute(s) ago</source>
<translation><numerusform>%n dakika önce</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="563"/>
<source>%n hour(s) ago</source>
<translation><numerusform>%n saat önce</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="567"/>
<source>%n day(s) ago</source>
<translation><numerusform>%n gün önce</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="573"/>
<source>Up to date</source>
<translation>Güncel</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="580"/>
<source>Catching up...</source>
<translation>Aralık kapatılıyor...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="590"/>
<source>Last received block was generated %1.</source>
<translation>Son alınan blok şu vakit oluşturulmuştu: %1.</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="649"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Bu muamele boyut sınırlarını aşmıştır. Gene de %1 ücret ödeyerek gönderebilirsiniz, ki bu ücret muamelenizi işleyen ve şebekeye yardım eden düğümlere ödenecektir. Ücreti ödemek istiyor musunuz?</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="654"/>
<source>Confirm transaction fee</source>
<translation>Muamele ücretini teyit et</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="681"/>
<source>Sent transaction</source>
<translation>Muamele yollandı</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="682"/>
<source>Incoming transaction</source>
<translation>Gelen muamele</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="683"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Tarih: %1
Miktar: %2
Tür: %3
Adres: %4
</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="804"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Cüzdan <b>şifrelenmiştir</b> ve şu anda <b>kilidi açılmıştır</b></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="812"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Cüzdan <b>şifrelenmiştir</b> ve şu anda <b>kilitlidir</b></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="835"/>
<source>Backup Wallet</source>
<translation>Cüzdanı yedekle</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="835"/>
<source>Wallet Data (*.dat)</source>
<translation>Cüzdan verileri (*.dat)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="838"/>
<source>Backup Failed</source>
<translation>Yedekleme başarısız oldu</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="838"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Cüzdan verilerinin başka bir konumda kaydedilmesi sırasında bir hata meydana geldi.</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="112"/>
<source>A fatal error occured. FlorijnCoin can no longer continue safely and will quit.</source>
<translation>Ciddi bir hata oluştu. Artık FlorijnCoin güvenli bir şekilde işlemeye devam edemez ve kapanacaktır.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="84"/>
<source>Network Alert</source>
<translation>Şebeke hakkında uyarı</translation>
</message>
</context>
<context>
<name>DisplayOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="246"/>
<source>Display</source>
<translation>Görünüm</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="257"/>
<source>default</source>
<translation>varsayılan</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="263"/>
<source>The user interface language can be set here. This setting will only take effect after restarting FlorijnCoin.</source>
<translation>Kullanıcı arayüzünün dili burada belirtilebilir. Bu ayar FlorijnCoin tekrar başlatıldığında etkinleşecektir.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="252"/>
<source>User Interface &Language:</source>
<translation>Kullanıcı arayüzü &lisanı:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="273"/>
<source>&Unit to show amounts in:</source>
<translation>Miktarı göstermek için &birim: </translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="277"/>
<source>Choose the default subdivision unit to show in the interface, and when sending coins</source>
<translation>FlorijnCoin gönderildiğinde arayüzde gösterilecek varsayılan alt birimi seçiniz</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="284"/>
<source>&Display addresses in transaction list</source>
<translation>Muamele listesinde adresleri &göster</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="285"/>
<source>Whether to show FlorijnCoin addresses in the transaction list</source>
<translation>Muamele listesinde FlorijnCoin adreslerinin gösterilip gösterilmeyeceklerini belirler</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="303"/>
<source>Warning</source>
<translation>Uyarı</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="303"/>
<source>This setting will take effect after restarting FlorijnCoin.</source>
<translation>Bu ayarlar FlorijnCoin tekrar başlatıldığında etkinleşecektir.</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="14"/>
<source>Edit Address</source>
<translation>Adresi düzenle</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="25"/>
<source>&Label</source>
<translation>&Etiket</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="35"/>
<source>The label associated with this address book entry</source>
<translation>Bu adres defteri unsuru ile ilişkili etiket</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="42"/>
<source>&Address</source>
<translation>&Adres</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="52"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Bu adres defteri unsuru ile ilişkili adres. Bu, sadece gönderi adresi için değiştirilebilir.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="20"/>
<source>New receiving address</source>
<translation>Yeni alım adresi</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="24"/>
<source>New sending address</source>
<translation>Yeni gönderi adresi</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="27"/>
<source>Edit receiving address</source>
<translation>Alım adresini düzenle</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="31"/>
<source>Edit sending address</source>
<translation>Gönderi adresini düzenle</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="91"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Girilen "%1" adresi hâlihazırda adres defterinde mevcuttur.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="96"/>
<source>The entered address "%1" is not a valid FlorijnCoin address.</source>
<translation>Girilen "%1" adresi geçerli bir FlorijnCoin adresi değildir.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="101"/>
<source>Could not unlock wallet.</source>
<translation>Cüzdan kilidi açılamadı.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="106"/>
<source>New key generation failed.</source>
<translation>Yeni anahtar oluşturulması başarısız oldu.</translation>
</message>
</context>
<context>
<name>HelpMessageBox</name>
<message>
<location filename="../bitcoin.cpp" line="133"/>
<location filename="../bitcoin.cpp" line="143"/>
<source>FlorijnCoin-Qt</source>
<translation>FlorijnCoin-Qt</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="133"/>
<source>version</source>
<translation>sürüm</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="135"/>
<source>Usage:</source>
<translation>Kullanım:</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="136"/>
<source>options</source>
<translation>seçenekler</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="138"/>
<source>UI options</source>
<translation>Kullanıcı arayüzü seçenekleri</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="139"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Lisan belirt, mesela "de_De" (varsayılan: sistem dili)</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="140"/>
<source>Start minimized</source>
<translation>Küçültülmüş olarak başla</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="141"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Başlatıldığında başlangıç ekranını göster (varsayılan: 1)</translation>
</message>
</context>
<context>
<name>MainOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="227"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation>Çıkışta blok ve adres veri tabanlarını ayırır. Bu, kapanışı yavaşlatır ancak veri tabanlarının başka klasörlere taşınabilmelerine imkân sağlar. Cüzdan daima ayırılır.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="212"/>
<source>Pay transaction &fee</source>
<translation>Muamele ücreti &öde</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="204"/>
<source>Main</source>
<translation>Ana menü</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="206"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation>Muamelelerin hızlı işlenmesini garantilemeye yardım eden, seçime dayalı kB başı muamele ücreti. Muamelelerin çoğunluğunun boyutu 1 kB'dir. 0.01 ücreti önerilir. </translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="222"/>
<source>&Start FlorijnCoin on system login</source>
<translation>FlorijnCoin'i sistem oturumuyla &başlat</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="223"/>
<source>Automatically start FlorijnCoin after logging in to the system</source>
<translation>Sistemde oturum açıldığında FlorijnCoin'i otomatik olarak başlat</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="226"/>
<source>&Detach databases at shutdown</source>
<translation>Kapanışta veritabanlarını &ayır</translation>
</message>
</context>
<context>
<name>MessagePage</name>
<message>
<location filename="../forms/messagepage.ui" line="14"/>
<source>Sign Message</source>
<translation>Mesaj imzala</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="20"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Bir adresin sizin olduğunu ispatlamak için adresinizle mesaj imzalayabilirsiniz. Oltalama saldırılarının kimliğinizi imzanızla elde etmeyi deneyebilecekleri için belirsiz hiçbir şey imzalamamaya dikkat ediniz. Sadece ayrıntılı açıklaması olan ve tümüne katıldığınız ifadeleri imzalayın.</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="38"/>
<source>The address to sign the message with (e.g. FY36Zmi14ZU4XyfYmMdoV9i8cN1po3qyr9)</source>
<translation>Mesajı imzalamak için kullanılacak adres (mesela FY36Zmi14ZU4XyfYmMdoV9i8cN1po3qyr9)</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="48"/>
<source>Choose adress from address book</source>
<translation>Adres defterinden adres seç</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="58"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="71"/>
<source>Paste address from clipboard</source>
<translation>Panodan adres yapıştır</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="81"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="93"/>
<source>Enter the message you want to sign here</source>
<translation>İmzalamak istediğiniz mesajı burada giriniz</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="128"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Güncel imzayı sistem panosuna kopyala</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="131"/>
<source>&Copy Signature</source>
<translation>İmzayı &kopyala</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="142"/>
<source>Reset all sign message fields</source>
<translation>Tüm mesaj alanlarını sıfırla</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="145"/>
<source>Clear &All</source>
<translation>Tümünü &temizle</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="31"/>
<source>Click "Sign Message" to get signature</source>
<translation>İmza elde etmek için "Mesaj İmzala" unsurunu tıklayın</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="114"/>
<source>Sign a message to prove you own this address</source>
<translation>Bu adresin sizin olduğunu ispatlamak için bir mesaj imzalayın</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="117"/>
<source>&Sign Message</source>
<translation>Mesaj &İmzala</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="30"/>
<source>Enter a FlorijnCoin address (e.g. FY36Zmi14ZU4XyfYmMdoV9i8cN1po3qyr9)</source>
<translation>FlorijnCoin adresi giriniz (mesela FY36Zmi14ZU4XyfYmMdoV9i8cN1po3qyr9)</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="83"/>
<location filename="../messagepage.cpp" line="90"/>
<location filename="../messagepage.cpp" line="105"/>
<location filename="../messagepage.cpp" line="117"/>
<source>Error signing</source>
<translation>İmza sırasında hata meydana geldi</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="83"/>
<source>%1 is not a valid address.</source>
<translation>%1 geçerli bir adres değildir.</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="90"/>
<source>%1 does not refer to a key.</source>
<translation>%1 herhangi bir anahtara işaret etmemektedir.</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="105"/>
<source>Private key for %1 is not available.</source>
<translation>%1 için özel anahtar mevcut değil.</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="117"/>
<source>Sign failed</source>
<translation>İmzalama başarısız oldu</translation>
</message>
</context>
<context>
<name>NetworkOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="345"/>
<source>Network</source>
<translation>Şebeke</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="347"/>
<source>Map port using &UPnP</source>
<translation>Portları &UPnP kullanarak haritala</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="348"/>
<source>Automatically open the FlorijnCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Yönlendiricide FlorijnCoin istemci portlarını otomatik olarak açar. Bu, sadece yönlendiricinizin UPnP desteği bulunuyorsa ve etkinse çalışabilir.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="351"/>
<source>&Connect through SOCKS4 proxy:</source>
<translation>SOCKS4 vekil sunucusu vasıtasıyla ba&ğlan:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="352"/>
<source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source>
<translation>FlorijnCoin şebekesine SOCKS4 vekil sunucusu vasıtasıyla bağlanır (mesela Tor ile bağlanıldığında)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="357"/>
<source>Proxy &IP:</source>
<translation>Vekil &İP:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="366"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="363"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Vekil sunucunun İP adresi (mesela 127.0.0.1)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="372"/>
<source>Port of the proxy (e.g. 1234)</source>
<translation>Vekil sunucun portu (örneğin 1234)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../optionsdialog.cpp" line="135"/>
<source>Options</source>
<translation>Seçenekler</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="47"/>
<location filename="../forms/overviewpage.ui" line="204"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the FlorijnCoin network after a connection is established, but this process has not completed yet.</source>
<translation>Görüntülenen veriler zaman aşımını uğramış olabilir. Bağlantı kurulduğunda cüzdanınız otomatik olarak şebeke ile eşleşir ancak bu işlem henüz tamamlanmamıştır.</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="89"/>
<source>Balance:</source>
<translation>Bakiye:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="147"/>
<source>Number of transactions:</source>
<translation>Muamele sayısı:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="118"/>
<source>Unconfirmed:</source>
<translation>Doğrulanmamış:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="40"/>
<source>Wallet</source>
<translation>Cüzdan</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="197"/>
<source><b>Recent transactions</b></source>
<translation><b>Son muameleler</b></translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="105"/>
<source>Your current balance</source>
<translation>Güncel bakiyeniz</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="134"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Doğrulanması beklenen ve henüz güncel bakiyeye ilâve edilmemiş muamelelerin toplamı</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="154"/>
<source>Total number of transactions in wallet</source>
<translation>Cüzdandaki muamelelerin toplam sayısı</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="110"/>
<location filename="../overviewpage.cpp" line="111"/>
<source>out of sync</source>
<translation>eşleşme dışı</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="14"/>
<source>QR Code Dialog</source>
<translation>QR kodu diyaloğu</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="32"/>
<source>QR Code</source>
<translation>QR Kodu</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="55"/>
<source>Request Payment</source>
<translation>Ödeme isteği</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="70"/>
<source>Amount:</source>
<translation>Miktar:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="105"/>
<source>BTC</source>
<translation>BTC</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="121"/>
<source>Label:</source>
<translation>Etiket:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="144"/>
<source>Message:</source>
<translation>Mesaj:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="186"/>
<source>&Save As...</source>
<translation>&Farklı kaydet...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="45"/>
<source>Error encoding URI into QR Code.</source>
<translation>URI'nin QR koduna kodlanmasında hata oluştu.</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="63"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Sonuç URI çok uzun, etiket ya da mesaj metnini kısaltmayı deneyiniz.</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="120"/>
<source>Save QR Code</source>
<translation>QR kodu kaydet</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="120"/>
<source>PNG Images (*.png)</source>
<translation>PNG resimleri (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="14"/>
<source>FlorijnCoin debug window</source>
<translation>FlorijnCoin hata ayıklama penceresi</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="46"/>
<source>Client name</source>
<translation>İstemci ismi</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="56"/>
<location filename="../forms/rpcconsole.ui" line="79"/>
<location filename="../forms/rpcconsole.ui" line="102"/>
<location filename="../forms/rpcconsole.ui" line="125"/>
<location filename="../forms/rpcconsole.ui" line="161"/>
<location filename="../forms/rpcconsole.ui" line="214"/>
<location filename="../forms/rpcconsole.ui" line="237"/>
<location filename="../forms/rpcconsole.ui" line="260"/>
<location filename="../rpcconsole.cpp" line="245"/>
<source>N/A</source>
<translation>Mevcut değil</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="69"/>
<source>Client version</source>
<translation>İstemci sürümü</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="24"/>
<source>&Information</source>
<translation>&Malumat</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="39"/>
<source>Client</source>
<translation>İstemci</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="115"/>
<source>Startup time</source>
<translation>Başlama zamanı</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="144"/>
<source>Network</source>
<translation>Şebeke</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="151"/>
<source>Number of connections</source>
<translation>Bağlantı sayısı</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="174"/>
<source>On testnet</source>
<translation>Testnet üzerinde</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="197"/>
<source>Block chain</source>
<translation>Blok zinciri</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="204"/>
<source>Current number of blocks</source>
<translation>Güncel blok sayısı</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="227"/>
<source>Estimated total blocks</source>
<translation>Tahmini toplam blok sayısı</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="250"/>
<source>Last block time</source>
<translation>Son blok zamanı</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="292"/>
<source>Debug logfile</source>
<translation>Hata ayıklama kütük dosyası</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="299"/>
<source>Open the FlorijnCoin debug logfile from the current data directory. This can take a few seconds for large logfiles.</source>
<translation>Güncel veri klasöründen FlorijnCoin hata ayıklama kütüğünü aç. Büyük kütük dosyaları için bu birkaç saniye alabilir.</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="302"/>
<source>&Open</source>
<translation>&Aç</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="323"/>
<source>&Console</source>
<translation>&Konsol</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="92"/>
<source>Build date</source>
<translation>Derleme tarihi</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="372"/>
<source>Clear console</source>
<translation>Konsolu temizle</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="212"/>
<source>Welcome to the FlorijnCoin RPC console.</source>
<translation>FlorijnCoin RPC konsoluna hoş geldiniz.</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="213"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Tarihçede gezinmek için imleç tuşlarını kullanınız, <b>Ctrl-L</b> ile de ekranı temizleyebilirsiniz.</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="214"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Mevcut komutların listesi için <b>help</b> yazınız.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="14"/>
<location filename="../sendcoinsdialog.cpp" line="122"/>
<location filename="../sendcoinsdialog.cpp" line="127"/>
<location filename="../sendcoinsdialog.cpp" line="132"/>
<location filename="../sendcoinsdialog.cpp" line="137"/>
<location filename="../sendcoinsdialog.cpp" line="143"/>
<location filename="../sendcoinsdialog.cpp" line="148"/>
<location filename="../sendcoinsdialog.cpp" line="153"/>
<source>Send Coins</source>
<translation>FlorijnCoin yolla</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="64"/>
<source>Send to multiple recipients at once</source>
<translation>Birçok alıcıya aynı anda gönder</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="67"/>
<source>&Add Recipient</source>
<translation>Alıcı &ekle</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="84"/>
<source>Remove all transaction fields</source>
<translation>Bütün muamele alanlarını kaldır</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="87"/>
<source>Clear &All</source>
<translation>Tümünü &temizle</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="106"/>
<source>Balance:</source>
<translation>Bakiye:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="113"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="144"/>
<source>Confirm the send action</source>
<translation>Yollama etkinliğini teyit ediniz</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="147"/>
<source>&Send</source>
<translation>&Gönder</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="94"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> şu adrese: %2 (%3)</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="99"/>
<source>Confirm send coins</source>
<translation>Gönderiyi teyit ediniz</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="100"/>
<source>Are you sure you want to send %1?</source>
<translation>%1 göndermek istediğinizden emin misiniz?</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="100"/>
<source> and </source>
<translation> ve </translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="123"/>
<source>The recepient address is not valid, please recheck.</source>
<translation>Alıcı adresi geçerli değildir, lütfen denetleyiniz.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="128"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Ödeyeceğiniz tutarın sıfırdan yüksek olması gerekir.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="133"/>
<source>The amount exceeds your balance.</source>
<translation>Tutar bakiyenizden yüksektir.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="138"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Toplam, %1 muamele ücreti ilâve edildiğinde bakiyenizi geçmektedir.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="144"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Çift adres bulundu, belli bir gönderi sırasında her adrese sadece tek bir gönderide bulunulabilir.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="149"/>
<source>Error: Transaction creation failed.</source>
<translation>Hata: Muamele oluşturması başarısız oldu.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="154"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Hata: Muamele reddedildi. Cüzdanınızdaki madenî paraların bazıları zaten harcanmış olduğunda bu meydana gelebilir. Örneğin wallet.dat dosyasının bir kopyasını kullandıysanız ve kopyada para harcandığında ancak burada harcandığı işaretlenmediğinde.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="29"/>
<source>A&mount:</source>
<translation>M&iktar:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="42"/>
<source>Pay &To:</source>
<translation>&Şu kişiye öde:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="66"/>
<location filename="../sendcoinsentry.cpp" line="25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Adres defterinize eklemek için bu adrese ilişik bir etiket giriniz</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="75"/>
<source>&Label:</source>
<translation>&Etiket:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="93"/>
<source>The address to send the payment to (e.g. FY36Zmi14ZU4XyfYmMdoV9i8cN1po3qyr9)</source>
<translation>Ödemenin gönderileceği adres (mesela FY36Zmi14ZU4XyfYmMdoV9i8cN1po3qyr9)</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="103"/>
<source>Choose address from address book</source>
<translation>Adres defterinden adres seç</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="113"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="120"/>
<source>Paste address from clipboard</source>
<translation>Panodan adres yapıştır</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="130"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="137"/>
<source>Remove this recipient</source>
<translation>Bu alıcıyı kaldır</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="26"/>
<source>Enter a FlorijnCoin address (e.g. FY36Zmi14ZU4XyfYmMdoV9i8cN1po3qyr9)</source>
<translation>FlorijnCoin adresi giriniz (mesela FY36Zmi14ZU4XyfYmMdoV9i8cN1po3qyr9)</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="21"/>
<source>Open for %1 blocks</source>
<translation>%1 blok için açık</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="23"/>
<source>Open until %1</source>
<translation>%1 değerine dek açık</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="29"/>
<source>%1/offline?</source>
<translation>%1/çevrimdışı mı?</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="31"/>
<source>%1/unconfirmed</source>
<translation>%1/doğrulanmadı</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="33"/>
<source>%1 confirmations</source>
<translation>%1 teyit</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="51"/>
<source><b>Status:</b> </source>
<translation><b>Durum:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="56"/>
<source>, has not been successfully broadcast yet</source>
<translation>, henüz başarılı bir şekilde yayınlanmadı</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="58"/>
<source>, broadcast through %1 node</source>
<translation>, %1 düğüm vasıtasıyla yayınlandı</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="60"/>
<source>, broadcast through %1 nodes</source>
<translation>, %1 düğüm vasıtasıyla yayınlandı</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="64"/>
<source><b>Date:</b> </source>
<translation><b>Tarih:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="71"/>
<source><b>Source:</b> Generated<br></source>
<translation><b>Kaynak:</b> Oluşturuldu<br></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="77"/>
<location filename="../transactiondesc.cpp" line="94"/>
<source><b>From:</b> </source>
<translation><b>Gönderen:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="94"/>
<source>unknown</source>
<translation>bilinmiyor</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="95"/>
<location filename="../transactiondesc.cpp" line="118"/>
<location filename="../transactiondesc.cpp" line="178"/>
<source><b>To:</b> </source>
<translation><b>Alıcı:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="98"/>
<source> (yours, label: </source>
<translation> (sizin, etiket: </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="100"/>
<source> (yours)</source>
<translation> (sizin)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="136"/>
<location filename="../transactiondesc.cpp" line="150"/>
<location filename="../transactiondesc.cpp" line="195"/>
<location filename="../transactiondesc.cpp" line="212"/>
<source><b>Credit:</b> </source>
<translation><b>Gelir:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="138"/>
<source>(%1 matures in %2 more blocks)</source>
<translation>(%1, %2 ek blok sonrasında olgunlaşacak)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="142"/>
<source>(not accepted)</source>
<translation>(kabul edilmedi)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="186"/>
<location filename="../transactiondesc.cpp" line="194"/>
<location filename="../transactiondesc.cpp" line="209"/>
<source><b>Debit:</b> </source>
<translation><b>Gider:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="200"/>
<source><b>Transaction fee:</b> </source>
<translation><b>Muamele ücreti:<b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="216"/>
<source><b>Net amount:</b> </source>
<translation><b>Net miktar:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="222"/>
<source>Message:</source>
<translation>Mesaj:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="224"/>
<source>Comment:</source>
<translation>Yorum:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="226"/>
<source>Transaction ID:</source>
<translation>Muamele kimliği:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="229"/>
<source>Generated coins must wait 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, it will change to "not accepted" and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Oluşturulan FlorijnCoin'lerin harcanabilmelerinden önce 120 blok beklemeleri gerekmektedir. Bu blok, oluşturduğunuzda, blok zincirine eklenmesi için ağda yayınlandı. Zincire eklenmesi başarısız olursa, "kabul edilmedi" olarak değiştirilecek ve harcanamayacaktır. Bu, bazen başka bir düğüm sizden birkaç saniye önce ya da sonra blok oluşturursa meydana gelebilir.</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="14"/>
<source>Transaction details</source>
<translation>Muamele detayları</translation>
</message>
<message>
<location filename="../forms/transactiondescdialog.ui" line="20"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Bu pano muamelenin ayrıntılı açıklamasını gösterir</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="226"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="226"/>
<source>Type</source>
<translation>Tür</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="226"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="226"/>
<source>Amount</source>
<translation>Miktar</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="281"/>
<source>Open for %n block(s)</source>
<translation><numerusform>%n blok için açık</numerusform></translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="284"/>
<source>Open until %1</source>
<translation>%1 değerine dek açık</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="287"/>
<source>Offline (%1 confirmations)</source>
<translation>Çevrimdışı (%1 teyit)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="290"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Doğrulanmadı (%1 (toplam %2 üzerinden) teyit)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="293"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Doğrulandı (%1 teyit)</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="301"/>
<source>Mined balance will be available in %n more blocks</source>
<translation><numerusform>Madenden çıkarılan bakiye %n ek blok sonrasında kullanılabilecektir</numerusform></translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="307"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Bu blok başka hiçbir düğüm tarafından alınmamıştır ve muhtemelen kabul edilmeyecektir!</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="310"/>
<source>Generated but not accepted</source>
<translation>Oluşturuldu ama kabul edilmedi</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="353"/>
<source>Received with</source>
<translation>Şununla alındı</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="355"/>
<source>Received from</source>
<translation>Alındığı kişi</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="358"/>
<source>Sent to</source>
<translation>Gönderildiği adres</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="360"/>
<source>Payment to yourself</source>
<translation>Kendinize ödeme</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="362"/>
<source>Mined</source>
<translation>Madenden çıkarılan</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="400"/>
<source>(n/a)</source>
<translation>(mevcut değil)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="599"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Muamele durumu. Doğrulama sayısını görüntülemek için imleci bu alanda tutunuz.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="601"/>
<source>Date and time that the transaction was received.</source>
<translation>Muamelenin alındığı tarih ve zaman.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="603"/>
<source>Type of transaction.</source>
<translation>Muamele türü.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="605"/>
<source>Destination address of transaction.</source>
<translation>Muamelenin alıcı adresi.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="607"/>
<source>Amount removed from or added to balance.</source>
<translation>Bakiyeden alınan ya da bakiyeye eklenen miktar.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="55"/>
<location filename="../transactionview.cpp" line="71"/>
<source>All</source>
<translation>Hepsi</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="56"/>
<source>Today</source>
<translation>Bugün</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="57"/>
<source>This week</source>
<translation>Bu hafta</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="58"/>
<source>This month</source>
<translation>Bu ay</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="59"/>
<source>Last month</source>
<translation>Geçen ay</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="60"/>
<source>This year</source>
<translation>Bu sene</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="61"/>
<source>Range...</source>
<translation>Aralık...</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="72"/>
<source>Received with</source>
<translation>Şununla alınan</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="74"/>
<source>Sent to</source>
<translation>Gönderildiği adres</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="76"/>
<source>To yourself</source>
<translation>Kendinize</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="77"/>
<source>Mined</source>
<translation>Oluşturulan</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="78"/>
<source>Other</source>
<translation>Diğer</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="85"/>
<source>Enter address or label to search</source>
<translation>Aranacak adres ya da etiket giriniz</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="92"/>
<source>Min amount</source>
<translation>Asgari miktar</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="126"/>
<source>Copy address</source>
<translation>Adresi kopyala</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="127"/>
<source>Copy label</source>
<translation>Etiketi kopyala</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="128"/>
<source>Copy amount</source>
<translation>Miktarı kopyala</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="129"/>
<source>Edit label</source>
<translation>Etiketi düzenle</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="130"/>
<source>Show transaction details</source>
<translation>Muamele detaylarını göster</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="270"/>
<source>Export Transaction Data</source>
<translation>Muamele verilerini dışa aktar</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="271"/>
<source>Comma separated file (*.csv)</source>
<translation>Virgülle ayrılmış değerler dosyası (*.csv)</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="279"/>
<source>Confirmed</source>
<translation>Doğrulandı</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="280"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="281"/>
<source>Type</source>
<translation>Tür</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="282"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="283"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="284"/>
<source>Amount</source>
<translation>Miktar</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="285"/>
<source>ID</source>
<translation>Kimlik</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="289"/>
<source>Error exporting</source>
<translation>Dışa aktarımda hata oluştu</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="289"/>
<source>Could not write to file %1.</source>
<translation>%1 dosyasına yazılamadı.</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="384"/>
<source>Range:</source>
<translation>Aralık:</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="392"/>
<source>to</source>
<translation>ilâ</translation>
</message>
</context>
<context>
<name>VerifyMessageDialog</name>
<message>
<location filename="../forms/verifymessagedialog.ui" line="14"/>
<source>Verify Signed Message</source>
<translation>İmzalı mesajı kontrol et</translation>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="20"/>
<source>Enter the message and signature below (be careful to correctly copy newlines, spaces, tabs and other invisible characters) to obtain the FlorijnCoin address used to sign the message.</source>
<translation>Mesajı imzalamak için kullanılan FlorijnCoin adresini elde etmek için mesaj ve imzayı aşağıda giriniz (yani satırlar, boşluklar ve sekmeler gibi görünmeyen karakterleri doğru şekilde kopyalamaya dikkat ediniz).</translation>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="62"/>
<source>Verify a message and obtain the FlorijnCoin address used to sign the message</source>
<translation>Mesajı kontrol et ve imzalamak için kullanılan FlorijnCoin adresini elde et</translation>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="65"/>
<source>&Verify Message</source>
<translation>Mesajı &kontrol et</translation>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="79"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Şu anda seçili olan adresi panoya kopyalar</translation>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="82"/>
<source>&Copy Address</source>
<translation>Adresi &kopyala</translation>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="93"/>
<source>Reset all verify message fields</source>
<translation>Tüm mesaj kontrolü alanlarını sıfırla</translation>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="96"/>
<source>Clear &All</source>
<translation>Tümünü &temizle</translation>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="28"/>
<source>Enter FlorijnCoin signature</source>
<translation>FlorijnCoin imzası gir</translation>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="29"/>
<source>Click "Verify Message" to obtain address</source>
<translation>Adresi elde etmek için "Mesajı kontrol et" düğmesini tıkayınız</translation>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="55"/>
<location filename="../verifymessagedialog.cpp" line="62"/>
<source>Invalid Signature</source>
<translation>Geçersiz imza</translation>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="55"/>
<source>The signature could not be decoded. Please check the signature and try again.</source>
<translation>İmzanın kodu çözülemedi. İmzayı kontrol edip tekrar deneyiniz.</translation>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="62"/>
<source>The signature did not match the message digest. Please check the signature and try again.</source>
<translation>İmza mesajın hash değeri eşleşmedi. İmzayı kontrol edip tekrar deneyiniz.</translation>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="72"/>
<source>Address not found in address book.</source>
<translation>Bu adres, adres defterinde bulunamadı.</translation>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="72"/>
<source>Address found in address book: %1</source>
<translation>Adres defterinde bu adres bulundu: %1</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="158"/>
<source>Sending...</source>
<translation>Gönderiliyor...</translation>
</message>
</context>
<context>
<name>WindowOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="313"/>
<source>Window</source>
<translation>Pencere</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="316"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>İşlem çubuğu yerine sistem çekmecesine &küçült</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="317"/>
<source>Show only a tray icon after minimizing the window</source>
<translation>Küçültüldükten sonra sadece çekmece ikonu gösterir</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="320"/>
<source>M&inimize on close</source>
<translation>Kapatma sırasında k&üçült</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="321"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Pencere kapatıldığında uygulamadan çıkmak yerine uygulamayı küçültür. Bu seçenek etkinleştirildiğinde, uygulama sadece menüden çıkış seçildiğinde kapanacaktır.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="43"/>
<source>FlorijnCoin version</source>
<translation>FlorijnCoin sürümü</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="44"/>
<source>Usage:</source>
<translation>Kullanım:</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="45"/>
<source>Send command to -server or bitcoind</source>
<translation>-server ya da bitcoind'ye komut gönder</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="46"/>
<source>List commands</source>
<translation>Komutları listele</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="47"/>
<source>Get help for a command</source>
<translation>Bir komut için yardım al</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="49"/>
<source>Options:</source>
<translation>Seçenekler:</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="50"/>
<source>Specify configuration file (default: bitcoin.conf)</source>
<translation>Yapılandırma dosyası belirt (varsayılan: bitcoin.conf)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="51"/>
<source>Specify pid file (default: bitcoind.pid)</source>
<translation>Pid dosyası belirt (varsayılan: bitcoind.pid)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="52"/>
<source>Generate coins</source>
<translation>Madenî para (FlorijnCoin) oluştur</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="53"/>
<source>Don't generate coins</source>
<translation>FlorijnCoin oluşturmasını devre dışı bırak</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="54"/>
<source>Specify data directory</source>
<translation>Veri dizinini belirt</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="55"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Veritabanı önbellek boyutunu megabayt olarak belirt (varsayılan: 25)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="56"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>Diskteki veritabanı kütüğü boyutunu megabayt olarak belirt (varsayılan: 100)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="57"/>
<source>Specify connection timeout (in milliseconds)</source>
<translation>Bağlantı zaman aşım süresini milisaniye olarak belirt</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="63"/>
<source>Listen for connections on <port> (default: 8333 or testnet: 18333)</source>
<translation>Bağlantılar için dinlenecek <port> (varsayılan: 8333 ya da testnet: 18333)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="64"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Eşler ile en çok <n> adet bağlantı kur (varsayılan: 125)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="66"/>
<source>Connect only to the specified node</source>
<translation>Sadece belirtilen düğüme bağlan</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="67"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Eş adresleri elde etmek için bir düğüme bağlan ve ardından bağlantıyı kes</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="68"/>
<source>Specify your own public address</source>
<translation>Kendi genel adresinizi tanımlayın</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="69"/>
<source>Only connect to nodes in network <net> (IPv4 or IPv6)</source>
<translation>Sadece <net> şebekesindeki düğümlere bağlan (IPv4 ya da IPv6)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="70"/>
<source>Try to discover public IP address (default: 1)</source>
<translation>Genel IP adresini keşfetmeye çalış (varsayılan: 1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="73"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation>Belirtilen adresle ilişiklendir. IPv6 için [makine]:port simgelemini kullanınız</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="75"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Aksaklık gösteren eşlerle bağlantıyı kesme sınırı (varsayılan: 100)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="76"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Aksaklık gösteren eşlerle yeni bağlantıları engelleme süresi, saniye olarak (varsayılan: 86400)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="79"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)</source>
<translation>Her bağlantı için alım tamponu, <n>*1000 bayt (varsayılan: 10000)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="80"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)</source>
<translation>Her bağlantı için yollama tamponu, <n>*1000 bayt (varsayılan: 10000)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="83"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation>Blok ve adres veri tabanlarını ayır. Kapatma süresini arttırır (varsayılan: 0)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="86"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Konut satırı ve JSON-RPC komutlarını kabul et</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="87"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Arka planda daemon (servis) olarak çalış ve komutları kabul et</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="88"/>
<source>Use the test network</source>
<translation>Deneme şebekesini kullan</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="89"/>
<source>Output extra debugging information</source>
<translation>İlâve hata ayıklama verisi çıkar</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="90"/>
<source>Prepend debug output with timestamp</source>
<translation>Hata ayıklama çıktısına tarih ön ekleri ilâve et</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="91"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Trace/hata ayıklama verilerini debug.log dosyası yerine konsola gönder</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="92"/>
<source>Send trace/debug info to debugger</source>
<translation>Hata ayıklayıcıya -debugger- trace/hata ayıklama verileri gönder</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="93"/>
<source>Username for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için kullanıcı ismi</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="94"/>
<source>Password for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için parola</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="95"/>
<source>Listen for JSON-RPC connections on <port> (default: 8332)</source>
<translation>JSON-RPC bağlantıları için dinlenecek <port> (varsayılan: 8332)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="96"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Belirtilen İP adresinden JSON-RPC bağlantılarını kabul et</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="97"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Şu <ip> adresinde (varsayılan: 127.0.0.1) çalışan düğüme komut yolla</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="98"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>En iyi blok değiştiğinde komutu çalıştır (cmd için %s blok hash değeri ile değiştirilecektir)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="101"/>
<source>Upgrade wallet to latest format</source>
<translation>Cüzdanı en yeni biçime güncelle</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="102"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Anahtar alan boyutunu <n> değerine ayarla (varsayılan: 100)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="103"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Blok zincirini eksik cüzdan muameleleri için tekrar tara</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="104"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation>Başlangıçta ne kadar blokun denetleneceği (varsayılan: 2500, 0 = tümü)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="105"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>Blok kontrolünün derinliği (0 ilâ 6, varsayılan: 1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="106"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>Harici blk000?.dat dosyasından blokları içe aktarır</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="108"/>
<source>
SSL options: (see the FlorijnCoin Wiki for SSL setup instructions)</source>
<translation>
SSL seçenekleri: (SSL kurulum bilgisi için FlorijnCoin vikisine bakınız)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="111"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için OpenSSL (https) kullan</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="112"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Sunucu sertifika dosyası (varsayılan: server.cert)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="113"/>
<source>Server private key (default: server.pem)</source>
<translation>Sunucu özel anahtarı (varsayılan: server.pem)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="114"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Kabul edilebilir şifreler (varsayılan: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="145"/>
<source>Warning: Disk space is low</source>
<translation>Uyarı: Disk alanı düşük</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="107"/>
<source>This help message</source>
<translation>Bu yardım mesajı</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="121"/>
<source>Cannot obtain a lock on data directory %s. FlorijnCoin is probably already running.</source>
<translation>%s veri dizininde kilit elde edilemedi. FlorijnCoin muhtemelen hâlihazırda çalışmaktadır.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="48"/>
<source>FlorijnCoin</source>
<translation>FlorijnCoin</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="30"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Bu bilgisayarda %s unsuruna bağlanılamadı. (bind şu hatayı iletti: %d, %s)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="58"/>
<source>Connect through socks proxy</source>
<translation>Socks vekil sunucusu vasıtasıyla bağlan</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="59"/>
<source>Select the version of socks proxy to use (4 or 5, 5 is default)</source>
<translation>Kullanılacak socks vekil sunucu sürümünü seç (4 veya 5, ki 5 varsayılan değerdir)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="60"/>
<source>Do not use proxy for connections to network <net> (IPv4 or IPv6)</source>
<translation><net> şebekesi ile bağlantılarda vekil sunucu kullanma (IPv4 ya da IPv6)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="61"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>-addnode, -seednode ve -connect için DNS aramalarına izin ver</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="62"/>
<source>Pass DNS requests to (SOCKS5) proxy</source>
<translation>DNS isteklerini (SOCKS5) vekil sunucusuna devret</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="142"/>
<source>Loading addresses...</source>
<translation>Adresler yükleniyor...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="132"/>
<source>Error loading blkindex.dat</source>
<translation>blkindex.dat dosyasının yüklenmesinde hata oluştu</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="134"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>wallet.dat dosyasının yüklenmesinde hata oluştu: bozuk cüzdan</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="135"/>
<source>Error loading wallet.dat: Wallet requires newer version of FlorijnCoin</source>
<translation>wallet.dat dosyasının yüklenmesinde hata oluştu: cüzdanın daha yeni bir FlorijnCoin sürümüne ihtiyacı var</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="136"/>
<source>Wallet needed to be rewritten: restart FlorijnCoin to complete</source>
<translation>Cüzdanın tekrar yazılması gerekiyordu: işlemi tamamlamak için FlorijnCoin'i yeniden başlatınız</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="137"/>
<source>Error loading wallet.dat</source>
<translation>wallet.dat dosyasının yüklenmesinde hata oluştu</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="124"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Geçersiz -proxy adresi: '%s'</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="125"/>
<source>Unknown network specified in -noproxy: '%s'</source>
<translation>-noproxy'de bilinmeyen bir şebeke belirtildi: '%s'</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="127"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>-onlynet için bilinmeyen bir şebeke belirtildi: '%s'</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="126"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Bilinmeyen bir -socks vekil sürümü talep edildi: %i</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="128"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>-bind adresi çözümlenemedi: '%s'</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="129"/>
<source>Not listening on any port</source>
<translation>Hiçbir port dinlenmiyor</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="130"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>-externalip adresi çözümlenemedi: '%s'</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="117"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>-paytxfee=<miktar> için geçersiz miktar: '%s'</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="143"/>
<source>Error: could not start node</source>
<translation>Hata: düğüm başlatılamadı</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="31"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation>Hata: Cüzdan kilitli, muamele oluşturulamadı </translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="32"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation>Hata: Muamelenin miktarı, karmaşıklığı ya da yakın geçmişte alınan fonların kullanılması nedeniyle bu muamele en az %s tutarında ücret gerektirmektedir </translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="35"/>
<source>Error: Transaction creation failed </source>
<translation>Hata: Muamele oluşturması başarısız oldu </translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="36"/>
<source>Sending...</source>
<translation>Gönderiliyor...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="37"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Hata: Muamele reddedildi. Cüzdanınızdaki madenî paraların bazıları zaten harcanmış olduğunda bu meydana gelebilir. Örneğin wallet.dat dosyasının bir kopyasını kullandıysanız ve kopyada para harcandığında ancak burada harcandığı işaretlenmediğinde.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="41"/>
<source>Invalid amount</source>
<translation>Geçersiz miktar</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="42"/>
<source>Insufficient funds</source>
<translation>Yetersiz bakiye</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="131"/>
<source>Loading block index...</source>
<translation>Blok indeksi yükleniyor...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="65"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Bağlanılacak düğüm ekle ve bağlantıyı zinde tutmaya çalış</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="28"/>
<source>Unable to bind to %s on this computer. FlorijnCoin is probably already running.</source>
<translation>Bu bilgisayarda %s unsuruna bağlanılamadı. FlorijnCoin muhtemelen hâlihazırda çalışmaktadır.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="71"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation>Eşleri Internet Relay Chat vasıtasıyla bul (varsayılan: 0)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="72"/>
<source>Accept connections from outside (default: 1)</source>
<translation>Dışarıdan gelen bağlantıları kabul et (varsayılan: 1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="74"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation>Eşleri DNS araması vasıtasıyla bul (varsayılan: 1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="81"/>
<source>Use Universal Plug and Play to map the listening port (default: 1)</source>
<translation>Dinlenecek portu haritalamak için Universal Plug and Play kullan (varsayılan: 1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="82"/>
<source>Use Universal Plug and Play to map the listening port (default: 0)</source>
<translation>Dinlenecek portu haritalamak için Universal Plug and Play kullan (varsayılan: 0)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="85"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Yolladığınız muameleler için eklenecek KB başı ücret</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="118"/>
<source>Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction.</source>
<translation>Uyarı: -paytxfee çok yüksek bir değere ayarlanmış. Bu, muamele gönderirseniz ödeyeceğiniz muamele ücretidir.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="133"/>
<source>Loading wallet...</source>
<translation>Cüzdan yükleniyor...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="138"/>
<source>Cannot downgrade wallet</source>
<translation>Cüzdan eski biçime geri alınamaz</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="139"/>
<source>Cannot initialize keypool</source>
<translation>Keypool başlatılamadı</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="140"/>
<source>Cannot write default address</source>
<translation>Varsayılan adres yazılamadı</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="141"/>
<source>Rescanning...</source>
<translation>Yeniden tarama...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="144"/>
<source>Done loading</source>
<translation>Yükleme tamamlandı</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="8"/>
<source>To use the %s option</source>
<translation>%s seçeneğini kullanmak için</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="9"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=bitcoinrpc
rpcpassword=%s
(you do not need to remember this password)
If the file does not exist, create it with owner-readable-only file permissions.
</source>
<translation>%s, şu yapılandırma dosyasında rpc parolası belirtmeniz gerekir:
%s
Aşağıdaki rastgele oluşturulan parolayı kullanmanız tavsiye edilir:
rpcuser=bitcoinrpc
rpcpassword=%s
(bu parolayı hatırlamanız gerekli değildir)
Dosya mevcut değilse, sadece sahibi için okumayla sınırlı izin ile oluşturunuz.
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="18"/>
<source>Error</source>
<translation>Hata</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="19"/>
<source>An error occured while setting up the RPC port %i for listening: %s</source>
<translation>%i RPC portunun dinleme için kurulması sırasında bir hata meydana geldi: %s</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="20"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>rpcpassword=<parola> şu yapılandırma dosyasında belirtilmelidir:
%s
Dosya mevcut değilse, sadece sahibi için okumayla sınırlı izin ile oluşturunuz.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="25"/>
<source>Warning: Please check that your computer's date and time are correct. If your clock is wrong FlorijnCoin will not work properly.</source>
<translation>Uyarı: Lütfen bilgisayarınızın tarih ve saatinin doğru olup olmadığını kontrol ediniz. Saatiniz doğru değilse FlorijnCoin gerektiği gibi çalışamaz.</translation>
</message>
</context>
</TS> | dutchpatriot/florijncoin | src/qt/locale/bitcoin_tr.ts | TypeScript | mit | 116,366 |
package iso20022
// Amount of money debited or credited on the books of an account servicer.
type AmountAndDirection55 struct {
// Amount of money in the cash entry.
Amount *RestrictedFINActiveOrHistoricCurrencyAndAmount `xml:"Amt"`
// Indicates whether an entry is a credit or a debit.
CreditDebitIndicator *CreditDebitCode `xml:"CdtDbtInd,omitempty"`
// Posting/settlement amount in its original currency when conversion from/into another currency has occurred.
OriginalCurrencyAndOrderedAmount *RestrictedFINActiveOrHistoricCurrencyAndAmount `xml:"OrgnlCcyAndOrdrdAmt,omitempty"`
// Information needed to process a currency exchange or conversion.
ForeignExchangeDetails *ForeignExchangeTerms23 `xml:"FXDtls,omitempty"`
}
func (a *AmountAndDirection55) SetAmount(value, currency string) {
a.Amount = NewRestrictedFINActiveOrHistoricCurrencyAndAmount(value, currency)
}
func (a *AmountAndDirection55) SetCreditDebitIndicator(value string) {
a.CreditDebitIndicator = (*CreditDebitCode)(&value)
}
func (a *AmountAndDirection55) SetOriginalCurrencyAndOrderedAmount(value, currency string) {
a.OriginalCurrencyAndOrderedAmount = NewRestrictedFINActiveOrHistoricCurrencyAndAmount(value, currency)
}
func (a *AmountAndDirection55) AddForeignExchangeDetails() *ForeignExchangeTerms23 {
a.ForeignExchangeDetails = new(ForeignExchangeTerms23)
return a.ForeignExchangeDetails
}
| fgrid/iso20022 | AmountAndDirection55.go | GO | mit | 1,392 |
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.model.internal.core;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import groovy.lang.Closure;
import org.gradle.api.Action;
import org.gradle.api.internal.ClosureBackedAction;
import org.gradle.api.specs.Specs;
import org.gradle.model.ModelSet;
import org.gradle.model.internal.core.rule.describe.ModelRuleDescriptor;
import org.gradle.model.internal.manage.instance.ManagedInstance;
import org.gradle.model.internal.type.ModelType;
import java.util.Collection;
import java.util.Iterator;
import static org.gradle.model.internal.core.NodePredicate.allLinks;
public class NodeBackedModelSet<T> implements ModelSet<T>, ManagedInstance {
private final String toString;
private final ModelType<T> elementType;
private final ModelRuleDescriptor descriptor;
private final MutableModelNode modelNode;
private final ModelViewState state;
private final ChildNodeInitializerStrategy<T> creatorStrategy;
private final ModelReference<T> elementTypeReference;
private Collection<T> elements;
public NodeBackedModelSet(String toString, ModelType<T> elementType, ModelRuleDescriptor descriptor, MutableModelNode modelNode, ModelViewState state, ChildNodeInitializerStrategy<T> creatorStrategy) {
this.toString = toString;
this.elementType = elementType;
this.elementTypeReference = ModelReference.of(elementType);
this.descriptor = descriptor;
this.modelNode = modelNode;
this.state = state;
this.creatorStrategy = creatorStrategy;
}
@Override
public MutableModelNode getBackingNode() {
return modelNode;
}
@Override
public ModelType<?> getManagedType() {
return ModelType.of(this.getClass());
}
@Override
public String toString() {
return toString;
}
@Override
public void create(final Action<? super T> action) {
state.assertCanMutate();
String name = String.valueOf(modelNode.getLinkCount(ModelNodes.withType(elementType)));
ModelPath childPath = modelNode.getPath().child(name);
final ModelRuleDescriptor descriptor = this.descriptor.append("create()");
NodeInitializer nodeInitializer = creatorStrategy.initializer(elementType, Specs.<ModelType<?>>satisfyAll());
ModelRegistration registration = ModelRegistrations.of(childPath, nodeInitializer)
.descriptor(descriptor)
.action(ModelActionRole.Initialize, NoInputsModelAction.of(ModelReference.of(childPath, elementType), descriptor, action))
.build();
modelNode.addLink(registration);
}
@Override
public void afterEach(Action<? super T> configAction) {
state.assertCanMutate();
modelNode.applyTo(allLinks(), ModelActionRole.Finalize, NoInputsModelAction.of(elementTypeReference, descriptor.append("afterEach()"), configAction));
}
@Override
public void beforeEach(Action<? super T> configAction) {
state.assertCanMutate();
modelNode.applyTo(allLinks(), ModelActionRole.Defaults, NoInputsModelAction.of(elementTypeReference, descriptor.append("afterEach()"), configAction));
}
@Override
public int size() {
state.assertCanReadChildren();
return modelNode.getLinkCount(ModelNodes.withType(elementType));
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean contains(Object o) {
return getElements().contains(o);
}
@Override
public Iterator<T> iterator() {
return getElements().iterator();
}
@Override
public Object[] toArray() {
return getElements().toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return getElements().toArray(a);
}
@Override
public boolean add(T e) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> c) {
return getElements().containsAll(c);
}
@Override
public boolean addAll(Collection<? extends T> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
// TODO - mix this in using decoration. Also validate closure parameter types, if declared
public void create(Closure<?> closure) {
create(ClosureBackedAction.of(closure));
}
public void afterEach(Closure<?> closure) {
afterEach(ClosureBackedAction.of(closure));
}
public void beforeEach(Closure<?> closure) {
beforeEach(ClosureBackedAction.of(closure));
}
private Collection<T> getElements() {
state.assertCanReadChildren();
if (elements == null) {
elements = Lists.newArrayList(
Iterables.transform(modelNode.getLinks(ModelNodes.withType(elementType)), new Function<MutableModelNode, T>() {
@Override
public T apply(MutableModelNode input) {
return input.asImmutable(elementType, descriptor).getInstance();
}
})
);
}
return elements;
}
}
| HenryHarper/Acquire-Reboot | gradle/src/model-core/org/gradle/model/internal/core/NodeBackedModelSet.java | Java | mit | 6,263 |
/// <reference types="@types/google-maps" />
import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, Injector, Input, OnInit, ViewChild } from '@angular/core';
import { AddressView } from 'app/api/models';
import { Breakpoint } from 'app/core/layout.service';
import { BaseComponent } from 'app/shared/base.component';
import { AddressHelperService } from 'app/ui/core/address-helper.service';
import { MapsService } from 'app/ui/core/maps.service';
import { UiLayoutService } from 'app/ui/core/ui-layout.service';
import { CountriesResolve } from 'app/ui/countries.resolve';
/**
* Shows the user / advertisement address(es) in the view page
*/
@Component({
selector: 'profile-addresses',
templateUrl: 'profile-addresses.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProfileAddressesComponent extends BaseComponent implements OnInit, AfterViewInit {
constructor(
injector: Injector,
private uiLayout: UiLayoutService,
public addressHelper: AddressHelperService,
public maps: MapsService,
public countriesResolve: CountriesResolve,
) {
super(injector);
}
@ViewChild('mapContainer') mapContainer: ElementRef;
map: google.maps.Map;
private allInfoWindows: google.maps.InfoWindow[] = [];
@Input() addresses: AddressView[];
locatedAddresses: AddressView[];
ngOnInit() {
super.ngOnInit();
this.locatedAddresses = (this.addresses || []).filter(a => a.location);
}
ngAfterViewInit() {
// We'll only use a dynamic map with multiple located addresses
if (this.locatedAddresses.length > 1) {
this.addSub(this.maps.ensureScriptLoaded().subscribe(() => this.showMap()));
}
}
closeAllInfoWindows() {
this.allInfoWindows.forEach(iw => iw.close());
}
singleMapWidth(breakpoints: Set<Breakpoint>): number | 'auto' {
if (breakpoints.has('xl')) {
return 400;
} else if (breakpoints.has('gt-xs')) {
return 340;
} else {
return 'auto';
}
}
private showMap() {
const container = this.mapContainer.nativeElement as HTMLElement;
this.map = new google.maps.Map(container, {
mapTypeControl: false,
streetViewControl: false,
minZoom: 2,
maxZoom: 17,
styles: this.uiLayout.googleMapStyles,
});
const bounds = new google.maps.LatLngBounds();
this.locatedAddresses.map(a => {
const marker = new google.maps.Marker({
title: a.name,
icon: this.dataForFrontendHolder.dataForFrontend.mapMarkerUrl,
position: new google.maps.LatLng(a.location.latitude, a.location.longitude),
});
bounds.extend(marker.getPosition());
marker.addListener('click', () => {
this.closeAllInfoWindows();
let infoWindow = marker['infoWindow'] as google.maps.InfoWindow;
if (!infoWindow) {
infoWindow = new google.maps.InfoWindow({
content: marker.getTitle(),
});
this.allInfoWindows.push(infoWindow);
}
infoWindow.open(marker.getMap(), marker);
});
marker.setMap(this.map);
});
this.map.addListener('click', () => this.closeAllInfoWindows());
this.map.fitBounds(bounds);
}
}
| cyclosproject/cyclos4-ui | src/app/ui/shared/profile-addresses.component.ts | TypeScript | mit | 3,215 |
/**
* @file HGEventCollisionScripter.cpp
* @brief EventCollision script adapter implementation
*
* @author Master.G (MG), mg@snsteam.com
*
* @internal
* Created: 2013/02/21
* Company: SNSTEAM.inc
* (C) Copyright 2013 SNSTEAM.inc All rights reserved.
*
* This file is a part of Hourglass Engine Project.
*
* The copyright to the contents herein is the property of SNSTEAM.inc
* The contents may be used and/or copied only with the written permission of
* SNSTEAM.inc or in accordance with the terms and conditions stipulated in
* the agreement/contract under which the contents have been supplied.
* =====================================================================================
*/
#include "HGEventCollisionScripter.h"
#include "HGEvent.h"
#include "HGEventScripter.h"
#include "HGPhysicalEntity.h"
#include "HGPhysicalEntityScripter.h"
#define EVENTCOLLISION_METATABLE "EventCollisionMetatable"
#define EVENTCOLLISION_LUA_NAME "EventCollision"
HGNAMESPACE_START
EventCollision* eventcollision_check(lua_State* L, int idx)
{
EventCollision* event = NULL;
if (lua_isuserdata(L, idx))
event = *static_cast<EventCollision **>(luaL_checkudata(L, idx, EVENTCOLLISION_METATABLE));
return event;
}
int eventcollision_push(lua_State* L, EventCollision* event)
{
int ret = 0;
BREAK_START;
if (event == NULL)
break;
EventCollision** udata = static_cast<EventCollision **>(lua_newuserdata(L, sizeof(EventCollision *)));
*udata = event;
luaL_getmetatable(L, EVENTCOLLISION_METATABLE);
lua_setmetatable(L, -2);
ret = 1;
BREAK_END;
return ret;
}
// EventCollision methods
static int eventcollision_collision_type(lua_State* L)
{
EventCollision* event = NULL;
int collisionType = 0;
event = eventcollision_check(L, 1);
if (event != NULL)
collisionType = event->collisionType;
lua_pushinteger(L, collisionType);
return 1;
}
static int eventcollision_physical_obj(lua_State* L)
{
EventCollision* event = eventcollision_check(L, 1);
if (event != NULL)
{
PhysicalEntity *comp = (PhysicalEntity *)event->obj;
return physicalentity_push(L, comp);
}
return 0;
}
HGNAMESPACE_END
| master-g/hourglass | Hourglass/original/HGScript/HGEventScripter/HGEventCollisionScripter.cpp | C++ | mit | 2,308 |
# -*- coding: utf-8 -*-
'''
Description:
Extract the feature from the text in English.
Version:
python3
'''
from sklearn.feature_extraction.text import CountVectorizer
VECTORIZER = CountVectorizer(min_df=1)
# 以下代码设置了特征提取方法的参数(以1-2个单词作为滑动窗口大小,以空格作为单词的分割点,最小词频为1)
# 详细参考API介绍:
# http://scikit-learn.org/stable/modules/feature_extraction.html#text-feature-extraction
# VECTORIZER = CountVectorizer(ngram_range=(1,2), token_pattern=r'\b\w+\b', min_df=1)
CORPUS = [
'This is the first document.',
'This is the second second document.',
'And the third one.',
'Is this the first document?'
]
X = VECTORIZER.fit_transform(CORPUS)
FEATURE_NAMES = VECTORIZER.get_feature_names()
print(FEATURE_NAMES)
| Jackson-Y/Machine-Learning | text/feature_extraction.py | Python | mit | 828 |
export default function(field, bucketKey) {
switch (field) {
case 'average_rating':
return {
0: '☆☆☆☆☆',
1: '★☆☆☆☆',
2: '★★☆☆☆',
3: '★★★☆☆',
4: '★★★★☆',
5: '★★★★★',
}[bucketKey];
case 'completion_date':
case 'start_date':
return new Date(parseInt(bucketKey, 10)).getFullYear();
default:
return bucketKey;
}
}
| clinwiki-org/clinwiki | front/src/utils/aggs/aggKeyToInner.ts | TypeScript | mit | 461 |
# frozen_string_literal: true
module MediaWiktory::Wikipedia
module Modules
# Output nothing.
#
# The "submodule" (MediaWiki API term) is included in action after setting some param, providing
# additional tweaking for this param. Example (for {MediaWiktory::Wikipedia::Actions::Query} and
# its submodules):
#
# ```ruby
# api.query # returns Actions::Query
# .prop(:revisions) # adds prop=revisions to action URL, and includes Modules::Revisions into action
# .limit(10) # method of Modules::Revisions, adds rvlimit=10 to URL
# ```
#
# All submodule's parameters are documented as its public methods, see below.
#
module None
end
end
end
| molybdenum-99/mediawiktory | lib/mediawiktory/wikipedia/modules/none.rb | Ruby | mit | 735 |
require "mars_geo/version"
module MarsGeo
autoload :Converter, 'mars_geo/converter'
autoload :Point, 'mars_geo/point'
end
| jonnyzheng/mars_geo | lib/mars_geo.rb | Ruby | mit | 127 |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
namespace MonogameDraw
{
public enum LINECAP
{
NONE,
SQUARE,
CIRCLE
};
public class Renderer
{
private GraphicsDevice gd;
private BasicEffect effect;
private Matrix orthographic;
private static VertexPosition[] drawRectangleVertices = new[] {
new VertexPosition(new Vector3(-0.5f, -0.5f, 0)),
new VertexPosition(new Vector3(0.5f, -0.5f, 0)),
new VertexPosition(new Vector3(0.5f, 0.5f, 0)),
new VertexPosition(new Vector3(-0.5f, 0.5f, 0)),
new VertexPosition(new Vector3(-0.5f, -0.5f, 0))
};
private static VertexPosition[] fillRectangleVertices = new[] {
new VertexPosition(new Vector3(-0.5f, -0.5f, 0)),
new VertexPosition(new Vector3(0.5f, -0.5f, 0)),
new VertexPosition(new Vector3(-0.5f, 0.5f, 0)),
new VertexPosition(new Vector3(0.5f, 0.5f, 0))
};
private static Dictionary<int, VertexPosition[]> filledNgons = new Dictionary<int, VertexPosition[]>();
private static Dictionary<int, VertexPosition[]> drawnNgons = new Dictionary<int, VertexPosition[]>();
private const int NGON_CACHE_SIZE = 25;
public Renderer(GraphicsDevice gd)
{
this.gd = gd;
effect = new BasicEffect(gd);
orthographic = Matrix.CreateOrthographicOffCenter(0, gd.Viewport.Width, gd.Viewport.Height, 0, 0, 1);
}
~Renderer()
{
effect.Dispose();
}
private void Draw(PrimitiveType primitiveType, VertexPosition[] vertexPositions, int primitiveCount, Color color, Matrix worldMatrix)
{
effect.World = worldMatrix;
effect.DiffuseColor = color.ToVector3();
foreach (EffectPass pass in effect.CurrentTechnique.Passes)
{
pass.Apply();
gd.DrawUserPrimitives(primitiveType, vertexPositions, 0, primitiveCount);
}
}
public void FillNgon(float x, float y, float rx, float ry, int sides, Color color, double angle = 0, double offsetAngle = 0)
{
if (rx <= 0 || ry <= 0 || sides < 3) return;
VertexPosition[] vertexPositions;
if (filledNgons.ContainsKey(sides))
{
vertexPositions = filledNgons[sides];
}
else
{
Vector3[] vertices = new Vector3[sides];
double nextAngle = MathHelper.TwoPi / sides;
for (int i = 0; i < sides; i++)
{
double currX = Math.Cos(nextAngle * i + offsetAngle - MathHelper.PiOver2);
double currY = Math.Sin(nextAngle * i + offsetAngle - MathHelper.PiOver2);
vertices[i] = new Vector3((float)currX, (float)currY, 0);
}
vertexPositions = new VertexPosition[sides];
vertexPositions[0] = new VertexPosition(vertices[0]);
for (int i = 0; i < sides / 2; i++)
{
vertexPositions[i * 2 + 1] = new VertexPosition(vertices[i + 1]);
if (i * 2 + 2 != sides)
vertexPositions[i * 2 + 2] = new VertexPosition(vertices[sides - i - 1]);
}
if (filledNgons.Count > NGON_CACHE_SIZE) filledNgons.Remove(filledNgons.Keys.First());
filledNgons.Add(sides, vertexPositions);
}
Matrix translation = Matrix.CreateTranslation(x, y, 0);
Matrix rotation = Matrix.CreateRotationZ((float)angle);
Matrix scale = Matrix.CreateScale(rx, ry, 1);
Draw(PrimitiveType.TriangleStrip, vertexPositions, sides - 2, color, scale * rotation * translation * orthographic);
}
public void FillRect(float x, float y, float width, float height, Color color, double angle = 0)
{
Matrix translation = Matrix.CreateTranslation(x, y, 0);
Matrix rotation = Matrix.CreateRotationZ((float)angle);
Matrix scale = Matrix.CreateScale(width, height, 1);
Draw(PrimitiveType.TriangleStrip, fillRectangleVertices, 2, color, scale * rotation * translation * orthographic);
}
public void FillSquare(float x, float y, float length, Color color, double angle = 0)
{
FillRect(x, y, length, length, color, angle);
}
public void FillCircle(float x, float y, float radius, Color color, float quality = 1f)
{
FillEllipse(x, y, radius, radius, color, quality);
}
public void FillEllipse(float x, float y, float rx, float ry, Color color, float quality = 1f)
{
int sides = Math.Max((int)(quality * (rx + ry) / 3f + 3), 8);
FillNgon(x, y, rx, ry, sides, color);
}
public void StrokeLine(float ax, float ay, float bx, float by, Color color, int thickness = 1, LINECAP linecap = LINECAP.NONE)
{
if (thickness == 1)
{
VertexPosition[] vertexPositions = new[]
{
new VertexPosition(new Vector3(ax, ay, 0)),
new VertexPosition(new Vector3(bx, by, 0))
};
Draw(PrimitiveType.LineStrip, vertexPositions, 1, color, orthographic);
}
else
{
double angle = Math.Atan2(by - ay, bx - ax);
float xDelta = (float)(Math.Cos(angle + MathHelper.PiOver2) * thickness / 2);
float yDelta = (float)(Math.Sin(angle + MathHelper.PiOver2) * thickness / 2);
VertexPosition[] vertexPositions = new[]
{
new VertexPosition(new Vector3(ax + xDelta, ay + yDelta, 0)),
new VertexPosition(new Vector3(ax - xDelta, ay - yDelta, 0)),
new VertexPosition(new Vector3(bx + xDelta, by + yDelta, 0)),
new VertexPosition(new Vector3(bx - xDelta, by - yDelta, 0))
};
if (thickness > 2)
{
switch (linecap)
{
case LINECAP.CIRCLE:
FillCircle(ax, ay, thickness / 2, color);
FillCircle(bx, by, thickness / 2, color);
break;
case LINECAP.SQUARE:
FillSquare(ax, ay, thickness, color, angle);
FillSquare(bx, by, thickness, color, angle);
break;
}
}
Draw(PrimitiveType.TriangleStrip, vertexPositions, 2, color, orthographic);
}
}
public void StrokePath(List<Vector2> points, Color color, int thickness = 1, LINECAP linecap = LINECAP.NONE)
{
if (points.Count < 2) return;
if (thickness == 1)
{
VertexPosition[] vertexPositions = new VertexPosition[points.Count];
for (int i = 0; i < points.Count; i++)
{
vertexPositions[i] = new VertexPosition(new Vector3(points[i].X, points[i].Y, 0));
}
Draw(PrimitiveType.LineStrip, vertexPositions, points.Count - 1, color, orthographic);
}
else
{
if (points.Count == 2)
{
StrokeLine(points[0].X, points[0].Y, points[1].X, points[2].Y, color, thickness);
return;
}
VertexPosition[] vertexPositions = new VertexPosition[points.Count * 4 - 4];
double angle = 0;
for (int i = 0; i < points.Count - 1; i++)
{
Vector2 point = points[i];
Vector2 nextPoint = points[i + 1];
angle = Math.Atan2(nextPoint.Y - point.Y, nextPoint.X - point.X);
float xDelta = (float)(Math.Cos(angle + MathHelper.PiOver2) * thickness / 2);
float yDelta = (float)(Math.Sin(angle + MathHelper.PiOver2) * thickness / 2);
vertexPositions[4 * i] = new VertexPosition(new Vector3(point.X + xDelta, point.Y + yDelta, 0));
vertexPositions[4 * i + 1] = new VertexPosition(new Vector3(point.X - xDelta, point.Y - yDelta, 0));
vertexPositions[4 * i + 2] = new VertexPosition(new Vector3(nextPoint.X + xDelta, nextPoint.Y + yDelta, 0));
vertexPositions[4 * i + 3] = new VertexPosition(new Vector3(nextPoint.X - xDelta, nextPoint.Y - yDelta, 0));
switch(linecap)
{
case LINECAP.CIRCLE:
FillCircle(points[i].X, points[i].Y, thickness / 2, color);
break;
case LINECAP.SQUARE:
if(i == 0) FillSquare(points[i].X, points[i].Y, thickness, color, angle);
break;
}
}
switch (linecap)
{
case LINECAP.CIRCLE:
FillCircle(points[points.Count - 1].X, points[points.Count - 1].Y, thickness / 2, color);
break;
case LINECAP.SQUARE:
FillSquare(points[points.Count - 1].X, points[points.Count - 1].Y, thickness, color, angle);
break;
}
Draw(PrimitiveType.TriangleStrip, vertexPositions, points.Count * 4 - 6, color, orthographic);
}
}
public void StrokeLoop(List<Vector2> points, Color color, int thickness = 1)
{
if (points.Count < 2) return;
if (thickness == 1)
{
points.Add(points[0]);
StrokePath(points, color, thickness);
}
else
{
if (points.Count == 2)
{
StrokeLine(points[0].X, points[0].Y, points[1].X, points[2].Y, color, thickness);
return;
}
points.Add(points[0]);
VertexPosition[] vertexPositions = new VertexPosition[points.Count * 4 - 2];
for (int i = 0; i < points.Count - 1; i++)
{
Vector2 point = points[i];
Vector2 nextPoint = points[i + 1];
double angle = Math.Atan2(nextPoint.Y - point.Y, nextPoint.X - point.X);
float xDelta = (float)(Math.Cos(angle + MathHelper.PiOver2) * thickness / 2);
float yDelta = (float)(Math.Sin(angle + MathHelper.PiOver2) * thickness / 2);
vertexPositions[4 * i] = new VertexPosition(new Vector3(point.X + xDelta, point.Y + yDelta, 0));
vertexPositions[4 * i + 1] = new VertexPosition(new Vector3(point.X - xDelta, point.Y - yDelta, 0));
vertexPositions[4 * i + 2] = new VertexPosition(new Vector3(nextPoint.X + xDelta, nextPoint.Y + yDelta, 0));
vertexPositions[4 * i + 3] = new VertexPosition(new Vector3(nextPoint.X - xDelta, nextPoint.Y - yDelta, 0));
}
vertexPositions[vertexPositions.Length - 2] = vertexPositions[0];
vertexPositions[vertexPositions.Length - 1] = vertexPositions[1];
Draw(PrimitiveType.TriangleStrip, vertexPositions, points.Count * 4 - 4, color, orthographic);
}
}
public void StrokeNgon(float x, float y, float rx, float ry, int sides, Color color, double angle = 0, double offsetAngle = 0)
{
if (rx <= 0 || ry <= 0 || sides < 3) return;
VertexPosition[] vertexPositions;
if (drawnNgons.ContainsKey(sides))
{
vertexPositions = drawnNgons[sides];
}
else
{
vertexPositions = new VertexPosition[sides + 1];
double nextAngle = MathHelper.TwoPi / sides;
for (int i = 0; i < sides; i++)
{
double currX = Math.Cos(nextAngle * i + offsetAngle - MathHelper.PiOver2);
double currY = Math.Sin(nextAngle * i + offsetAngle - MathHelper.PiOver2);
vertexPositions[i] = new VertexPosition(new Vector3((float)currX, (float)currY, 0));
}
vertexPositions[vertexPositions.Length - 1] = vertexPositions[0];
if (drawnNgons.Count > NGON_CACHE_SIZE) drawnNgons.Remove(drawnNgons.Keys.First());
drawnNgons.Add(sides, vertexPositions);
}
Matrix translation = Matrix.CreateTranslation(x, y, 0);
Matrix rotation = Matrix.CreateRotationZ((float)angle);
Matrix scale = Matrix.CreateScale(rx, ry, 1);
Draw(PrimitiveType.LineStrip, vertexPositions, sides, color, scale * rotation * translation * orthographic);
}
public void StrokeCircle(float x, float y, float radius, Color color, float qualityFactor = 1f)
{
StrokeEllipse(x, y, radius, radius, color, qualityFactor);
}
public void StrokeEllipse(float x, float y, float rx, float ry, Color color, float qualityFactor = 1f)
{
int quality = Math.Max((int)(qualityFactor * ((rx + ry) / 3f + 3)), 8);
StrokeNgon(x, y, rx, ry, quality, color);
}
public void StrokeRect(float x, float y, float width, float height, Color color, double angle = 0)
{
Matrix translation = Matrix.CreateTranslation(x, y, 0);
Matrix rotation = Matrix.CreateRotationZ((float)angle);
Matrix scale = Matrix.CreateScale(width, height, 1);
Draw(PrimitiveType.LineStrip, drawRectangleVertices, 4, color, scale * rotation * translation * orthographic);
}
}
}
| battesonb/MonogameDraw | MonogameDraw/Renderer.cs | C# | mit | 11,384 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PathConverter
{
class Converter
{
public static string[] Convert(string input)
{
var results = new string[4];
if (String.IsNullOrEmpty(input)) return results;
var parts = input.Split(new[] { '/', '\\' });
if (parts.Length < 2) return results;
// suppose input is valid path to make things simple
var first = parts[0];
string driver = null;
string driver2 = null;
bool skipSecond = false;
if (first == String.Empty)
{
var second = parts[1];
if (second.Length == 1 && Char.IsLetter(second, 0))
{
driver = second + ':';
driver2 = "/" + second;
skipSecond = true;
}
}
else if (first.EndsWith(":"))
{
driver = first;
driver2 = "/" + first.TrimEnd(':');
}
var list = new List<string> { driver ?? first };
// clear the extra path delimiters
var i = skipSecond ? 2 : 1;
for (; i < parts.Length; i++)
{
var item = parts[i];
if (item != String.Empty) list.Add(item);
}
// the last path delimiter should be preserved
var last = parts.Last();
if (last == String.Empty) list.Add(last);
var s3 = String.Join(@"/", list);
results = new string[]
{
String.Join(@"\", list),
String.Join(@"\\", list),
s3,
s3
};
if (!String.IsNullOrEmpty(driver2))
{
list[0] = driver2;
results[3] = String.Join(@"/", list);
}
return results;
}
}
}
| yanxyz/Backslash2Slash | PathConverter/Converter.cs | C# | mit | 2,124 |
require "transformator/transformation/step"
require_relative "../request_transformation"
class Skala::PrimoAdapter::Search::RequestTransformation::
SetOnCampus < Transformator::Transformation::Step
def call
transformation.inner_search_request.locate("onCampus").first.tap do |_node|
_node << (transformation.on_campus.try(:to_s) == "true" ? "true" : "false")
end
end
end
| ubpb/skala | lib/skala/primo_adapter/search/request_transformation/set_on_campus.rb | Ruby | mit | 394 |
package mekanism.common.transmitters;
import mekanism.api.transmitters.DynamicNetwork;
import mekanism.api.transmitters.IGridTransmitter;
public abstract class Transmitter<A, N extends DynamicNetwork<A, N>> implements IGridTransmitter<A, N>
{
public N theNetwork = null;
public boolean orphaned = true;
@Override
public N getTransmitterNetwork()
{
return theNetwork;
}
@Override
public boolean hasTransmitterNetwork()
{
return !isOrphan() && getTransmitterNetwork() != null;
}
@Override
public void setTransmitterNetwork(N network)
{
if(theNetwork == network)
{
return;
}
if(world().isRemote && theNetwork != null)
{
theNetwork.transmitters.remove(this);
if(theNetwork.transmitters.isEmpty())
{
theNetwork.deregister();
}
}
theNetwork = network;
orphaned = theNetwork == null;
if(world().isRemote && theNetwork != null)
{
theNetwork.transmitters.add(this);
}
}
@Override
public int getTransmitterNetworkSize()
{
return hasTransmitterNetwork() ? getTransmitterNetwork().getSize() : 0;
}
@Override
public int getTransmitterNetworkAcceptorSize()
{
return hasTransmitterNetwork() ? getTransmitterNetwork().getAcceptorSize() : 0;
}
@Override
public String getTransmitterNetworkNeeded()
{
return hasTransmitterNetwork() ? getTransmitterNetwork().getNeededInfo() : "No Network";
}
@Override
public String getTransmitterNetworkFlow()
{
return hasTransmitterNetwork() ? getTransmitterNetwork().getFlowInfo() : "No Network";
}
@Override
public String getTransmitterNetworkBuffer()
{
return hasTransmitterNetwork() ? getTransmitterNetwork().getStoredInfo() : "No Network";
}
@Override
public double getTransmitterNetworkCapacity()
{
return hasTransmitterNetwork() ? getTransmitterNetwork().getCapacity() : getCapacity();
}
@Override
public boolean isOrphan()
{
return orphaned;
}
@Override
public void setOrphan(boolean nowOrphaned)
{
orphaned = nowOrphaned;
}
}
| Microsoft/vsminecraft | minecraftpkg/MekanismModSample/src/main/java/mekanism/common/transmitters/Transmitter.java | Java | mit | 1,976 |
using DevExpress.XtraEditors;
namespace DevExpress.MailClient.Win.Controls {
public class BackstageViewLabel : LabelControl {
public BackstageViewLabel() {
Appearance.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
AutoSizeMode = DevExpress.XtraEditors.LabelAutoSizeMode.None;
LineLocation = DevExpress.XtraEditors.LineLocation.Bottom;
LineVisible = true;
ShowLineShadow = false;
}
}
}
| svlcode/MailClient | sources/DevExpress.MailClient.Win/Controls/BackstageViewLabel.cs | C# | mit | 554 |
#include "main.hpp"
TargetSelector::TargetSelector(SelectorType type, float range)
: type(type), range(range) {
}
void TargetSelector::selectTargets(Actor *wearer, TCODList<Actor *> & list) {
switch(type) {
case CLOSEST_MONSTER :
{
Actor *closestMonster=engine.getClosestMonster(wearer->x,wearer->y,range);
if ( closestMonster ) {
list.push(closestMonster);
}
}
break;
case SELECTED_MONSTER :
{
int x,y;
engine.gui->message(TCODColor::cyan, "Left-click to select an enemy,\nor right-click to cancel.");
if ( engine.pickATile(&x,&y,range)) {
Actor *actor=engine.getActor(x,y);
if ( actor ) {
list.push(actor);
}
}
}
break;
case WEARER_RANGE :
for (Actor **iterator=engine.actors.begin();
iterator != engine.actors.end(); iterator++) {
Actor *actor=*iterator;
if ( actor->destructible && !actor->destructible->isDead()
&& actor->getDistance(wearer->x,wearer->y) <= range) {
list.push(actor);
}
}
break;
case SELECTED_RANGE :
int x,y;
engine.gui->message(TCODColor::cyan, "Left-click to select a tile,\nor right-click to cancel.");
if ( engine.pickATile(&x,&y)) {
for (Actor **iterator=engine.actors.begin();
iterator != engine.actors.end(); iterator++) {
Actor *actor=*iterator;
if ( actor->destructible && !actor->destructible->isDead()
&& actor->getDistance(x,y) <= range) {
list.push(actor);
}
}
}
break;
}
if ( list.isEmpty() ) {
engine.gui->message(TCODColor::lightGrey,"No enemy is close enough");
}
}
HealthEffect::HealthEffect(float amount, const char *message)
: amount(amount), message(message) {
}
bool HealthEffect::applyTo(Actor *actor) {
if (!actor->destructible) return false;
if ( amount > 0 ) {
float pointsHealed=actor->destructible->heal(amount);
if (pointsHealed > 0) {
if ( message ) {
engine.gui->message(TCODColor::lightGrey,message,actor->name,pointsHealed);
}
return true;
}
} else {
if ( message && -amount-actor->destructible->defense > 0 ) {
engine.gui->message(TCODColor::lightGrey,message,actor->name,
-amount-actor->destructible->defense);
}
if ( actor->destructible->takeDamage(actor,-amount) > 0 ) {
return true;
}
}
return false;
}
AiChangeEffect::AiChangeEffect(TemporaryAi *newAi, const char *message)
: newAi(newAi), message(message) {
}
bool AiChangeEffect::applyTo(Actor *actor) {
newAi->applyTo(actor);
if ( message ) {
engine.gui->message(TCODColor::lightGrey,message,actor->name);
}
return true;
}
Pickable::Pickable(TargetSelector *selector, Effect *effect) :
selector(selector), effect(effect) {
}
Pickable::~Pickable() {
if ( selector ) delete selector;
if ( effect ) delete effect;
}
bool Pickable::pick(Actor *owner, Actor *wearer) {
if ( wearer->container && wearer->container->add(owner) ) {
engine.actors.remove(owner);
return true;
}
return false;
}
void Pickable::drop(Actor *owner, Actor *wearer) {
if ( wearer->container ) {
wearer->container->remove(owner);
engine.actors.push(owner);
owner->x=wearer->x;
owner->y=wearer->y;
engine.gui->message(TCODColor::lightGrey,"%s drops a %s.",
wearer->name,owner->name);
}
}
bool Pickable::use(Actor *owner, Actor *wearer) {
TCODList<Actor *> list;
if ( selector ) {
selector->selectTargets(wearer, list);
} else {
list.push(wearer);
}
bool succeed=false;
for (Actor **it=list.begin(); it!=list.end(); it++) {
if ( effect->applyTo(*it) ) {
succeed=true;
}
}
if ( succeed ) {
if ( wearer->container ) {
wearer->container->remove(owner);
delete owner;
}
}
return succeed;
}
| vrum/rlTut | rlTut/Pickable.cpp | C++ | mit | 3,659 |
<?php
/*
/*
* Made by Samerton
* Translation by Hi_Michael
* https://github.com/NamelessMC/Nameless/
* NamelessMC version 2.0.0-pr12
*
* License: MIT
*
* Chinese Language - Users
* Translation progress : 97%
* 翻譯有誤請使用GitHun回報issues
* https://github.com/haer0248/NamelessMC-v2-Traditional-Chinese/issues
*/
$language = [
/*
* Change this for the account validation message
*/
'validate_account_command' => 'To complete registration, please execute the command <strong>/verify {x}</strong> ingame.', // Don't replace {x}
/*
* User Related
*/
'guest' => '遊客',
'guests' => '遊客',
// UserCP
'user_cp' => '使用者後台',
'user_cp_icon' => '<i class="fa fa-cogs" aria-hidden="true"></i>',
'overview' => '總覽',
'user_details' => '使用者資訊',
'profile_settings' => '個人檔設定',
'successfully_logged_out' => '成功登出.',
'messaging' => '訊息',
'click_here_to_view' => '點擊查看.',
'moderation' => 'Moderation',
'alerts' => '提醒',
'delete_all' => '移除全部',
'private_profile' => 'Private profile',
'gif_avatar' => 'Upload .gif as custom avatar',
'placeholders' => 'Placeholders',
'no_placeholders' => 'No Placeholders',
// Profile settings
'field_is_required' => '需要 {x}.', // Don't replace {x}
'settings_updated_successfully' => '設定更新成功.',
'password_changed_successfully' => '密碼更新成功.',
'change_password' => '更換密碼',
'current_password' => '目前密碼',
'new_password' => '新密碼',
'confirm_new_password' => '確認新密碼',
'incorrect_password' => '密碼錯誤.',
'two_factor_auth' => 'TFA 二次驗證',
'enabled' => 'Enabled',
'disabled' => 'Disabled',
'enable' => '啟用',
'disable' => '禁用',
'tfa_scan_code' => '請在APP中掃描以下QR Code:',
'tfa_code' => '如果你的手機沒有相機鏡頭可以掃描QR Code,請輸入以下代碼:',
'tfa_enter_code' => '請在APP中輸入顯示的代碼:',
'invalid_tfa' => '代碼錯誤,請重試.',
'tfa_successful' => 'TFA二次驗證設定成功. 每次登入時必須二次驗證才能登入成功.',
'active_language' => '啟用語言',
'active_template' => 'Active Template',
'timezone' => '時區',
'upload_new_avatar' => '上傳新的頭像',
'nickname_already_exists' => 'Your chosen nickname already exists.',
'change_email_address' => 'Change Email Address',
'email_already_exists' => 'The email address you have entered already exists.',
'email_changed_successfully' => 'Email address changed successfully.',
'avatar' => 'Avatar',
'profile_banner' => 'Profile Banner',
'upload_profile_banner' => 'Upload Profile Banner',
'upload' => 'Upload',
'topic_updates' => 'Get emails for topics you follow',
'gravatar' => 'Use Gravatar as avatar',
// Alerts
'user_tag_info' => '你被標註於 {x}.', // Don't replace {x}
'no_alerts' => '沒有新提醒',
'view_alerts' => '檢視提醒',
'1_new_alert' => 'You have 1 new alert',
'x_new_alerts' => '你有 {x} 個新提醒', // Don't replace {x}
'no_alerts_usercp' => '你沒有任何提醒.',
// Registraton
'registration_check_email' => '感謝您的註冊! 請檢查你的電子郵件來完成註冊動作. 如果你沒有收到信請檢查垃圾信箱.',
'username' => '帳號',
'nickname' => '暱稱',
'minecraft_username' => 'Minecraft Username (遊戲名稱)',
'email_address' => '電子郵件位置',
'email' => '電子郵件',
'password' => '密碼',
'confirm_password' => '確認密碼',
'i_agree' => '我同意',
'agree_t_and_c' => 'I have read and accept the <a href="{x}" target="_blank">Terms and Conditions</a>.',
'create_an_account' => '建立帳號',
'terms_and_conditions' => '使用條款',
'validation_complete' => '你的帳戶已被驗證,你現在可以登入.',
'validation_error' => '驗證失敗,請聯絡網站管理員.',
'signature' => '簽名檔',
'signature_max_900' => '你的簽名檔字元超過900字.',
// Registration - Authme
'connect_with_authme' => '使用AuthMe連接帳戶',
'authme_help' => '請輸入在遊戲中的AuthMe帳戶資訊. 如果你沒有帳號,請依照伺服器給予的說明操作.',
'unable_to_connect_to_authme_db' => '無法連線至AuthMe資料庫,如果錯誤仍然存在,請連接網站管理員.',
'authme_account_linked' => '帳戶連接成功.',
'authme_email_help_1' => '完成,請輸入電子郵件.',
'authme_email_help_2' => '完成,請輸入電子郵件和選取帳戶名.',
// Registration errors
'username_required' => '帳號是必須的.',
'email_required' => '電子郵件是必須的.',
'password_required' => '密碼是必須的.',
'mcname_required' => 'Minecraft username(遊戲名稱) 是必須的.',
'accept_terms' => '你必須接受服務條款.',
'username_minimum_3' => '帳號最底限制 3 字元.',
'mcname_minimum_3' => 'Minecraft username (遊戲名稱) 最低限制 3 字元.',
'password_minimum_6' => '密碼最低限制 6 字元.',
'username_maximum_20' => '帳號限制最高 20 字元.',
'mcname_maximum_20' => 'Minecraft username (遊戲名稱) 最高限制 30 字元.',
'passwords_dont_match' => '密碼不相同.',
'username_mcname_email_exists' => '帳號或電子郵件已存在.',
'invalid_mcname' => 'Minecraft username 不相符 (非正版).',
'invalid_email' => '電子郵件不正確.',
'mcname_lookup_error' => '目前無法連接到 Moajng 伺服器,請稍等再試.',
'invalid_recaptcha' => '無效的 reCAPTCHA.',
'verify_account' => '驗證帳號',
'verify_account_help' => '請依照下列的說明來驗證 Minecraft 帳戶為您所有.',
'validate_account' => 'Validate Account',
'verification_failed' => '驗證失敗,請重試.',
'verification_success' => '成功驗證,已可以登入.',
'authme_username_exists' => '你的 AuthMe 帳號已存在,請直接登入',
'uuid_already_exists' => 'Your UUID already exists, meaning this Minecraft account has already registered.',
// Login
'successful_login' => '登入成功.',
'incorrect_details' => '部分資料輸入錯誤.',
'inactive_account' => ' 帳戶已啟動. 請點擊電子郵件驗證信,或許會在垃圾桶.',
'account_banned' => '帳戶已被封禁.',
'forgot_password' => '忘記密碼?',
'remember_me' => '記住我',
'must_input_email' => 'You must input an email address.',
'must_input_username' => '你必須輸入帳號.',
'must_input_password' => '你必須輸入密碼.',
'must_input_email_or_username' => 'You must input an email or username.',
'email_or_username' => 'Email or Username',
// Forgot password
'forgot_password_instructions' => '請輸入你的電子郵件讓我們可以在你忘記密碼時寄一封信給你重設密碼.',
'forgot_password_email_sent' => '如果該帳號已有電子郵件,則已發送包含進一步的說明. 如果你沒看到,請檢查你的垃圾桶.',
'unable_to_send_forgot_password_email' => '無法傳送忘記密碼電子郵件,請聯絡網站管理員.',
'enter_new_password' => '請確認你的電子郵件並在下面輸入密碼.',
'incorrect_email' => '電子郵件錯誤.',
'forgot_password_change_successful' => '密碼變更成功,你可以登入了.',
// Profile pages
'profile' => '個人檔',
'follow' => '追隨',
'no_wall_posts' => '這個人的塗鴉牆沒有東西.',
'change_banner' => '更換橫幅',
'post_on_wall' => '塗鴉牆上有 {x} 篇文章', // Don't replace {x}
'invalid_wall_post' => '請輸入 1 ~ 10000 個字元的文章內容.',
'1_reaction' => '1 個回應',
'x_reactions' => '{x} 個回應', // Don't replace {x}
'1_like' => '1 個讚',
'x_likes' => '{x} 個讚', // Don't replace {x}
'1_reply' => '1 個回覆',
'x_replies' => '{x} 個回覆', // Don't replace {x}
'no_replies_yet' => '這邊沒有回覆',
'feed' => '回饋',
'about' => '關於',
'reactions' => '回應',
'replies' => '回覆',
'new_reply' => '新回覆',
'registered' => '已註冊:',
'registered_x' => '已註冊: {x}',
'last_seen' => '上次上線:',
'last_seen_x' => '上次上線: {x}', // Don't replace {x}
'new_wall_post' => '{x} 在你的塗鴉牆上發文.',
'couldnt_find_that_user' => '找不到使用者.',
'block_user' => '封鎖使用者',
'unblock_user' => '解鎖使用者',
'confirm_block_user' => '你要封鎖這位使用者嗎?如果封鎖了他將會無法傳送私人訊息與在文章標注你.',
'confirm_unblock_user' => '你要解鎖這位使用者嗎?如果解鎖了他將可以傳送私人訊息與在文章標注你.',
'user_blocked' => '使用者封鎖.',
'user_unblocked' => '使用者解鎖.',
'views' => 'Profile Views:',
'private_profile_page' => 'This is a private profile!',
'new_wall_post_reply' => '{x} has replied to your post on {y}\'s profile.', // Don't replace {x} or {y}
'new_wall_post_reply_your_profile' => '{x} has replied to your post on your profile.', // Don't replace {x}
'no_about_fields' => 'This user has not added any about fields yet.',
'reply' => 'Reply',
'discord_username' => 'Discord Username',
// Reports
'invalid_report_content' => '無法建立回報. 請確認你輸入的內容有在 2-1024 字元以內.',
'report_post_content' => '請輸入內容',
'report_created' => '回報建立成功',
// Messaging
'no_messages' => '沒有新訊息',
'no_messages_full' => '你沒有新訊息.',
'view_messages' => '查看訊息',
'1_new_message' => 'You have 1 new message',
'x_new_messages' => '你有 {x} 則新訊息', // Don't replace {x}
'new_message' => '新訊息',
'message_title' => '訊息標題',
'to' => 'To',
'separate_users_with_commas' => '使用「,」區分使用者',
'title_required' => '請輸入標題',
'content_required' => '請輸入內容',
'users_to_required' => '請輸入使用者名稱',
'cant_send_to_self' => '你不能傳訊息給自己!',
'title_min_2' => '標題最低限制 2 字元',
'content_min_2' => '內文最低限制 2 字元',
'title_max_64' => '標題最高限制 64 字元',
'content_max_20480' => '內文最高限制 20480 字元',
'max_pm_10_users' => '最多只能傳給 10位 使用者',
'message_sent_successfully' => '訊息傳送成功',
'participants' => '參與者',
'last_message' => '最後的訊息',
'by' => 'by',
'leave_conversation' => '離開對話',
'confirm_leave' => '你要離開對話嗎?',
'one_or_more_users_blocked' => '你無法傳送私人對話,因為有使用者封鎖你.',
'messages' => 'Messages',
'latest_profile_posts' => 'Latest Profile Posts',
'no_profile_posts' => 'No profile posts.',
/*
* Infractions area
*/
'you_have_been_banned' => '你已被封禁!',
'you_have_received_a_warning' => '你已收到警告!',
'acknowledge' => '確認',
/*
* Hooks
*/
'user_x_has_registered' => '{x} has joined ' . SITE_NAME . '!',
'user_x_has_validated' => '{x} has validated their account!',
];
| NamelessMC/Nameless | custom/languages/Chinese/user.php | PHP | mit | 11,505 |
// Copyright mogemimi. Distributed under the MIT license.
#include "pomdog/experimental/skeletal2d/blendtrees/animation_node.h"
namespace pomdog::skeletal2d {
AnimationNode::~AnimationNode() = default;
} // namespace pomdog::skeletal2d
| mogemimi/pomdog | pomdog/experimental/skeletal2d/blendtrees/animation_node.cpp | C++ | mit | 240 |
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\DICOM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class ContentTime extends AbstractTag
{
protected $Id = '0008,0033';
protected $Name = 'ContentTime';
protected $FullName = 'DICOM::Main';
protected $GroupName = 'DICOM';
protected $g0 = 'DICOM';
protected $g1 = 'DICOM';
protected $g2 = 'Image';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Content Time';
}
| romainneutron/PHPExiftool | lib/PHPExiftool/Driver/Tag/DICOM/ContentTime.php | PHP | mit | 782 |
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { MessagesComponent } from './messages.component';
import { MessageService } from '../message.service';
describe('MessagesComponent', () => {
let component: MessagesComponent;
let fixture: ComponentFixture<MessagesComponent>;
let messageService: MessageService;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [MessagesComponent],
providers: [MessageService]
}).compileComponents();
messageService = TestBed.inject(MessageService);
}));
beforeEach(() => {
fixture = TestBed.createComponent(MessagesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
| mdvorak/resource-router | src/app/messages/messages.component.spec.ts | TypeScript | mit | 833 |
<?php
namespace Noxlogic\PhpotonBundle\Websocket;
class TimeoutException extends \RuntimeException { }
| jaytaph/phpoton_slack | src/Noxlogic/PhpotonBundle/Websocket/TimeoutException.php | PHP | mit | 105 |
/*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015 Neustar Inc.
*
* 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 "EppCommandInfoDomain.hpp"
#include "EppUtil.hpp"
DOM_Element EppCommandInfoDomain::toXML( DOM_Document& doc, const DOMString& tag )
{
DOM_Element elm;
DOM_Element body = EppUtil::createElementNS(doc, "domain", tag);
if( name != null )
{
elm = doc.createElement("name");
elm.appendChild(doc.createTextNode(name));
body.appendChild(elm);
}
return toXMLCommon(doc, tag, body);
}
EppCommandInfoDomain * EppCommandInfoDomain::fromXML( const DOM_Node& root )
{
DOM_NodeList list = root.getChildNodes();
for( unsigned int i = 0; i < list.getLength(); i++ )
{
DOM_Node node = list.item(i);
DOMString name = node.getLocalName();
if( name == null )
{
name = node.getNodeName();
}
if( name == null )
{
continue;
}
// if( name.equals("name") )
if( name.equals("name") || name.equals("domain:name") )
{
DOMString s = EppUtil::getText(node);
return new EppCommandInfoDomain(s);
}
}
return null;
}
| neustar/registrar_epp04toolkit | src/c++/src/epp/core/command/EppCommandInfoDomain.cpp | C++ | mit | 2,259 |
import _plotly_utils.basevalidators
class YValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(self, plotly_name="y", parent_name="bar", **kwargs):
super(YValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
anim=kwargs.pop("anim", True),
edit_type=kwargs.pop("edit_type", "calc+clearAxisTypes"),
role=kwargs.pop("role", "data"),
**kwargs
)
| plotly/python-api | packages/python/plotly/plotly/validators/bar/_y.py | Python | mit | 480 |
// fetch() polyfill for making API calls.
import 'whatwg-fetch';
// Object.assign() is commonly used with React.
// It will use the native implementation if it's present and isn't buggy.
import objectAssign from 'object-assign';
Object.assign = objectAssign;
| ZachMayer35/Radioscope | API/tests/config/polyfills.js | JavaScript | mit | 261 |
///<reference path="./move.ts" />
module GobangOnline {
export enum Color { Empty, Black, White };
export function getOpponentColor(color: Color): Color {
return color == Color.Black ? Color.White : Color.Black;
}
export function buildSquareMatrix(size:number, defaultValue:any) {
var matrix = [];
for (var i = 0; i < size; i++) {
matrix[i] = [];
for (var j = 0; j < size; j++) {
matrix[i][j] = defaultValue;
}
}
return matrix;
}
export function move2position(move: Move): { x: number; y: number } {
return {
x: move.column*(Settings.BOARD_X_END - Settings.BOARD_X_START)/(Settings.BOARD_SIZE-1)+Settings.BOARD_X_START,
y: move.row*(Settings.BOARD_Y_END - Settings.BOARD_Y_START)/(Settings.BOARD_SIZE-1)+Settings.BOARD_Y_START
};
}
export function position2move(position: { x: number; y: number }): Move {
return {
row: Math.round((position.y-Settings.BOARD_Y_START)/((Settings.BOARD_Y_END - Settings.BOARD_Y_START)/(Settings.BOARD_SIZE-1))),
column: Math.round((position.x-Settings.BOARD_X_START)/((Settings.BOARD_X_END - Settings.BOARD_X_START)/(Settings.BOARD_SIZE-1)))
};
}
export class Board {
private table: Color[][];
private moveLog: Move[];
constructor(public size) {
this.table = buildSquareMatrix(size, Color.Empty);
this.moveLog = [];
}
printBoard() {
var rows = [];
for (var i = 0; i < this.table.length; i++) {
var row = "";
for (var j = 0; j < this.table.length; j++) {
switch (this.table[i][j]) {
case Color.Empty: row += "."; break;
case Color.Black: row += "x"; break;
case Color.White: row += "o"; break;
}
}
rows.push(row);
}
return rows;
}
getMoveAt(id) {
return this.moveLog[id];
}
getMoveCount() {
return this.moveLog.length;
}
getLastMove() {
return this.moveLog[this.getMoveCount()-1];
}
colorAt(move: Move): Color {
return this.table[move.row][move.column];
}
setColorAt(move: Move, color: Color): void {
this.table[move.row][move.column] = color;
this.moveLog.push(move);
}
revertLastMove(): void {
var lastMove = this.moveLog.pop();
this.table[lastMove.row][lastMove.column] = Color.Empty;
}
isMoveValid(move: Move): boolean {
return !this.isOutOfBound(move) && this.colorAt(move) == Color.Empty;
}
isOutOfBound(move: Move): boolean {
return move.row < 0
|| move.row >= this.size
|| move.column < 0
|| move.column >= this.size;
}
hasNeighbor(move: Move): boolean {
for (var dx = -1; dx <= 1; dx++) {
for (var dy = -1; dy <= 1; dy++) {
var neighbor: Move = { row: move.row+dy, column: move.column+dx };
if (!(dx == 0 && dy == 0) && !this.isOutOfBound(neighbor) && this.colorAt(neighbor) != Color.Empty) {
return true;
}
}
}
return false;
}
isGameOver(playerColor: Color): boolean {
var run: number;
// check rows
for (var i: number = 0; i < this.size; i++) {
run = 0;
for (var j: number = 0; j < this.size; j++) {
if (this.colorAt({ row: i, column: j }) == playerColor) {
run++;
} else {
run = 0;
}
if (run == 5) {
return true;
}
}
}
// check columns
for (var i: number = 0; i < this.size; i++) {
run = 0;
for (var j: number = 0; j < this.size; j++) {
if (this.colorAt({ row: j, column: i }) == playerColor) {
run++;
} else {
run = 0;
}
if (run == 5) {
return true;
}
}
}
// check right-down diagnals
for (var i: number = 0; i < (this.size-4)*2-1; i++) {
run = 0;
var r: number = Math.max(this.size-5-i, 0);
var c: number = Math.max(i-(this.size-5), 0);
while (r < this.size && c < this.size) {
if (this.colorAt({ row: r, column: c }) == playerColor) {
run++;
} else {
run = 0;
}
if (run == 5) {
return true;
}
r++;
c++;
}
}
// check right-up diagnals
for (var i: number = 0; i < (this.size-4)*2-1; i++) {
run = 0;
var r: number = Math.min(i+4, this.size-1);
var c: number = Math.max(i-(this.size-5), 0);
while (r >= 0 && c < this.size) {
if (this.colorAt({ row: r, column: c }) == playerColor) {
run++;
} else {
run = 0;
}
if (run == 5) {
return true;
}
r--;
c++;
}
}
return false;
}
}
}
| go717franciswang/gobang | board.ts | TypeScript | mit | 4,943 |
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
#define rep(k, a, b) for (int k = (a); k < int(b); k++)
#define rrep(k, a, b) for (int k = (a); k >= int(b); k--)
#define irep(it, xs) for (auto it = xs.begin(); it!=xs.end(); it++)
#define rirep(it, xs) for (auto it = xs.rbegin(); it!=xs.rend(); it++)
#define erep(e, xs) for (auto& e : (xs))
#define rint(x) scanf("%d", &(x))
#define rfloat(x) scanf("%lf", &(x))
typedef long long LL;
typedef pair<int,int> II;
int n,m,b,mod;
int a[501];
int dp[501][501];
int main()
{
cin >> n >> m >> b >> mod;
rep(i, 0, n)
cin >> a[i];
// people, lines, bug
for(int i=0;i!=m;i++)
{
dp[]
}
for(int i=0;i<=m;i++)
{
for(int j=0;j!=b;j++)
{
for(int k=0;k<=m;k++)
{
for(int l=0;l<=b;l++)
{
dp[i][j] += dp[k][k] * dp[n-k][b-l];
}
}
}
}
cout << dp[n][b] << endl;
return 0;
}
| zzh8829/CompetitiveProgramming | Codeforces/544/C.cpp | C++ | mit | 1,315 |
# -*- coding: utf-8 -*-
from .record import (
Metadata,
Record,
)
__all__ = ['Parser']
class Parser:
def __init__(self, store):
self.store = store
def parse_record(self, metadata, line):
factors = line.split('|')
if len(factors) < 7:
return
registry, cc, type_, start, value, dete, status = factors[:7]
if type_ not in ('ipv4', 'ipv6'):
return
return Record(metadata, start, type_, value, cc)
def do(self, fp):
metadata = None
for line in fp:
line = line[:-1]
if line.startswith('#') or line.endswith('summary'):
continue
if metadata is None:
version, registry, serial, records,\
startdate, enddate, utcoffset = line.split('|')[:7]
metadata = Metadata(registry, version, serial)
continue
record = self.parse_record(metadata, line)
if record is None:
continue
self.store.persist(record)
| yosida95/ip2country | ip2country/parser.py | Python | mit | 1,079 |