repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
Sean3Don/inkscape | src/bind/java/org/inkscape/dom/svg/SVGSVGElementImpl.java | 10884 | /**
* This is a simple mechanism to bind Inkscape to Java, and thence
* to all of the nice things that can be layered upon that.
*
* Authors:
* Bob Jamison
*
* Copyright (c) 2007-2008 Inkscape.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Note that these SVG files are implementations of the Java
* interface package found here:
* http://www.w3.org/TR/SVG/java.html
*/
package org.inkscape.dom.svg;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import org.w3c.dom.DOMException;
import org.w3c.dom.svg.*;
import org.w3c.dom.css.CSSStyleDeclaration;
import org.w3c.dom.css.CSSValue;
import org.w3c.dom.css.RGBColor;
import org.w3c.dom.views.DocumentView;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.events.EventException;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.DocumentEvent;
import org.w3c.dom.stylesheets.DocumentStyle;
import org.w3c.dom.stylesheets.StyleSheetList;
public class SVGSVGElementImpl
extends
SVGElementImpl
//SVGTests,
//SVGLangSpace,
//SVGExternalResourcesRequired,
//SVGStylable,
//SVGLocatable,
//SVGFitToViewBox,
//SVGZoomAndPan,
//EventTarget,
//DocumentEvent,
//ViewCSS,
//DocumentCSS
implements org.w3c.dom.svg.SVGSVGElement
{
public SVGSVGElementImpl()
{
imbue(_SVGTests = new SVGTestsImpl());
imbue(_SVGLangSpace = new SVGLangSpaceImpl());
imbue(_SVGExternalResourcesRequired = new SVGExternalResourcesRequiredImpl());
imbue(_SVGStylable = new SVGStylableImpl());
imbue(_SVGLocatable = new SVGLocatableImpl());
imbue(_SVGFitToViewBox = new SVGFitToViewBoxImpl());
imbue(_SVGZoomAndPan = new SVGZoomAndPanImpl());
imbue(_EventTarget = new org.inkscape.dom.events.EventTargetImpl());
imbue(_DocumentEvent = new org.inkscape.dom.events.DocumentEventImpl());
imbue(_ViewCSS = new org.inkscape.dom.css.ViewCSSImpl());
imbue(_DocumentCSS = new org.inkscape.dom.css.DocumentCSSImpl());
}
//from SVGURIReference
private SVGURIReferenceImpl _SVGURIReference;
public SVGAnimatedString getHref()
{ return _SVGURIReference.getHref(); }
//end SVGURIReference
//from SVGTests
private SVGTestsImpl _SVGTests;
public SVGStringList getRequiredFeatures()
{ return _SVGTests.getRequiredFeatures(); }
public SVGStringList getRequiredExtensions()
{ return _SVGTests.getRequiredExtensions(); }
public SVGStringList getSystemLanguage()
{ return _SVGTests.getSystemLanguage(); }
public boolean hasExtension (String extension)
{ return _SVGTests.hasExtension(extension); }
//end SVGTests
//from SVGLangSpace
private SVGLangSpaceImpl _SVGLangSpace;
public String getXMLlang()
{ return _SVGLangSpace.getXMLlang(); }
public void setXMLlang(String xmllang)
throws DOMException
{ _SVGLangSpace.setXMLlang(xmllang); }
public String getXMLspace()
{ return _SVGLangSpace.getXMLspace(); }
public void setXMLspace(String xmlspace)
throws DOMException
{ _SVGLangSpace.setXMLspace(xmlspace); }
//end SVGLangSpace
//from SVGExternalResourcesRequired
private SVGExternalResourcesRequiredImpl _SVGExternalResourcesRequired;
public SVGAnimatedBoolean getExternalResourcesRequired()
{ return _SVGExternalResourcesRequired.getExternalResourcesRequired(); }
//end SVGExternalResourcesRequired
//from SVGStylable
private SVGStylableImpl _SVGStylable;
public SVGAnimatedString getClassName()
{ return _SVGStylable.getClassName(); }
public CSSStyleDeclaration getStyle()
{ return _SVGStylable.getStyle(); }
public CSSValue getPresentationAttribute(String name)
{ return _SVGStylable.getPresentationAttribute(name); }
//end SVGStylable
//from SVGLocatable
private SVGLocatableImpl _SVGLocatable;
public SVGElement getNearestViewportElement()
{ return _SVGLocatable.getNearestViewportElement(); }
public SVGElement getFarthestViewportElement()
{ return _SVGLocatable.getFarthestViewportElement(); }
public SVGRect getBBox()
{ return _SVGLocatable.getBBox(); }
public SVGMatrix getCTM()
{ return _SVGLocatable.getCTM(); }
public SVGMatrix getScreenCTM()
{ return _SVGLocatable.getScreenCTM(); }
public SVGMatrix getTransformToElement (SVGElement element)
throws SVGException
{ return _SVGLocatable.getTransformToElement(element); }
//end SVGLocatable
//from EventTarget
private org.inkscape.dom.events.EventTargetImpl _EventTarget;
public void addEventListener(String type,
EventListener listener,
boolean useCapture)
{ _EventTarget.addEventListener(type, listener, useCapture); }
public void removeEventListener(String type,
EventListener listener,
boolean useCapture)
{ _EventTarget.removeEventListener(type, listener, useCapture); }
public boolean dispatchEvent(Event evt)
throws EventException
{ return _EventTarget.dispatchEvent(evt); }
public void addEventListenerNS(String namespaceURI,
String type,
EventListener listener,
boolean useCapture,
Object evtGroup)
{ _EventTarget.addEventListenerNS(namespaceURI, type, listener, useCapture, evtGroup); }
public void removeEventListenerNS(String namespaceURI,
String type,
EventListener listener,
boolean useCapture)
{ _EventTarget.removeEventListenerNS(namespaceURI, type, listener, useCapture); }
public boolean willTriggerNS(String namespaceURI,
String type)
{ return _EventTarget.willTriggerNS(namespaceURI, type); }
public boolean hasEventListenerNS(String namespaceURI,
String type)
{ return _EventTarget.hasEventListenerNS(namespaceURI, type); }
//end EventTarget
//from SVGFitToViewBox
SVGFitToViewBoxImpl _SVGFitToViewBox;
public SVGAnimatedRect getViewBox()
{ return _SVGFitToViewBox.getViewBox(); }
public SVGAnimatedPreserveAspectRatio getPreserveAspectRatio()
{ return _SVGFitToViewBox.getPreserveAspectRatio(); }
//end SVGFitToViewBox
//from SVGZoomAndPan
SVGZoomAndPanImpl _SVGZoomAndPan;
public short getZoomAndPan()
{ return _SVGZoomAndPan.getZoomAndPan(); }
public void setZoomAndPan(short zoomAndPan) throws DOMException
{ _SVGZoomAndPan.setZoomAndPan(zoomAndPan); }
//end SVGZoomAndPan
//from DocumentEvent
org.inkscape.dom.events.DocumentEventImpl _DocumentEvent;
public Event createEvent(String eventType) throws DOMException
{ return _DocumentEvent.createEvent(eventType); }
public boolean canDispatch(String namespaceURI, String type)
{ return _DocumentEvent.canDispatch(namespaceURI, type); }
//end DocumentEvent
//from ViewCSS
org.inkscape.dom.css.ViewCSSImpl _ViewCSS;
public CSSStyleDeclaration getComputedStyle(Element elt, String pseudoElt)
{ return _ViewCSS.getComputedStyle(elt, pseudoElt); }
//end ViewCSS
//from AbstractView (from ViewCSS)
public DocumentView getDocument()
{ return _ViewCSS.getDocument(); }
//end AbstractView
//from DocumentCSS
org.inkscape.dom.css.DocumentCSSImpl _DocumentCSS;
public CSSStyleDeclaration getOverrideStyle(Element elt, String pseudoElt)
{ return _DocumentCSS.getOverrideStyle(elt, pseudoElt); }
//end DocumentCSS
//from DocumentStyle (from DocumentCSS)
public StyleSheetList getStyleSheets()
{ return _DocumentCSS.getStyleSheets(); }
//end DocumentStyle
public native SVGAnimatedLength getX( );
public native SVGAnimatedLength getY( );
public native SVGAnimatedLength getWidth( );
public native SVGAnimatedLength getHeight( );
public native String getContentScriptType( );
public native void setContentScriptType( String contentScriptType )
throws DOMException;
public native String getContentStyleType( );
public native void setContentStyleType( String contentStyleType )
throws DOMException;
public native SVGRect getViewport( );
public native float getPixelUnitToMillimeterX( );
public native float getPixelUnitToMillimeterY( );
public native float getScreenPixelToMillimeterX( );
public native float getScreenPixelToMillimeterY( );
public native boolean getUseCurrentView( );
public native void setUseCurrentView( boolean useCurrentView )
throws DOMException;
public native SVGViewSpec getCurrentView( );
public native float getCurrentScale( );
public native void setCurrentScale( float currentScale )
throws DOMException;
public native SVGPoint getCurrentTranslate( );
public native int suspendRedraw ( int max_wait_milliseconds );
public native void unsuspendRedraw ( int suspend_handle_id )
throws DOMException;
public native void unsuspendRedrawAll ( );
public native void forceRedraw ( );
public native void pauseAnimations ( );
public native void unpauseAnimations ( );
public native boolean animationsPaused ( );
public native float getCurrentTime ( );
public native void setCurrentTime ( float seconds );
public native NodeList getIntersectionList ( SVGRect rect, SVGElement referenceElement );
public native NodeList getEnclosureList ( SVGRect rect, SVGElement referenceElement );
public native boolean checkIntersection ( SVGElement element, SVGRect rect );
public native boolean checkEnclosure ( SVGElement element, SVGRect rect );
public native void deselectAll ( );
public native SVGNumber createSVGNumber ( );
public native SVGLength createSVGLength ( );
public native SVGAngle createSVGAngle ( );
public native SVGPoint createSVGPoint ( );
public native SVGMatrix createSVGMatrix ( );
public native SVGRect createSVGRect ( );
public native SVGTransform createSVGTransform ( );
public native SVGTransform createSVGTransformFromMatrix ( SVGMatrix matrix );
public native Element getElementById ( String elementId );
}
| gpl-2.0 |
sabel83/metashell | 3rd/templight/clang/test/CodeGenCXX/x86_64-arguments-avx.cpp | 1206 | // RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm -o - %s -target-feature +avx | FileCheck %s
namespace test1 {
typedef double __m256d __attribute__((__vector_size__(32)));
class PR22753 {
public:
__m256d data;
};
// CHECK: define{{.*}} <4 x double> @_ZN5test14testENS_7PR22753E(<4 x double>
PR22753 test(PR22753 x) {
return x;
}
}
namespace test2 {
typedef double __m128d __attribute__((__vector_size__(16)));
typedef float __m128 __attribute__((__vector_size__(16)));
typedef double __m256d __attribute__((__vector_size__(32)));
typedef float __m256 __attribute__((__vector_size__(32)));
union U1 {
__m128 v1;
__m128d v2;
};
union UU1 {
union U1;
__m128d v3;
};
// CHECK: define{{.*}} <2 x double> @_ZN5test27PR23082ENS_3UU1E(<2 x double>
UU1 PR23082(UU1 x) {
return x;
}
union U2 {
__m256 v1;
__m256d v2;
};
union UU2 {
union U2;
__m256d v3;
};
// CHECK: define{{.*}} <4 x double> @_ZN5test27PR23082ENS_3UU2E(<4 x double>
UU2 PR23082(UU2 x) {
return x;
}
}
namespace test3 {
union U {
__attribute__((__vector_size__(32))) float f1;
int f2;
};
// CHECK: define{{.*}} i32 @_ZN5test31fENS_1UE({{.*}}* byval({{.*}}) align 32
int f(U u) { return u.f2; }
}
| gpl-3.0 |
MTK6580/walkie-talkie | ALPS.L1.MP6.V2_HEXING6580_WE_L/alps/cts/tools/vm-tests-tf/src/dot/junit/opcodes/shl_int_2addr/Test_shl_int_2addr.java | 3084 | package dot.junit.opcodes.shl_int_2addr;
import dot.junit.DxTestCase;
import dot.junit.DxUtil;
import dot.junit.opcodes.shl_int_2addr.d.T_shl_int_2addr_1;
import dot.junit.opcodes.shl_int_2addr.d.T_shl_int_2addr_6;
public class Test_shl_int_2addr extends DxTestCase {
/**
* @title 15 << 1
*/
public void testN1() {
T_shl_int_2addr_1 t = new T_shl_int_2addr_1();
assertEquals(30, t.run(15, 1));
}
/**
* @title 33 << 2
*/
public void testN2() {
T_shl_int_2addr_1 t = new T_shl_int_2addr_1();
assertEquals(132, t.run(33, 2));
}
/**
* @title -15 << 1
*/
public void testN3() {
T_shl_int_2addr_1 t = new T_shl_int_2addr_1();
assertEquals(-30, t.run(-15, 1));
}
/**
* @title Arguments = 1 & -1
*/
public void testN4() {
T_shl_int_2addr_1 t = new T_shl_int_2addr_1();
assertEquals(0x80000000, t.run(1, -1));
}
/**
* @title Verify that shift distance is actually in range 0 to 32.
*/
public void testN5() {
T_shl_int_2addr_1 t = new T_shl_int_2addr_1();
assertEquals(66, t.run(33, 33));
}
/**
* @title Arguments = 0 & -1
*/
public void testB1() {
T_shl_int_2addr_1 t = new T_shl_int_2addr_1();
assertEquals(0, t.run(0, -1));
}
/**
* @title Arguments = Integer.MAX_VALUE & 1
*/
public void testB2() {
T_shl_int_2addr_1 t = new T_shl_int_2addr_1();
assertEquals(0xfffffffe, t.run(Integer.MAX_VALUE, 1));
}
/**
* @title Arguments = Integer.MIN_VALUE & 1
*/
public void testB3() {
T_shl_int_2addr_1 t = new T_shl_int_2addr_1();
assertEquals(0, t.run(Integer.MIN_VALUE, 1));
}
/**
* @title Arguments = 1 & 0
*/
public void testB4() {
T_shl_int_2addr_1 t = new T_shl_int_2addr_1();
assertEquals(1, t.run(1, 0));
}
/**
* @constraint A23
* @title number of registers
*/
public void testVFE1() {
load("dot.junit.opcodes.shl_int_2addr.d.T_shl_int_2addr_2", VerifyError.class);
}
/**
* @constraint B1
* @title types of arguments - double & int
*/
public void testVFE2() {
load("dot.junit.opcodes.shl_int_2addr.d.T_shl_int_2addr_3", VerifyError.class);
}
/**
* @constraint B1
* @title types of arguments - long & int
*/
public void testVFE3() {
load("dot.junit.opcodes.shl_int_2addr.d.T_shl_int_2addr_4", VerifyError.class);
}
/**
* @constraint B1
* @title types of arguments - reference & int
*/
public void testVFE4() {
load("dot.junit.opcodes.shl_int_2addr.d.T_shl_int_2addr_5", VerifyError.class);
}
/**
* @constraint B1
* @title Types of arguments - float, float. The verifier checks that ints
* and floats are not used interchangeably.
*/
public void testVFE5() {
load("dot.junit.opcodes.shl_int_2addr.d.T_shl_int_2addr_6", VerifyError.class);
}
}
| gpl-3.0 |
sydneyjd/supertux | src/object/block.cpp | 4668 | // SuperTux
// Copyright (C) 2006 Matthias Braun <matze@braunis.de>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "object/block.hpp"
#include "audio/sound_manager.hpp"
#include "badguy/badguy.hpp"
#include "object/broken_brick.hpp"
#include "object/coin.hpp"
#include "object/flower.hpp"
#include "object/growup.hpp"
#include "object/player.hpp"
#include "object/portable.hpp"
#include "supertux/constants.hpp"
#include "supertux/sector.hpp"
static const float BOUNCY_BRICK_MAX_OFFSET = 8;
static const float BOUNCY_BRICK_SPEED = 90;
static const float BUMP_ROTATION_ANGLE = 10;
Block::Block(SpritePtr newsprite) :
sprite(newsprite),
bouncing(false),
breaking(false),
bounce_dir(0),
bounce_offset(0),
original_y(-1)
{
bbox.set_size(32, 32.1f);
set_group(COLGROUP_STATIC);
SoundManager::current()->preload("sounds/upgrade.wav");
SoundManager::current()->preload("sounds/brick.wav");
}
Block::~Block()
{
}
HitResponse
Block::collision(GameObject& other, const CollisionHit& )
{
Player* player = dynamic_cast<Player*> (&other);
if(player) {
if(player->get_bbox().get_top() > bbox.get_bottom() - SHIFT_DELTA) {
hit(*player);
}
}
// only interact with other objects if...
// 1) we are bouncing
// 2) the object is not portable (either never or not currently)
// 3) the object is being hit from below (baguys don't get killed for activating boxes)
Portable* portable = dynamic_cast<Portable*> (&other);
MovingObject* moving_object = dynamic_cast<MovingObject*> (&other);
bool is_portable = ((portable != 0) && portable->is_portable());
bool hit_mo_from_below = ((moving_object == 0) || (moving_object->get_bbox().get_bottom() < (bbox.get_top() + SHIFT_DELTA)));
if(bouncing && !is_portable && hit_mo_from_below) {
// Badguys get killed
BadGuy* badguy = dynamic_cast<BadGuy*> (&other);
if(badguy) {
badguy->kill_fall();
}
// Coins get collected
Coin* coin = dynamic_cast<Coin*> (&other);
if(coin) {
coin->collect();
}
//Eggs get jumped
GrowUp* growup = dynamic_cast<GrowUp*> (&other);
if(growup) {
growup->do_jump();
}
}
return FORCE_MOVE;
}
void
Block::update(float elapsed_time)
{
if(!bouncing)
return;
float offset = original_y - get_pos().y;
if(offset > BOUNCY_BRICK_MAX_OFFSET) {
bounce_dir = BOUNCY_BRICK_SPEED;
movement = Vector(0, bounce_dir * elapsed_time);
if(breaking){
break_me();
}
} else if(offset < BOUNCY_BRICK_SPEED * elapsed_time && bounce_dir > 0) {
movement = Vector(0, offset);
bounce_dir = 0;
bouncing = false;
sprite->set_angle(0);
} else {
movement = Vector(0, bounce_dir * elapsed_time);
}
}
void
Block::draw(DrawingContext& context)
{
sprite->draw(context, get_pos(), LAYER_OBJECTS+1);
}
void
Block::start_bounce(GameObject* hitter)
{
if(original_y == -1){
original_y = bbox.p1.y;
}
bouncing = true;
bounce_dir = -BOUNCY_BRICK_SPEED;
bounce_offset = 0;
MovingObject* hitter_mo = dynamic_cast<MovingObject*>(hitter);
if (hitter_mo) {
float center_of_hitter = hitter_mo->get_bbox().get_middle().x;
float offset = (bbox.get_middle().x - center_of_hitter)*2 / bbox.get_width();
sprite->set_angle(BUMP_ROTATION_ANGLE*offset);
}
}
void
Block::start_break(GameObject* hitter)
{
start_bounce(hitter);
breaking = true;
}
void
Block::break_me()
{
Sector* sector = Sector::current();
sector->add_object(
std::make_shared<BrokenBrick>(sprite->clone(), get_pos(), Vector(-100, -400)));
sector->add_object(
std::make_shared<BrokenBrick>(sprite->clone(), get_pos() + Vector(0, 16),
Vector(-150, -300)));
sector->add_object(
std::make_shared<BrokenBrick>(sprite->clone(), get_pos() + Vector(16, 0),
Vector(100, -400)));
sector->add_object(
std::make_shared<BrokenBrick>(sprite->clone(), get_pos() + Vector(16, 16),
Vector(150, -300)));
remove_me();
}
/* EOF */
| gpl-3.0 |
BigBoss424/a-zplumbing | Magento-CE-2/vendor/magento/module-sales/Test/Unit/Model/Order/Pdf/Config/ReaderTest.php | 3355 | <?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Test\Unit\Model\Order\Pdf\Config;
class ReaderTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Magento\Sales\Model\Order\Pdf\Config\Reader
*/
protected $_model;
/**
* @var \Magento\Framework\Config\FileResolverInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $_fileResolverMock;
/**
* @var \Magento\Sales\Model\Order\Pdf\Config\Converter|\PHPUnit_Framework_MockObject_MockObject
*/
protected $_converter;
/**
* @var \Magento\Sales\Model\Order\Pdf\Config\SchemaLocator
*/
protected $_schemaLocator;
/**
* @var \Magento\Framework\Config\ValidationStateInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $_validationState;
protected function setUp()
{
$this->_fileResolverMock = $this->getMock('Magento\Framework\Config\FileResolverInterface');
$this->_fileResolverMock->expects(
$this->once()
)->method(
'get'
)->with(
'pdf.xml',
'scope'
)->will(
$this->returnValue(
[
file_get_contents(__DIR__ . '/_files/pdf_one.xml'),
file_get_contents(__DIR__ . '/_files/pdf_two.xml'),
]
)
);
$this->_converter = $this->getMock('Magento\Sales\Model\Order\Pdf\Config\Converter', ['convert']);
$moduleReader = $this->getMock(
'Magento\Framework\Module\Dir\Reader',
['getModuleDir'],
[],
'',
false
);
$moduleReader->expects(
$this->once()
)->method(
'getModuleDir'
)->with(
'etc',
'Magento_Sales'
)->will(
$this->returnValue('stub')
);
$this->_schemaLocator = new \Magento\Sales\Model\Order\Pdf\Config\SchemaLocator($moduleReader);
$this->_validationState = $this->getMock('Magento\Framework\Config\ValidationStateInterface');
$this->_validationState->expects($this->any())
->method('isValidationRequired')
->willReturn(false);
$this->_model = new \Magento\Sales\Model\Order\Pdf\Config\Reader(
$this->_fileResolverMock,
$this->_converter,
$this->_schemaLocator,
$this->_validationState,
'pdf.xml'
);
}
public function testRead()
{
$expectedResult = new \stdClass();
$constraint = function (\DOMDOcument $actual) {
try {
$expected = __DIR__ . '/_files/pdf_merged.xml';
\PHPUnit_Framework_Assert::assertXmlStringEqualsXmlFile($expected, $actual->saveXML());
return true;
} catch (\PHPUnit_Framework_AssertionFailedError $e) {
return false;
}
};
$this->_converter->expects(
$this->once()
)->method(
'convert'
)->with(
$this->callback($constraint)
)->will(
$this->returnValue($expectedResult)
);
$this->assertSame($expectedResult, $this->_model->read('scope'));
}
}
| gpl-3.0 |
thermesmarins/tmsm-woocommerce-vouchers | includes/advanced-custom-fields/assets/js/acf-input.js | 227101 | (function($, undefined){
// vars
var storage = [];
/**
* acf.Field
*
* description
*
* @date 23/3/18
* @since 5.6.9
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.Field = acf.Model.extend({
// field type
type: '',
// class used to avoid nested event triggers
eventScope: '.acf-field',
// initialize events on 'ready'
wait: 'ready',
/**
* setup
*
* Called during the constructor function to setup this field ready for initialization
*
* @date 8/5/18
* @since 5.6.9
*
* @param jQuery $field The field element.
* @return void
*/
setup: function( $field ){
// set $el
this.$el = $field;
// inherit $field data
this.inherit( $field );
// inherit controll data
this.inherit( this.$control() );
},
/**
* val
*
* Sets or returns the field's value
*
* @date 8/5/18
* @since 5.6.9
*
* @param mixed val Optional. The value to set
* @return mixed
*/
val: function( val ){
// Set.
if( val !== undefined ) {
return this.setValue( val );
// Get.
} else {
return this.prop('disabled') ? null : this.getValue();
}
},
/**
* getValue
*
* returns the field's value
*
* @date 8/5/18
* @since 5.6.9
*
* @param void
* @return mixed
*/
getValue: function(){
return this.$input().val();
},
/**
* setValue
*
* sets the field's value and returns true if changed
*
* @date 8/5/18
* @since 5.6.9
*
* @param mixed val
* @return boolean. True if changed.
*/
setValue: function( val ){
return acf.val( this.$input(), val );
},
/**
* __
*
* i18n helper to be removed
*
* @date 8/5/18
* @since 5.6.9
*
* @param type $var Description. Default.
* @return type Description.
*/
__: function( string ){
return acf._e( this.type, string );
},
/**
* $control
*
* returns the control jQuery element used for inheriting data. Uses this.control setting.
*
* @date 8/5/18
* @since 5.6.9
*
* @param void
* @return jQuery
*/
$control: function(){
return false;
},
/**
* $input
*
* returns the input jQuery element used for saving values. Uses this.input setting.
*
* @date 8/5/18
* @since 5.6.9
*
* @param void
* @return jQuery
*/
$input: function(){
return this.$('[name]:first');
},
/**
* $inputWrap
*
* description
*
* @date 12/5/18
* @since 5.6.9
*
* @param type $var Description. Default.
* @return type Description.
*/
$inputWrap: function(){
return this.$('.acf-input:first');
},
/**
* $inputWrap
*
* description
*
* @date 12/5/18
* @since 5.6.9
*
* @param type $var Description. Default.
* @return type Description.
*/
$labelWrap: function(){
return this.$('.acf-label:first');
},
/**
* getInputName
*
* Returns the field's input name
*
* @date 8/5/18
* @since 5.6.9
*
* @param void
* @return string
*/
getInputName: function(){
return this.$input().attr('name') || '';
},
/**
* parent
*
* returns the field's parent field or false on failure.
*
* @date 8/5/18
* @since 5.6.9
*
* @param void
* @return object|false
*/
parent: function() {
// vars
var parents = this.parents();
// return
return parents.length ? parents[0] : false;
},
/**
* parents
*
* description
*
* @date 9/7/18
* @since 5.6.9
*
* @param type $var Description. Default.
* @return type Description.
*/
parents: function(){
// vars
var $parents = this.$el.parents('.acf-field');
// convert
var parents = acf.getFields( $parents );
// return
return parents;
},
show: function( lockKey, context ){
// show field and store result
var changed = acf.show( this.$el, lockKey );
// do action if visibility has changed
if( changed ) {
this.prop('hidden', false);
acf.doAction('show_field', this, context);
}
// return
return changed;
},
hide: function( lockKey, context ){
// hide field and store result
var changed = acf.hide( this.$el, lockKey );
// do action if visibility has changed
if( changed ) {
this.prop('hidden', true);
acf.doAction('hide_field', this, context);
}
// return
return changed;
},
enable: function( lockKey, context ){
// enable field and store result
var changed = acf.enable( this.$el, lockKey );
// do action if disabled has changed
if( changed ) {
this.prop('disabled', false);
acf.doAction('enable_field', this, context);
}
// return
return changed;
},
disable: function( lockKey, context ){
// disabled field and store result
var changed = acf.disable( this.$el, lockKey );
// do action if disabled has changed
if( changed ) {
this.prop('disabled', true);
acf.doAction('disable_field', this, context);
}
// return
return changed;
},
showEnable: function( lockKey, context ){
// enable
this.enable.apply(this, arguments);
// show and return true if changed
return this.show.apply(this, arguments);
},
hideDisable: function( lockKey, context ){
// disable
this.disable.apply(this, arguments);
// hide and return true if changed
return this.hide.apply(this, arguments);
},
showNotice: function( props ){
// ensure object
if( typeof props !== 'object' ) {
props = { text: props };
}
// remove old notice
if( this.notice ) {
this.notice.remove();
}
// create new notice
props.target = this.$inputWrap();
this.notice = acf.newNotice( props );
},
removeNotice: function( timeout ){
if( this.notice ) {
this.notice.away( timeout || 0 );
this.notice = false;
}
},
showError: function( message ){
// add class
this.$el.addClass('acf-error');
// add message
if( message !== undefined ) {
this.showNotice({
text: message,
type: 'error',
dismiss: false
});
}
// action
acf.doAction('invalid_field', this);
// add event
this.$el.one('focus change', 'input, select, textarea', $.proxy( this.removeError, this ));
},
removeError: function(){
// remove class
this.$el.removeClass('acf-error');
// remove notice
this.removeNotice( 250 );
// action
acf.doAction('valid_field', this);
},
trigger: function( name, args, bubbles ){
// allow some events to bubble
if( name == 'invalidField' ) {
bubbles = true;
}
// return
return acf.Model.prototype.trigger.apply(this, [name, args, bubbles]);
},
});
/**
* newField
*
* description
*
* @date 14/12/17
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.newField = function( $field ){
// vars
var type = $field.data('type');
var mid = modelId( type );
var model = acf.models[ mid ] || acf.Field;
// instantiate
var field = new model( $field );
// actions
acf.doAction('new_field', field);
// return
return field;
};
/**
* mid
*
* Calculates the model ID for a field type
*
* @date 15/12/17
* @since 5.6.5
*
* @param string type
* @return string
*/
var modelId = function( type ) {
return acf.strPascalCase( type || '' ) + 'Field';
};
/**
* registerFieldType
*
* description
*
* @date 14/12/17
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.registerFieldType = function( model ){
// vars
var proto = model.prototype;
var type = proto.type;
var mid = modelId( type );
// store model
acf.models[ mid ] = model;
// store reference
storage.push( type );
};
/**
* acf.getFieldType
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.getFieldType = function( type ){
var mid = modelId( type );
return acf.models[ mid ] || false;
}
/**
* acf.getFieldTypes
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.getFieldTypes = function( args ){
// defaults
args = acf.parseArgs(args, {
category: '',
// hasValue: true
});
// clonse available types
var types = [];
// loop
storage.map(function( type ){
// vars
var model = acf.getFieldType(type);
var proto = model.prototype;
// check operator
if( args.category && proto.category !== args.category ) {
return;
}
// append
types.push( model );
});
// return
return types;
};
})(jQuery);
(function($, undefined){
/**
* findFields
*
* Returns a jQuery selection object of acf fields.
*
* @date 14/12/17
* @since 5.6.5
*
* @param object $args {
* Optional. Arguments to find fields.
*
* @type string key The field's key (data-attribute).
* @type string name The field's name (data-attribute).
* @type string type The field's type (data-attribute).
* @type string is jQuery selector to compare against.
* @type jQuery parent jQuery element to search within.
* @type jQuery sibling jQuery element to search alongside.
* @type limit int The number of fields to find.
* @type suppressFilters bool Whether to allow filters to add/remove results. Default behaviour will ignore clone fields.
* }
* @return jQuery
*/
acf.findFields = function( args ){
// vars
var selector = '.acf-field';
var $fields = false;
// args
args = acf.parseArgs(args, {
key: '',
name: '',
type: '',
is: '',
parent: false,
sibling: false,
limit: false,
visible: false,
suppressFilters: false,
});
// filter args
if( !args.suppressFilters ) {
args = acf.applyFilters('find_fields_args', args);
}
// key
if( args.key ) {
selector += '[data-key="' + args.key + '"]';
}
// type
if( args.type ) {
selector += '[data-type="' + args.type + '"]';
}
// name
if( args.name ) {
selector += '[data-name="' + args.name + '"]';
}
// is
if( args.is ) {
selector += args.is;
}
// visibility
if( args.visible ) {
selector += ':visible';
}
// query
if( args.parent ) {
$fields = args.parent.find( selector );
} else if( args.sibling ) {
$fields = args.sibling.siblings( selector );
} else {
$fields = $( selector );
}
// filter
if( !args.suppressFilters ) {
$fields = $fields.not('.acf-clone .acf-field');
$fields = acf.applyFilters('find_fields', $fields);
}
// limit
if( args.limit ) {
$fields = $fields.slice( 0, args.limit );
}
// return
return $fields;
};
/**
* findField
*
* Finds a specific field with jQuery
*
* @date 14/12/17
* @since 5.6.5
*
* @param string key The field's key.
* @param jQuery $parent jQuery element to search within.
* @return jQuery
*/
acf.findField = function( key, $parent ){
return acf.findFields({
key: key,
limit: 1,
parent: $parent,
suppressFilters: true
});
};
/**
* getField
*
* Returns a field instance
*
* @date 14/12/17
* @since 5.6.5
*
* @param jQuery|string $field jQuery element or field key.
* @return object
*/
acf.getField = function( $field ){
// allow jQuery
if( $field instanceof jQuery ) {
// find fields
} else {
$field = acf.findField( $field );
}
// instantiate
var field = $field.data('acf');
if( !field ) {
field = acf.newField( $field );
}
// return
return field;
};
/**
* getFields
*
* Returns multiple field instances
*
* @date 14/12/17
* @since 5.6.5
*
* @param jQuery|object $fields jQuery elements or query args.
* @return array
*/
acf.getFields = function( $fields ){
// allow jQuery
if( $fields instanceof jQuery ) {
// find fields
} else {
$fields = acf.findFields( $fields );
}
// loop
var fields = [];
$fields.each(function(){
var field = acf.getField( $(this) );
fields.push( field );
});
// return
return fields;
};
/**
* findClosestField
*
* Returns the closest jQuery field element
*
* @date 9/4/18
* @since 5.6.9
*
* @param jQuery $el
* @return jQuery
*/
acf.findClosestField = function( $el ){
return $el.closest('.acf-field');
};
/**
* getClosestField
*
* Returns the closest field instance
*
* @date 22/1/18
* @since 5.6.5
*
* @param jQuery $el
* @return object
*/
acf.getClosestField = function( $el ){
var $field = acf.findClosestField( $el );
return this.getField( $field );
};
/**
* addGlobalFieldAction
*
* Sets up callback logic for global field actions
*
* @date 15/6/18
* @since 5.6.9
*
* @param string action
* @return void
*/
var addGlobalFieldAction = function( action ){
// vars
var globalAction = action;
var pluralAction = action + '_fields'; // ready_fields
var singleAction = action + '_field'; // ready_field
// global action
var globalCallback = function( $el /*, arg1, arg2, etc*/ ){
//console.log( action, arguments );
// get args [$el, ...]
var args = acf.arrayArgs( arguments );
var extraArgs = args.slice(1);
// find fields
var fields = acf.getFields({ parent: $el });
// check
if( fields.length ) {
// pluralAction
var pluralArgs = [ pluralAction, fields ].concat( extraArgs );
acf.doAction.apply(null, pluralArgs);
}
};
// plural action
var pluralCallback = function( fields /*, arg1, arg2, etc*/ ){
//console.log( pluralAction, arguments );
// get args [fields, ...]
var args = acf.arrayArgs( arguments );
var extraArgs = args.slice(1);
// loop
fields.map(function( field, i ){
//setTimeout(function(){
// singleAction
var singleArgs = [ singleAction, field ].concat( extraArgs );
acf.doAction.apply(null, singleArgs);
//}, i * 100);
});
};
// add actions
acf.addAction(globalAction, globalCallback);
acf.addAction(pluralAction, pluralCallback);
// also add single action
addSingleFieldAction( action );
}
/**
* addSingleFieldAction
*
* Sets up callback logic for single field actions
*
* @date 15/6/18
* @since 5.6.9
*
* @param string action
* @return void
*/
var addSingleFieldAction = function( action ){
// vars
var singleAction = action + '_field'; // ready_field
var singleEvent = action + 'Field'; // readyField
// single action
var singleCallback = function( field /*, arg1, arg2, etc*/ ){
//console.log( singleAction, arguments );
// get args [field, ...]
var args = acf.arrayArgs( arguments );
var extraArgs = args.slice(1);
// action variations (ready_field/type=image)
var variations = ['type', 'name', 'key'];
variations.map(function( variation ){
// vars
var prefix = '/' + variation + '=' + field.get(variation);
// singleAction
args = [ singleAction + prefix , field ].concat( extraArgs );
acf.doAction.apply(null, args);
});
// event
if( singleFieldEvents.indexOf(action) > -1 ) {
field.trigger(singleEvent, extraArgs);
}
};
// add actions
acf.addAction(singleAction, singleCallback);
}
// vars
var globalFieldActions = [ 'prepare', 'ready', 'load', 'append', 'remove', 'unmount', 'remount', 'sortstart', 'sortstop', 'show', 'hide', 'unload' ];
var singleFieldActions = [ 'valid', 'invalid', 'enable', 'disable', 'new', 'duplicate' ];
var singleFieldEvents = [ 'remove', 'unmount', 'remount', 'sortstart', 'sortstop', 'show', 'hide', 'unload', 'valid', 'invalid', 'enable', 'disable', 'duplicate' ];
// add
globalFieldActions.map( addGlobalFieldAction );
singleFieldActions.map( addSingleFieldAction );
/**
* fieldsEventManager
*
* Manages field actions and events
*
* @date 15/12/17
* @since 5.6.5
*
* @param void
* @param void
*/
var fieldsEventManager = new acf.Model({
id: 'fieldsEventManager',
events: {
'click .acf-field a[href="#"]': 'onClick',
'change .acf-field': 'onChange'
},
onClick: function( e ){
// prevent default of any link with an href of #
e.preventDefault();
},
onChange: function(){
// preview hack allows post to save with no title or content
$('#_acf_changed').val(1);
}
});
var duplicateFieldsManager = new acf.Model({
id: 'duplicateFieldsManager',
actions: {
'duplicate': 'onDuplicate',
'duplicate_fields': 'onDuplicateFields',
},
onDuplicate: function( $el, $el2 ){
var fields = acf.getFields({ parent: $el });
if( fields.length ) {
var $fields = acf.findFields({ parent: $el2 });
acf.doAction( 'duplicate_fields', fields, $fields );
}
},
onDuplicateFields: function( fields, duplicates ){
fields.map(function( field, i ){
acf.doAction( 'duplicate_field', field, $(duplicates[i]) );
});
}
});
})(jQuery);
(function($, undefined){
var i = 0;
var Field = acf.Field.extend({
type: 'accordion',
wait: '',
$control: function(){
return this.$('.acf-fields:first');
},
initialize: function(){
// Bail early if this is a duplicate of an existing initialized accordion.
if( this.$el.hasClass('acf-accordion') ) {
return;
}
// bail early if is cell
if( this.$el.is('td') ) return;
// enpoint
if( this.get('endpoint') ) {
return this.remove();
}
// vars
var $field = this.$el;
var $label = this.$labelWrap()
var $input = this.$inputWrap();
var $wrap = this.$control();
var $instructions = $input.children('.description');
// force description into label
if( $instructions.length ) {
$label.append( $instructions );
}
// table
if( this.$el.is('tr') ) {
// vars
var $table = this.$el.closest('table');
var $newLabel = $('<div class="acf-accordion-title"/>');
var $newInput = $('<div class="acf-accordion-content"/>');
var $newTable = $('<table class="' + $table.attr('class') + '"/>');
var $newWrap = $('<tbody/>');
// dom
$newLabel.append( $label.html() );
$newTable.append( $newWrap );
$newInput.append( $newTable );
$input.append( $newLabel );
$input.append( $newInput );
// modify
$label.remove();
$wrap.remove();
$input.attr('colspan', 2);
// update vars
$label = $newLabel;
$input = $newInput;
$wrap = $newWrap;
}
// add classes
$field.addClass('acf-accordion');
$label.addClass('acf-accordion-title');
$input.addClass('acf-accordion-content');
// index
i++;
// multi-expand
if( this.get('multi_expand') ) {
$field.attr('multi-expand', 1);
}
// open
var order = acf.getPreference('this.accordions') || [];
if( order[i-1] !== undefined ) {
this.set('open', order[i-1]);
}
if( this.get('open') ) {
$field.addClass('-open');
$input.css('display', 'block'); // needed for accordion to close smoothly
}
// add icon
$label.prepend( accordionManager.iconHtml({ open: this.get('open') }) );
// classes
// - remove 'inside' which is a #poststuff WP class
var $parent = $field.parent();
$wrap.addClass( $parent.hasClass('-left') ? '-left' : '' );
$wrap.addClass( $parent.hasClass('-clear') ? '-clear' : '' );
// append
$wrap.append( $field.nextUntil('.acf-field-accordion', '.acf-field') );
// clean up
$wrap.removeAttr('data-open data-multi_expand data-endpoint');
},
});
acf.registerFieldType( Field );
/**
* accordionManager
*
* Events manager for the acf accordion
*
* @date 14/2/18
* @since 5.6.9
*
* @param void
* @return void
*/
var accordionManager = new acf.Model({
actions: {
'unload': 'onUnload'
},
events: {
'click .acf-accordion-title': 'onClick',
'invalidField .acf-accordion': 'onInvalidField'
},
isOpen: function( $el ) {
return $el.hasClass('-open');
},
toggle: function( $el ){
if( this.isOpen($el) ) {
this.close( $el );
} else {
this.open( $el );
}
},
iconHtml: function( props ){
// Use SVG inside Gutenberg editor.
if( acf.isGutenberg() ) {
if( props.open ) {
return '<svg class="acf-accordion-icon" width="24px" height="24px" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" role="img" aria-hidden="true" focusable="false"><g><path fill="none" d="M0,0h24v24H0V0z"></path></g><g><path d="M12,8l-6,6l1.41,1.41L12,10.83l4.59,4.58L18,14L12,8z"></path></g></svg>';
} else {
return '<svg class="acf-accordion-icon" width="24px" height="24px" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" role="img" aria-hidden="true" focusable="false"><g><path fill="none" d="M0,0h24v24H0V0z"></path></g><g><path d="M7.41,8.59L12,13.17l4.59-4.58L18,10l-6,6l-6-6L7.41,8.59z"></path></g></svg>';
}
} else {
if( props.open ) {
return '<i class="acf-accordion-icon dashicons dashicons-arrow-down"></i>';
} else {
return '<i class="acf-accordion-icon dashicons dashicons-arrow-right"></i>';
}
}
},
open: function( $el ){
var duration = acf.isGutenberg() ? 0 : 300;
// open
$el.find('.acf-accordion-content:first').slideDown( duration ).css('display', 'block');
$el.find('.acf-accordion-icon:first').replaceWith( this.iconHtml({ open: true }) );
$el.addClass('-open');
// action
acf.doAction('show', $el);
// close siblings
if( !$el.attr('multi-expand') ) {
$el.siblings('.acf-accordion.-open').each(function(){
accordionManager.close( $(this) );
});
}
},
close: function( $el ){
var duration = acf.isGutenberg() ? 0 : 300;
// close
$el.find('.acf-accordion-content:first').slideUp( duration );
$el.find('.acf-accordion-icon:first').replaceWith( this.iconHtml({ open: false }) );
$el.removeClass('-open');
// action
acf.doAction('hide', $el);
},
onClick: function( e, $el ){
// prevent Defailt
e.preventDefault();
// open close
this.toggle( $el.parent() );
},
onInvalidField: function( e, $el ){
// bail early if already focused
if( this.busy ) {
return;
}
// disable functionality for 1sec (allow next validation to work)
this.busy = true;
this.setTimeout(function(){
this.busy = false;
}, 1000);
// open accordion
this.open( $el );
},
onUnload: function( e ){
// vars
var order = [];
// loop
$('.acf-accordion').each(function(){
var open = $(this).hasClass('-open') ? 1 : 0;
order.push(open);
});
// set
if( order.length ) {
acf.setPreference('this.accordions', order);
}
}
});
})(jQuery);
(function($, undefined){
var Field = acf.Field.extend({
type: 'button_group',
events: {
'click input[type="radio"]': 'onClick'
},
$control: function(){
return this.$('.acf-button-group');
},
$input: function(){
return this.$('input:checked');
},
setValue: function( val ){
this.$('input[value="' + val + '"]').prop('checked', true).trigger('change');
},
onClick: function( e, $el ){
// vars
var $label = $el.parent('label');
var selected = $label.hasClass('selected');
// remove previous selected
this.$('.selected').removeClass('selected');
// add active class
$label.addClass('selected');
// allow null
if( this.get('allow_null') && selected ) {
$label.removeClass('selected');
$el.prop('checked', false).trigger('change');
}
}
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
var Field = acf.Field.extend({
type: 'checkbox',
events: {
'change input': 'onChange',
'click .acf-add-checkbox': 'onClickAdd',
'click .acf-checkbox-toggle': 'onClickToggle',
'click .acf-checkbox-custom': 'onClickCustom'
},
$control: function(){
return this.$('.acf-checkbox-list');
},
$toggle: function(){
return this.$('.acf-checkbox-toggle');
},
$input: function(){
return this.$('input[type="hidden"]');
},
$inputs: function(){
return this.$('input[type="checkbox"]').not('.acf-checkbox-toggle');
},
getValue: function(){
var val = [];
this.$(':checked').each(function(){
val.push( $(this).val() );
});
return val.length ? val : false;
},
onChange: function( e, $el ){
// Vars.
var checked = $el.prop('checked');
var $label = $el.parent('label');
var $toggle = this.$toggle();
// Add or remove "selected" class.
if( checked ) {
$label.addClass('selected');
} else {
$label.removeClass('selected');
}
// Update toggle state if all inputs are checked.
if( $toggle.length ) {
var $inputs = this.$inputs();
// all checked
if( $inputs.not(':checked').length == 0 ) {
$toggle.prop('checked', true);
} else {
$toggle.prop('checked', false);
}
}
},
onClickAdd: function( e, $el ){
var html = '<li><input class="acf-checkbox-custom" type="checkbox" checked="checked" /><input type="text" name="' + this.getInputName() + '[]" /></li>';
$el.parent('li').before( html );
},
onClickToggle: function( e, $el ){
// Vars.
var checked = $el.prop('checked');
var $inputs = this.$('input[type="checkbox"]');
var $labels = this.$('label');
// Update "checked" state.
$inputs.prop('checked', checked);
// Add or remove "selected" class.
if( checked ) {
$labels.addClass('selected');
} else {
$labels.removeClass('selected');
}
},
onClickCustom: function( e, $el ){
var checked = $el.prop('checked');
var $text = $el.next('input[type="text"]');
// checked
if( checked ) {
$text.prop('disabled', false);
// not checked
} else {
$text.prop('disabled', true);
// remove
if( $text.val() == '' ) {
$el.parent('li').remove();
}
}
}
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
var Field = acf.Field.extend({
type: 'color_picker',
wait: 'load',
events: {
'duplicateField': 'onDuplicate'
},
$control: function(){
return this.$('.acf-color-picker');
},
$input: function(){
return this.$('input[type="hidden"]');
},
$inputText: function(){
return this.$('input[type="text"]');
},
setValue: function( val ){
// update input (with change)
acf.val( this.$input(), val );
// update iris
this.$inputText().iris('color', val);
},
initialize: function(){
// vars
var $input = this.$input();
var $inputText = this.$inputText();
// event
var onChange = function( e ){
// timeout is required to ensure the $input val is correct
setTimeout(function(){
acf.val( $input, $inputText.val() );
}, 1);
}
// args
var args = {
defaultColor: false,
palettes: true,
hide: true,
change: onChange,
clear: onChange
};
// filter
var args = acf.applyFilters('color_picker_args', args, this);
// initialize
$inputText.wpColorPicker( args );
},
onDuplicate: function( e, $el, $duplicate ){
// The wpColorPicker library does not provide a destroy method.
// Manually reset DOM by replacing elements back to their original state.
$colorPicker = $duplicate.find('.wp-picker-container');
$inputText = $duplicate.find('input[type="text"]');
$colorPicker.replaceWith( $inputText );
}
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
var Field = acf.Field.extend({
type: 'date_picker',
events: {
'blur input[type="text"]': 'onBlur',
'duplicateField': 'onDuplicate'
},
$control: function(){
return this.$('.acf-date-picker');
},
$input: function(){
return this.$('input[type="hidden"]');
},
$inputText: function(){
return this.$('input[type="text"]');
},
initialize: function(){
// save_format: compatibility with ACF < 5.0.0
if( this.has('save_format') ) {
return this.initializeCompatibility();
}
// vars
var $input = this.$input();
var $inputText = this.$inputText();
// args
var args = {
dateFormat: this.get('date_format'),
altField: $input,
altFormat: 'yymmdd',
changeYear: true,
yearRange: "-100:+100",
changeMonth: true,
showButtonPanel: true,
firstDay: this.get('first_day')
};
// filter
args = acf.applyFilters('date_picker_args', args, this);
// add date picker
acf.newDatePicker( $inputText, args );
// action
acf.doAction('date_picker_init', $inputText, args, this);
},
initializeCompatibility: function(){
// vars
var $input = this.$input();
var $inputText = this.$inputText();
// get and set value from alt field
$inputText.val( $input.val() );
// args
var args = {
dateFormat: this.get('date_format'),
altField: $input,
altFormat: this.get('save_format'),
changeYear: true,
yearRange: "-100:+100",
changeMonth: true,
showButtonPanel: true,
firstDay: this.get('first_day')
};
// filter for 3rd party customization
args = acf.applyFilters('date_picker_args', args, this);
// backup
var dateFormat = args.dateFormat;
// change args.dateFormat
args.dateFormat = this.get('save_format');
// add date picker
acf.newDatePicker( $inputText, args );
// now change the format back to how it should be.
$inputText.datepicker( 'option', 'dateFormat', dateFormat );
// action for 3rd party customization
acf.doAction('date_picker_init', $inputText, args, this);
},
onBlur: function(){
if( !this.$inputText().val() ) {
acf.val( this.$input(), '' );
}
},
onDuplicate: function( e, $el, $duplicate ){
$duplicate.find('input[type="text"]').removeClass('hasDatepicker').removeAttr('id');
}
});
acf.registerFieldType( Field );
// manager
var datePickerManager = new acf.Model({
priority: 5,
wait: 'ready',
initialize: function(){
// vars
var locale = acf.get('locale');
var rtl = acf.get('rtl');
var l10n = acf.get('datePickerL10n');
// bail ealry if no l10n
if( !l10n ) {
return false;
}
// bail ealry if no datepicker library
if( typeof $.datepicker === 'undefined' ) {
return false;
}
// rtl
l10n.isRTL = rtl;
// append
$.datepicker.regional[ locale ] = l10n;
$.datepicker.setDefaults(l10n);
}
});
// add
acf.newDatePicker = function( $input, args ){
// bail ealry if no datepicker library
if( typeof $.datepicker === 'undefined' ) {
return false;
}
// defaults
args = args || {};
// initialize
$input.datepicker( args );
// wrap the datepicker (only if it hasn't already been wrapped)
if( $('body > #ui-datepicker-div').exists() ) {
$('body > #ui-datepicker-div').wrap('<div class="acf-ui-datepicker" />');
}
};
})(jQuery);
(function($, undefined){
var Field = acf.models.DatePickerField.extend({
type: 'date_time_picker',
$control: function(){
return this.$('.acf-date-time-picker');
},
initialize: function(){
// vars
var $input = this.$input();
var $inputText = this.$inputText();
// args
var args = {
dateFormat: this.get('date_format'),
timeFormat: this.get('time_format'),
altField: $input,
altFieldTimeOnly: false,
altFormat: 'yy-mm-dd',
altTimeFormat: 'HH:mm:ss',
changeYear: true,
yearRange: "-100:+100",
changeMonth: true,
showButtonPanel: true,
firstDay: this.get('first_day'),
controlType: 'select',
oneLine: true
};
// filter
args = acf.applyFilters('date_time_picker_args', args, this);
// add date time picker
acf.newDateTimePicker( $inputText, args );
// action
acf.doAction('date_time_picker_init', $inputText, args, this);
}
});
acf.registerFieldType( Field );
// manager
var dateTimePickerManager = new acf.Model({
priority: 5,
wait: 'ready',
initialize: function(){
// vars
var locale = acf.get('locale');
var rtl = acf.get('rtl');
var l10n = acf.get('dateTimePickerL10n');
// bail ealry if no l10n
if( !l10n ) {
return false;
}
// bail ealry if no datepicker library
if( typeof $.timepicker === 'undefined' ) {
return false;
}
// rtl
l10n.isRTL = rtl;
// append
$.timepicker.regional[ locale ] = l10n;
$.timepicker.setDefaults(l10n);
}
});
// add
acf.newDateTimePicker = function( $input, args ){
// bail ealry if no datepicker library
if( typeof $.timepicker === 'undefined' ) {
return false;
}
// defaults
args = args || {};
// initialize
$input.datetimepicker( args );
// wrap the datepicker (only if it hasn't already been wrapped)
if( $('body > #ui-datepicker-div').exists() ) {
$('body > #ui-datepicker-div').wrap('<div class="acf-ui-datepicker" />');
}
};
})(jQuery);
(function($, undefined){
var Field = acf.Field.extend({
type: 'google_map',
map: false,
wait: 'load',
events: {
'click a[data-name="clear"]': 'onClickClear',
'click a[data-name="locate"]': 'onClickLocate',
'click a[data-name="search"]': 'onClickSearch',
'keydown .search': 'onKeydownSearch',
'keyup .search': 'onKeyupSearch',
'focus .search': 'onFocusSearch',
'blur .search': 'onBlurSearch',
'showField': 'onShow',
},
$control: function(){
return this.$('.acf-google-map');
},
$search: function(){
return this.$('.search');
},
$canvas: function(){
return this.$('.canvas');
},
setState: function( state ){
// Remove previous state classes.
this.$control().removeClass( '-value -loading -searching' );
// Determine auto state based of current value.
if( state === 'default' ) {
state = this.val() ? 'value' : '';
}
// Update state class.
if( state ) {
this.$control().addClass( '-' + state );
}
},
getValue: function(){
var val = this.$input().val();
if( val ) {
return JSON.parse( val )
} else {
return false;
}
},
setValue: function( val, silent ){
// Convert input value.
var valAttr = '';
if( val ) {
valAttr = JSON.stringify( val );
}
// Update input (with change).
acf.val( this.$input(), valAttr );
// Bail early if silent update.
if( silent ) {
return;
}
// Render.
this.renderVal( val );
/**
* Fires immediately after the value has changed.
*
* @date 12/02/2014
* @since 5.0.0
*
* @param object|string val The new value.
* @param object map The Google Map isntance.
* @param object field The field instance.
*/
acf.doAction('google_map_change', val, this.map, this);
},
renderVal: function( val ){
// Value.
if( val ) {
this.setState( 'value' );
this.$search().val( val.address );
this.setPosition( val.lat, val.lng );
// No value.
} else {
this.setState( '' );
this.$search().val( '' );
this.map.marker.setVisible( false );
}
},
newLatLng: function( lat, lng ){
return new google.maps.LatLng( parseFloat(lat), parseFloat(lng) );
},
setPosition: function( lat, lng ){
// Update marker position.
this.map.marker.setPosition({
lat: parseFloat(lat),
lng: parseFloat(lng)
});
// Show marker.
this.map.marker.setVisible( true );
// Center map.
this.center();
},
center: function(){
// Find marker position.
var position = this.map.marker.getPosition();
if( position ) {
var lat = position.lat();
var lng = position.lng();
// Or find default settings.
} else {
var lat = this.get('lat');
var lng = this.get('lng');
}
// Center map.
this.map.setCenter({
lat: parseFloat(lat),
lng: parseFloat(lng)
});
},
initialize: function(){
// Ensure Google API is loaded and then initialize map.
withAPI( this.initializeMap.bind(this) );
},
initializeMap: function(){
// Get value ignoring conditional logic status.
var val = this.getValue();
// Construct default args.
var args = acf.parseArgs(val, {
zoom: this.get('zoom'),
lat: this.get('lat'),
lng: this.get('lng')
});
// Create Map.
var mapArgs = {
scrollwheel: false,
zoom: parseInt( args.zoom ),
center: {
lat: parseFloat( args.lat ),
lng: parseFloat( args.lng )
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
marker: {
draggable: true,
raiseOnDrag: true
},
autocomplete: {}
};
mapArgs = acf.applyFilters('google_map_args', mapArgs, this);
var map = new google.maps.Map( this.$canvas()[0], mapArgs );
// Create Marker.
var markerArgs = acf.parseArgs(mapArgs.marker, {
draggable: true,
raiseOnDrag: true,
map: map
});
markerArgs = acf.applyFilters('google_map_marker_args', markerArgs, this);
var marker = new google.maps.Marker( markerArgs );
// Maybe Create Autocomplete.
var autocomplete = false;
if( acf.isset(google, 'maps', 'places', 'Autocomplete') ) {
var autocompleteArgs = mapArgs.autocomplete || {};
autocompleteArgs = acf.applyFilters('google_map_autocomplete_args', autocompleteArgs, this);
autocomplete = new google.maps.places.Autocomplete( this.$search()[0], autocompleteArgs );
autocomplete.bindTo('bounds', map);
}
// Add map events.
this.addMapEvents( this, map, marker, autocomplete );
// Append references.
map.acf = this;
map.marker = marker;
map.autocomplete = autocomplete;
this.map = map;
// Set position.
if( val ) {
this.setPosition( val.lat, val.lng );
}
/**
* Fires immediately after the Google Map has been initialized.
*
* @date 12/02/2014
* @since 5.0.0
*
* @param object map The Google Map isntance.
* @param object marker The Google Map marker isntance.
* @param object field The field instance.
*/
acf.doAction('google_map_init', map, marker, this);
},
addMapEvents: function( field, map, marker, autocomplete ){
// Click map.
google.maps.event.addListener( map, 'click', function( e ) {
var lat = e.latLng.lat();
var lng = e.latLng.lng();
field.searchPosition( lat, lng );
});
// Drag marker.
google.maps.event.addListener( marker, 'dragend', function(){
var lat = this.getPosition().lat();
var lng = this.getPosition().lng();
field.searchPosition( lat, lng );
});
// Autocomplete search.
if( autocomplete ) {
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = this.getPlace();
field.searchPlace( place );
});
}
// Detect zoom change.
google.maps.event.addListener( map, 'zoom_changed', function(){
var val = field.val();
if( val ) {
val.zoom = map.getZoom();
field.setValue( val, true );
}
});
},
searchPosition: function( lat, lng ){
//console.log('searchPosition', lat, lng );
// Start Loading.
this.setState( 'loading' );
// Query Geocoder.
var latLng = { lat: lat, lng: lng };
geocoder.geocode({ location: latLng }, function( results, status ){
//console.log('searchPosition', arguments );
// End Loading.
this.setState( '' );
// Status failure.
if( status !== 'OK' ) {
this.showNotice({
text: acf.__('Location not found: %s').replace('%s', status),
type: 'warning'
});
// Success.
} else {
var val = this.parseResult( results[0] );
// Override lat/lng to match user defined marker location.
// Avoids issue where marker "snaps" to nearest result.
val.lat = lat;
val.lng = lng;
this.val( val );
}
}.bind( this ));
},
searchPlace: function( place ){
//console.log('searchPlace', place );
// Bail early if no place.
if( !place ) {
return;
}
// Selecting from the autocomplete dropdown will return a rich PlaceResult object.
// Be sure to over-write the "formatted_address" value with the one displayed to the user for best UX.
if( place.geometry ) {
place.formatted_address = this.$search().val();
var val = this.parseResult( place );
this.val( val );
// Searching a custom address will return an empty PlaceResult object.
} else if( place.name ) {
this.searchAddress( place.name );
}
},
searchAddress: function( address ){
//console.log('searchAddress', address );
// Bail early if no address.
if( !address ) {
return;
}
// Allow "lat,lng" search.
var latLng = address.split(',');
if( latLng.length == 2 ) {
var lat = parseFloat(latLng[0]);
var lng = parseFloat(latLng[1]);
if( lat && lng ) {
return this.searchPosition( lat, lng );
}
}
// Start Loading.
this.setState( 'loading' );
// Query Geocoder.
geocoder.geocode({ address: address }, function( results, status ){
//console.log('searchPosition', arguments );
// End Loading.
this.setState( '' );
// Status failure.
if( status !== 'OK' ) {
this.showNotice({
text: acf.__('Location not found: %s').replace('%s', status),
type: 'warning'
});
// Success.
} else {
var val = this.parseResult( results[0] );
// Override address data with parameter allowing custom address to be defined in search.
val.address = address;
// Update value.
this.val( val );
}
}.bind( this ));
},
searchLocation: function(){
//console.log('searchLocation' );
// Check HTML5 geolocation.
if( !navigator.geolocation ) {
return alert( acf.__('Sorry, this browser does not support geolocation') );
}
// Start Loading.
this.setState( 'loading' );
// Query Geolocation.
navigator.geolocation.getCurrentPosition(
// Success.
function( results ){
// End Loading.
this.setState( '' );
// Search position.
var lat = results.coords.latitude;
var lng = results.coords.longitude;
this.searchPosition( lat, lng );
}.bind(this),
// Failure.
function( error ){
this.setState( '' );
}.bind(this)
);
},
/**
* parseResult
*
* Returns location data for the given GeocoderResult object.
*
* @date 15/10/19
* @since 5.8.6
*
* @param object obj A GeocoderResult object.
* @return object
*/
parseResult: function( obj ) {
// Construct basic data.
var result = {
address: obj.formatted_address,
lat: obj.geometry.location.lat(),
lng: obj.geometry.location.lng(),
};
// Add zoom level.
result.zoom = this.map.getZoom();
// Add place ID.
if( obj.place_id ) {
result.place_id = obj.place_id;
}
// Add place name.
if( obj.name ) {
result.name = obj.name;
}
// Create search map for address component data.
var map = {
street_number: [ 'street_number' ],
street_name: [ 'street_address', 'route' ],
city: [ 'locality' ],
state: [
'administrative_area_level_1',
'administrative_area_level_2',
'administrative_area_level_3',
'administrative_area_level_4',
'administrative_area_level_5'
],
post_code: [ 'postal_code' ],
country: [ 'country' ]
};
// Loop over map.
for( var k in map ) {
var keywords = map[ k ];
// Loop over address components.
for( var i = 0; i < obj.address_components.length; i++ ) {
var component = obj.address_components[ i ];
var component_type = component.types[0];
// Look for matching component type.
if( keywords.indexOf(component_type) !== -1 ) {
// Append to result.
result[ k ] = component.long_name;
// Append short version.
if( component.long_name !== component.short_name ) {
result[ k + '_short' ] = component.short_name;
}
}
}
}
/**
* Filters the parsed result.
*
* @date 18/10/19
* @since 5.8.6
*
* @param object result The parsed result value.
* @param object obj The GeocoderResult object.
*/
return acf.applyFilters('google_map_result', result, obj, this.map, this);
},
onClickClear: function(){
this.val( false );
},
onClickLocate: function(){
this.searchLocation();
},
onClickSearch: function(){
this.searchAddress( this.$search().val() );
},
onFocusSearch: function( e, $el ){
this.setState( 'searching' );
},
onBlurSearch: function( e, $el ){
// Get saved address value.
var val = this.val();
var address = val ? val.address : '';
// Remove 'is-searching' if value has not changed.
if( $el.val() === address ) {
this.setState( 'default' );
}
},
onKeyupSearch: function( e, $el ){
// Clear empty value.
if( !$el.val() ) {
this.val( false );
}
},
// Prevent form from submitting.
onKeydownSearch: function( e, $el ){
if( e.which == 13 ) {
e.preventDefault();
$el.blur();
}
},
// Center map once made visible.
onShow: function(){
if( this.map ) {
this.setTimeout( this.center );
}
},
});
acf.registerFieldType( Field );
// Vars.
var loading = false;
var geocoder = false;
/**
* withAPI
*
* Loads the Google Maps API library and troggers callback.
*
* @date 28/3/19
* @since 5.7.14
*
* @param function callback The callback to excecute.
* @return void
*/
function withAPI( callback ) {
// Check if geocoder exists.
if( geocoder ) {
return callback();
}
// Check if geocoder API exists.
if( acf.isset(window, 'google', 'maps', 'Geocoder') ) {
geocoder = new google.maps.Geocoder();
return callback();
}
// Geocoder will need to be loaded. Hook callback to action.
acf.addAction( 'google_map_api_loaded', callback );
// Bail early if already loading API.
if( loading ) {
return;
}
// load api
var url = acf.get('google_map_api');
if( url ) {
// Set loading status.
loading = true;
// Load API
$.ajax({
url: url,
dataType: 'script',
cache: true,
success: function(){
geocoder = new google.maps.Geocoder();
acf.doAction('google_map_api_loaded');
}
});
}
}
})(jQuery);
(function($, undefined){
var Field = acf.Field.extend({
type: 'image',
$control: function(){
return this.$('.acf-image-uploader');
},
$input: function(){
return this.$('input[type="hidden"]');
},
events: {
'click a[data-name="add"]': 'onClickAdd',
'click a[data-name="edit"]': 'onClickEdit',
'click a[data-name="remove"]': 'onClickRemove',
'change input[type="file"]': 'onChange'
},
initialize: function(){
// add attribute to form
if( this.get('uploader') === 'basic' ) {
this.$el.closest('form').attr('enctype', 'multipart/form-data');
}
},
validateAttachment: function( attachment ){
// Use WP attachment attributes when available.
if( attachment && attachment.attributes ) {
attachment = attachment.attributes;
}
// Apply defaults.
attachment = acf.parseArgs(attachment, {
id: 0,
url: '',
alt: '',
title: '',
caption: '',
description: '',
width: 0,
height: 0
});
// Override with "preview size".
var size = acf.isget( attachment, 'sizes', this.get('preview_size') );
if( size ) {
attachment.url = size.url;
attachment.width = size.width;
attachment.height = size.height;
}
// Return.
return attachment;
},
render: function( attachment ){
attachment = this.validateAttachment( attachment );
// Update DOM.
this.$('img').attr({
src: attachment.url,
alt: attachment.alt
});
if( attachment.id ) {
this.val( attachment.id );
this.$control().addClass('has-value');
} else {
this.val( '' );
this.$control().removeClass('has-value');
}
},
// create a new repeater row and render value
append: function( attachment, parent ){
// create function to find next available field within parent
var getNext = function( field, parent ){
// find existing file fields within parent
var fields = acf.getFields({
key: field.get('key'),
parent: parent.$el
});
// find the first field with no value
for( var i = 0; i < fields.length; i++ ) {
if( !fields[i].val() ) {
return fields[i];
}
}
// return
return false;
}
// find existing file fields within parent
var field = getNext( this, parent );
// add new row if no available field
if( !field ) {
parent.$('.acf-button:last').trigger('click');
field = getNext( this, parent );
}
// render
if( field ) {
field.render( attachment );
}
},
selectAttachment: function(){
// vars
var parent = this.parent();
var multiple = (parent && parent.get('type') === 'repeater');
// new frame
var frame = acf.newMediaPopup({
mode: 'select',
type: 'image',
title: acf.__('Select Image'),
field: this.get('key'),
multiple: multiple,
library: this.get('library'),
allowedTypes: this.get('mime_types'),
select: $.proxy(function( attachment, i ) {
if( i > 0 ) {
this.append( attachment, parent );
} else {
this.render( attachment );
}
}, this)
});
},
editAttachment: function(){
// vars
var val = this.val();
// bail early if no val
if( !val ) return;
// popup
var frame = acf.newMediaPopup({
mode: 'edit',
title: acf.__('Edit Image'),
button: acf.__('Update Image'),
attachment: val,
field: this.get('key'),
select: $.proxy(function( attachment, i ) {
this.render( attachment );
}, this)
});
},
removeAttachment: function(){
this.render( false );
},
onClickAdd: function( e, $el ){
this.selectAttachment();
},
onClickEdit: function( e, $el ){
this.editAttachment();
},
onClickRemove: function( e, $el ){
this.removeAttachment();
},
onChange: function( e, $el ){
var $hiddenInput = this.$input();
acf.getFileInputData($el, function( data ){
$hiddenInput.val( $.param(data) );
});
}
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
var Field = acf.models.ImageField.extend({
type: 'file',
$control: function(){
return this.$('.acf-file-uploader');
},
$input: function(){
return this.$('input[type="hidden"]');
},
validateAttachment: function( attachment ){
// defaults
attachment = attachment || {};
// WP attachment
if( attachment.id !== undefined ) {
attachment = attachment.attributes;
}
// args
attachment = acf.parseArgs(attachment, {
url: '',
alt: '',
title: '',
filename: '',
filesizeHumanReadable: '',
icon: '/wp-includes/images/media/default.png'
});
// return
return attachment;
},
render: function( attachment ){
// vars
attachment = this.validateAttachment( attachment );
// update image
this.$('img').attr({
src: attachment.icon,
alt: attachment.alt,
title: attachment.title
});
// update elements
this.$('[data-name="title"]').text( attachment.title );
this.$('[data-name="filename"]').text( attachment.filename ).attr( 'href', attachment.url );
this.$('[data-name="filesize"]').text( attachment.filesizeHumanReadable );
// vars
var val = attachment.id || '';
// update val
acf.val( this.$input(), val );
// update class
if( val ) {
this.$control().addClass('has-value');
} else {
this.$control().removeClass('has-value');
}
},
selectAttachment: function(){
// vars
var parent = this.parent();
var multiple = (parent && parent.get('type') === 'repeater');
// new frame
var frame = acf.newMediaPopup({
mode: 'select',
title: acf.__('Select File'),
field: this.get('key'),
multiple: multiple,
library: this.get('library'),
allowedTypes: this.get('mime_types'),
select: $.proxy(function( attachment, i ) {
if( i > 0 ) {
this.append( attachment, parent );
} else {
this.render( attachment );
}
}, this)
});
},
editAttachment: function(){
// vars
var val = this.val();
// bail early if no val
if( !val ) {
return false;
}
// popup
var frame = acf.newMediaPopup({
mode: 'edit',
title: acf.__('Edit File'),
button: acf.__('Update File'),
attachment: val,
field: this.get('key'),
select: $.proxy(function( attachment, i ) {
this.render( attachment );
}, this)
});
}
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
var Field = acf.Field.extend({
type: 'link',
events: {
'click a[data-name="add"]': 'onClickEdit',
'click a[data-name="edit"]': 'onClickEdit',
'click a[data-name="remove"]': 'onClickRemove',
'change .link-node': 'onChange',
},
$control: function(){
return this.$('.acf-link');
},
$node: function(){
return this.$('.link-node');
},
getValue: function(){
// vars
var $node = this.$node();
// return false if empty
if( !$node.attr('href') ) {
return false;
}
// return
return {
title: $node.html(),
url: $node.attr('href'),
target: $node.attr('target')
};
},
setValue: function( val ){
// default
val = acf.parseArgs(val, {
title: '',
url: '',
target: ''
});
// vars
var $div = this.$control();
var $node = this.$node();
// remove class
$div.removeClass('-value -external');
// add class
if( val.url ) $div.addClass('-value');
if( val.target === '_blank' ) $div.addClass('-external');
// update text
this.$('.link-title').html( val.title );
this.$('.link-url').attr('href', val.url).html( val.url );
// update node
$node.html(val.title);
$node.attr('href', val.url);
$node.attr('target', val.target);
// update inputs
this.$('.input-title').val( val.title );
this.$('.input-target').val( val.target );
this.$('.input-url').val( val.url ).trigger('change');
},
onClickEdit: function( e, $el ){
acf.wpLink.open( this.$node() );
},
onClickRemove: function( e, $el ){
this.setValue( false );
},
onChange: function( e, $el ){
// get the changed value
var val = this.getValue();
// update inputs
this.setValue(val);
}
});
acf.registerFieldType( Field );
// manager
acf.wpLink = new acf.Model({
getNodeValue: function(){
var $node = this.get('node');
return {
title: acf.decode( $node.html() ),
url: $node.attr('href'),
target: $node.attr('target')
};
},
setNodeValue: function( val ){
var $node = this.get('node');
$node.text( val.title );
$node.attr('href', val.url);
$node.attr('target', val.target);
$node.trigger('change');
},
getInputValue: function(){
return {
title: $('#wp-link-text').val(),
url: $('#wp-link-url').val(),
target: $('#wp-link-target').prop('checked') ? '_blank' : ''
};
},
setInputValue: function( val ){
$('#wp-link-text').val( val.title );
$('#wp-link-url').val( val.url );
$('#wp-link-target').prop('checked', val.target === '_blank' );
},
open: function( $node ){
// add events
this.on('wplink-open', 'onOpen');
this.on('wplink-close', 'onClose');
// set node
this.set('node', $node);
// create textarea
var $textarea = $('<textarea id="acf-link-textarea" style="display:none;"></textarea>');
$('body').append( $textarea );
// vars
var val = this.getNodeValue();
// open popup
wpLink.open( 'acf-link-textarea', val.url, val.title, null );
},
onOpen: function(){
// always show title (WP will hide title if empty)
$('#wp-link-wrap').addClass('has-text-field');
// set inputs
var val = this.getNodeValue();
this.setInputValue( val );
// Update button text.
if( val.url && wpLinkL10n ) {
$('#wp-link-submit').val( wpLinkL10n.update );
}
},
close: function(){
wpLink.close();
},
onClose: function(){
// Bail early if no node.
// Needed due to WP triggering this event twice.
if( !this.has('node') ) {
return false;
}
// Determine context.
var $submit = $('#wp-link-submit');
var isSubmit = ( $submit.is(':hover') || $submit.is(':focus') );
// Set value
if( isSubmit ) {
var val = this.getInputValue();
this.setNodeValue( val );
}
// Cleanup.
this.off('wplink-open');
this.off('wplink-close');
$('#acf-link-textarea').remove();
this.set('node', null);
}
});
})(jQuery);
(function($, undefined){
var Field = acf.Field.extend({
type: 'oembed',
events: {
'click [data-name="clear-button"]': 'onClickClear',
'keypress .input-search': 'onKeypressSearch',
'keyup .input-search': 'onKeyupSearch',
'change .input-search': 'onChangeSearch'
},
$control: function(){
return this.$('.acf-oembed');
},
$input: function(){
return this.$('.input-value');
},
$search: function(){
return this.$('.input-search');
},
getValue: function(){
return this.$input().val();
},
getSearchVal: function(){
return this.$search().val();
},
setValue: function( val ){
// class
if( val ) {
this.$control().addClass('has-value');
} else {
this.$control().removeClass('has-value');
}
acf.val( this.$input(), val );
},
showLoading: function( show ){
acf.showLoading( this.$('.canvas') );
},
hideLoading: function(){
acf.hideLoading( this.$('.canvas') );
},
maybeSearch: function(){
// vars
var prevUrl = this.val();
var url = this.getSearchVal();
// no value
if( !url ) {
return this.clear();
}
// fix missing 'http://' - causes the oembed code to error and fail
if( url.substr(0, 4) != 'http' ) {
url = 'http://' + url;
}
// bail early if no change
if( url === prevUrl ) return;
// clear existing timeout
var timeout = this.get('timeout');
if( timeout ) {
clearTimeout( timeout );
}
// set new timeout
var callback = $.proxy(this.search, this, url);
this.set('timeout', setTimeout(callback, 300));
},
search: function( url ){
// ajax
var ajaxData = {
action: 'acf/fields/oembed/search',
s: url,
field_key: this.get('key')
};
// clear existing timeout
var xhr = this.get('xhr');
if( xhr ) {
xhr.abort();
}
// loading
this.showLoading();
// query
var xhr = $.ajax({
url: acf.get('ajaxurl'),
data: acf.prepareForAjax(ajaxData),
type: 'post',
dataType: 'json',
context: this,
success: function( json ){
// error
if( !json || !json.html ) {
json = {
url: false,
html: ''
}
}
// update vars
this.val( json.url );
this.$('.canvas-media').html( json.html );
},
complete: function(){
this.hideLoading();
}
});
this.set('xhr', xhr);
},
clear: function(){
this.val('');
this.$search().val('');
this.$('.canvas-media').html('');
},
onClickClear: function( e, $el ){
this.clear();
},
onKeypressSearch: function( e, $el ){
if( e.which == 13 ) {
e.preventDefault();
this.maybeSearch();
}
},
onKeyupSearch: function( e, $el ){
if( $el.val() ) {
this.maybeSearch();
}
},
onChangeSearch: function( e, $el ){
this.maybeSearch();
}
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
var Field = acf.Field.extend({
type: 'radio',
events: {
'click input[type="radio"]': 'onClick',
},
$control: function(){
return this.$('.acf-radio-list');
},
$input: function(){
return this.$('input:checked');
},
$inputText: function(){
return this.$('input[type="text"]');
},
getValue: function(){
var val = this.$input().val();
if( val === 'other' && this.get('other_choice') ) {
val = this.$inputText().val();
}
return val;
},
onClick: function( e, $el ){
// vars
var $label = $el.parent('label');
var selected = $label.hasClass('selected');
var val = $el.val();
// remove previous selected
this.$('.selected').removeClass('selected');
// add active class
$label.addClass('selected');
// allow null
if( this.get('allow_null') && selected ) {
$label.removeClass('selected');
$el.prop('checked', false).trigger('change');
val = false;
}
// other
if( this.get('other_choice') ) {
// enable
if( val === 'other' ) {
this.$inputText().prop('disabled', false);
// disable
} else {
this.$inputText().prop('disabled', true);
}
}
}
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
var Field = acf.Field.extend({
type: 'range',
events: {
'input input[type="range"]': 'onChange',
'change input': 'onChange'
},
$input: function(){
return this.$('input[type="range"]');
},
$inputAlt: function(){
return this.$('input[type="number"]');
},
setValue: function( val ){
this.busy = true;
// Update range input (with change).
acf.val( this.$input(), val );
// Update alt input (without change).
// Read in input value to inherit min/max validation.
acf.val( this.$inputAlt(), this.$input().val(), true );
this.busy = false;
},
onChange: function( e, $el ){
if( !this.busy ) {
this.setValue( $el.val() );
}
}
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
var Field = acf.Field.extend({
type: 'relationship',
events: {
'keypress [data-filter]': 'onKeypressFilter',
'change [data-filter]': 'onChangeFilter',
'keyup [data-filter]': 'onChangeFilter',
'click .choices-list .acf-rel-item': 'onClickAdd',
'click [data-name="remove_item"]': 'onClickRemove',
},
$control: function(){
return this.$('.acf-relationship');
},
$list: function( list ) {
return this.$('.' + list + '-list');
},
$listItems: function( list ) {
return this.$list( list ).find('.acf-rel-item');
},
$listItem: function( list, id ) {
return this.$list( list ).find('.acf-rel-item[data-id="' + id + '"]');
},
getValue: function(){
var val = [];
this.$listItems('values').each(function(){
val.push( $(this).data('id') );
});
return val.length ? val : false;
},
newChoice: function( props ){
return [
'<li>',
'<span data-id="' + props.id + '" class="acf-rel-item">' + props.text + '</span>',
'</li>'
].join('');
},
newValue: function( props ){
return [
'<li>',
'<input type="hidden" name="' + this.getInputName() + '[]" value="' + props.id + '" />',
'<span data-id="' + props.id + '" class="acf-rel-item">' + props.text,
'<a href="#" class="acf-icon -minus small dark" data-name="remove_item"></a>',
'</span>',
'</li>'
].join('');
},
initialize: function(){
// Delay initialization until "interacted with" or "in view".
var delayed = this.proxy(acf.once(function(){
// Add sortable.
this.$list('values').sortable({
items: 'li',
forceHelperSize: true,
forcePlaceholderSize: true,
scroll: true,
update: this.proxy(function(){
this.$input().trigger('change');
})
});
// Avoid browser remembering old scroll position and add event.
this.$list('choices').scrollTop(0).on('scroll', this.proxy(this.onScrollChoices));
// Fetch choices.
this.fetch();
}));
// Bind "interacted with".
this.$el.one( 'mouseover', delayed );
this.$el.one( 'focus', 'input', delayed );
// Bind "in view".
acf.onceInView( this.$el, delayed );
},
onScrollChoices: function(e){
// bail early if no more results
if( this.get('loading') || !this.get('more') ) {
return;
}
// Scrolled to bottom
var $list = this.$list('choices');
var scrollTop = Math.ceil( $list.scrollTop() );
var scrollHeight = Math.ceil( $list[0].scrollHeight );
var innerHeight = Math.ceil( $list.innerHeight() );
var paged = this.get('paged') || 1;
if( (scrollTop + innerHeight) >= scrollHeight ) {
// update paged
this.set('paged', (paged+1));
// fetch
this.fetch();
}
},
onKeypressFilter: function( e, $el ){
// don't submit form
if( e.which == 13 ) {
e.preventDefault();
}
},
onChangeFilter: function( e, $el ){
// vars
var val = $el.val();
var filter = $el.data('filter');
// Bail early if filter has not changed
if( this.get(filter) === val ) {
return;
}
// update attr
this.set(filter, val);
// reset paged
this.set('paged', 1);
// fetch
if( $el.is('select') ) {
this.fetch();
// search must go through timeout
} else {
this.maybeFetch();
}
},
onClickAdd: function( e, $el ){
// vars
var val = this.val();
var max = parseInt( this.get('max') );
// can be added?
if( $el.hasClass('disabled') ) {
return false;
}
// validate
if( max > 0 && val && val.length >= max ) {
// add notice
this.showNotice({
text: acf.__('Maximum values reached ( {max} values )').replace('{max}', max),
type: 'warning'
});
return false;
}
// disable
$el.addClass('disabled');
// add
var html = this.newValue({
id: $el.data('id'),
text: $el.html()
});
this.$list('values').append( html )
// trigger change
this.$input().trigger('change');
},
onClickRemove: function( e, $el ){
// Prevent default here because generic handler wont be triggered.
e.preventDefault();
// vars
var $span = $el.parent();
var $li = $span.parent();
var id = $span.data('id');
// remove value
$li.remove();
// show choice
this.$listItem('choices', id).removeClass('disabled');
// trigger change
this.$input().trigger('change');
},
maybeFetch: function(){
// vars
var timeout = this.get('timeout');
// abort timeout
if( timeout ) {
clearTimeout( timeout );
}
// fetch
timeout = this.setTimeout(this.fetch, 300);
this.set('timeout', timeout);
},
getAjaxData: function(){
// load data based on element attributes
var ajaxData = this.$control().data();
for( var name in ajaxData ) {
ajaxData[ name ] = this.get( name );
}
// extra
ajaxData.action = 'acf/fields/relationship/query';
ajaxData.field_key = this.get('key');
// Filter.
ajaxData = acf.applyFilters( 'relationship_ajax_data', ajaxData, this );
// return
return ajaxData;
},
fetch: function(){
// abort XHR if this field is already loading AJAX data
var xhr = this.get('xhr');
if( xhr ) {
xhr.abort();
}
// add to this.o
var ajaxData = this.getAjaxData();
// clear html if is new query
var $choiceslist = this.$list( 'choices' );
if( ajaxData.paged == 1 ) {
$choiceslist.html('');
}
// loading
var $loading = $('<li><i class="acf-loading"></i> ' + acf.__('Loading') + '</li>');
$choiceslist.append($loading);
this.set('loading', true);
// callback
var onComplete = function(){
this.set('loading', false);
$loading.remove();
};
var onSuccess = function( json ){
// no results
if( !json || !json.results || !json.results.length ) {
// prevent pagination
this.set('more', false);
// add message
if( this.get('paged') == 1 ) {
this.$list('choices').append('<li>' + acf.__('No matches found') + '</li>');
}
// return
return;
}
// set more (allows pagination scroll)
this.set('more', json.more );
// get new results
var html = this.walkChoices(json.results);
var $html = $( html );
// apply .disabled to left li's
var val = this.val();
if( val && val.length ) {
val.map(function( id ){
$html.find('.acf-rel-item[data-id="' + id + '"]').addClass('disabled');
});
}
// append
$choiceslist.append( $html );
// merge together groups
var $prevLabel = false;
var $prevList = false;
$choiceslist.find('.acf-rel-label').each(function(){
var $label = $(this);
var $list = $label.siblings('ul');
if( $prevLabel && $prevLabel.text() == $label.text() ) {
$prevList.append( $list.children() );
$(this).parent().remove();
return;
}
// update vars
$prevLabel = $label;
$prevList = $list;
});
};
// get results
var xhr = $.ajax({
url: acf.get('ajaxurl'),
dataType: 'json',
type: 'post',
data: acf.prepareForAjax(ajaxData),
context: this,
success: onSuccess,
complete: onComplete
});
// set
this.set('xhr', xhr);
},
walkChoices: function( data ){
// walker
var walk = function( data ){
// vars
var html = '';
// is array
if( $.isArray(data) ) {
data.map(function(item){
html += walk( item );
});
// is item
} else if( $.isPlainObject(data) ) {
// group
if( data.children !== undefined ) {
html += '<li><span class="acf-rel-label">' + acf.escHtml( data.text ) + '</span><ul class="acf-bl">';
html += walk( data.children );
html += '</ul></li>';
// single
} else {
html += '<li><span class="acf-rel-item" data-id="' + acf.escAttr( data.id ) + '">' + acf.escHtml( data.text ) + '</span></li>';
}
}
// return
return html;
};
return walk( data );
}
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
var Field = acf.Field.extend({
type: 'select',
select2: false,
wait: 'load',
events: {
'removeField': 'onRemove',
'duplicateField': 'onDuplicate'
},
$input: function(){
return this.$('select');
},
initialize: function(){
// vars
var $select = this.$input();
// inherit data
this.inherit( $select );
// select2
if( this.get('ui') ) {
// populate ajax_data (allowing custom attribute to already exist)
var ajaxAction = this.get('ajax_action');
if( !ajaxAction ) {
ajaxAction = 'acf/fields/' + this.get('type') + '/query';
}
// select2
this.select2 = acf.newSelect2($select, {
field: this,
ajax: this.get('ajax'),
multiple: this.get('multiple'),
placeholder: this.get('placeholder'),
allowNull: this.get('allow_null'),
ajaxAction: ajaxAction,
});
}
},
onRemove: function(){
if( this.select2 ) {
this.select2.destroy();
}
},
onDuplicate: function( e, $el, $duplicate ){
if( this.select2 ) {
$duplicate.find('.select2-container').remove();
$duplicate.find('select').removeClass('select2-hidden-accessible');
}
}
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
// vars
var CONTEXT = 'tab';
var Field = acf.Field.extend({
type: 'tab',
wait: '',
tabs: false,
tab: false,
events: {
'duplicateField': 'onDuplicate'
},
findFields: function(){
return this.$el.nextUntil('.acf-field-tab', '.acf-field');
},
getFields: function(){
return acf.getFields( this.findFields() );
},
findTabs: function(){
return this.$el.prevAll('.acf-tab-wrap:first');
},
findTab: function(){
return this.$('.acf-tab-button');
},
initialize: function(){
// bail early if is td
if( this.$el.is('td') ) {
this.events = {};
return false;
}
// vars
var $tabs = this.findTabs();
var $tab = this.findTab();
var settings = acf.parseArgs($tab.data(), {
endpoint: false,
placement: '',
before: this.$el
});
// create wrap
if( !$tabs.length || settings.endpoint ) {
this.tabs = new Tabs( settings );
} else {
this.tabs = $tabs.data('acf');
}
// add tab
this.tab = this.tabs.addTab($tab, this);
},
isActive: function(){
return this.tab.isActive();
},
showFields: function(){
// show fields
this.getFields().map(function( field ){
field.show( this.cid, CONTEXT );
field.hiddenByTab = false;
}, this);
},
hideFields: function(){
// hide fields
this.getFields().map(function( field ){
field.hide( this.cid, CONTEXT );
field.hiddenByTab = this.tab;
}, this);
},
show: function( lockKey ){
// show field and store result
var visible = acf.Field.prototype.show.apply(this, arguments);
// check if now visible
if( visible ) {
// show tab
this.tab.show();
// check active tabs
this.tabs.refresh();
}
// return
return visible;
},
hide: function( lockKey ){
// hide field and store result
var hidden = acf.Field.prototype.hide.apply(this, arguments);
// check if now hidden
if( hidden ) {
// hide tab
this.tab.hide();
// reset tabs if this was active
if( this.isActive() ) {
this.tabs.reset();
}
}
// return
return hidden;
},
enable: function( lockKey ){
// enable fields
this.getFields().map(function( field ){
field.enable( CONTEXT );
});
},
disable: function( lockKey ){
// disable fields
this.getFields().map(function( field ){
field.disable( CONTEXT );
});
},
onDuplicate: function( e, $el, $duplicate ){
if( this.isActive() ) {
$duplicate.prevAll('.acf-tab-wrap:first').remove();
}
}
});
acf.registerFieldType( Field );
/**
* tabs
*
* description
*
* @date 8/2/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
var i = 0;
var Tabs = acf.Model.extend({
tabs: [],
active: false,
actions: {
'refresh': 'onRefresh'
},
data: {
before: false,
placement: 'top',
index: 0,
initialized: false,
},
setup: function( settings ){
// data
$.extend(this.data, settings);
// define this prop to avoid scope issues
this.tabs = [];
this.active = false;
// vars
var placement = this.get('placement');
var $before = this.get('before');
var $parent = $before.parent();
// add sidebar for left placement
if( placement == 'left' && $parent.hasClass('acf-fields') ) {
$parent.addClass('-sidebar');
}
// create wrap
if( $before.is('tr') ) {
this.$el = $('<tr class="acf-tab-wrap"><td colspan="2"><ul class="acf-hl acf-tab-group"></ul></td></tr>');
} else {
this.$el = $('<div class="acf-tab-wrap -' + placement + '"><ul class="acf-hl acf-tab-group"></ul></div>');
}
// append
$before.before( this.$el );
// set index
this.set('index', i, true);
i++;
},
initializeTabs: function(){
// find first visible tab
var tab = this.getVisible().shift();
// remember previous tab state
var order = acf.getPreference('this.tabs') || [];
var groupIndex = this.get('index');
var tabIndex = order[ groupIndex ];
if( this.tabs[ tabIndex ] && this.tabs[ tabIndex ].isVisible() ) {
tab = this.tabs[ tabIndex ];
}
// select
if( tab ) {
this.selectTab( tab );
} else {
this.closeTabs();
}
// set local variable used by tabsManager
this.set('initialized', true);
},
getVisible: function(){
return this.tabs.filter(function( tab ){
return tab.isVisible();
});
},
getActive: function(){
return this.active;
},
setActive: function( tab ){
return this.active = tab;
},
hasActive: function(){
return (this.active !== false);
},
isActive: function( tab ){
var active = this.getActive();
return (active && active.cid === tab.cid);
},
closeActive: function(){
if( this.hasActive() ) {
this.closeTab( this.getActive() );
}
},
openTab: function( tab ){
// close existing tab
this.closeActive();
// open
tab.open();
// set active
this.setActive( tab );
},
closeTab: function( tab ){
// close
tab.close();
// set active
this.setActive( false );
},
closeTabs: function(){
this.tabs.map( this.closeTab, this );
},
selectTab: function( tab ){
// close other tabs
this.tabs.map(function( t ){
if( tab.cid !== t.cid ) {
this.closeTab( t );
}
}, this);
// open
this.openTab( tab );
},
addTab: function( $a, field ){
// create <li>
var $li = $('<li>' + $a.outerHTML() + '</li>');
// append
this.$('ul').append( $li );
// initialize
var tab = new Tab({
$el: $li,
field: field,
group: this,
});
// store
this.tabs.push( tab );
// return
return tab;
},
reset: function(){
// close existing tab
this.closeActive();
// find and active a tab
return this.refresh();
},
refresh: function(){
// bail early if active already exists
if( this.hasActive() ) {
return false;
}
// find next active tab
var tab = this.getVisible().shift();
// open tab
if( tab ) {
this.openTab( tab );
}
// return
return tab;
},
onRefresh: function(){
// only for left placements
if( this.get('placement') !== 'left' ) {
return;
}
// vars
var $parent = this.$el.parent();
var $list = this.$el.children('ul');
var attribute = $parent.is('td') ? 'height' : 'min-height';
// find height (minus 1 for border-bottom)
var height = $list.position().top + $list.outerHeight(true) - 1;
// add css
$parent.css(attribute, height);
}
});
var Tab = acf.Model.extend({
group: false,
field: false,
events: {
'click a': 'onClick'
},
index: function(){
return this.$el.index();
},
isVisible: function(){
return acf.isVisible( this.$el );
},
isActive: function(){
return this.$el.hasClass('active');
},
open: function(){
// add class
this.$el.addClass('active');
// show field
this.field.showFields();
},
close: function(){
// remove class
this.$el.removeClass('active');
// hide field
this.field.hideFields();
},
onClick: function( e, $el ){
// prevent default
e.preventDefault();
// toggle
this.toggle();
},
toggle: function(){
// bail early if already active
if( this.isActive() ) {
return;
}
// toggle this tab
this.group.openTab( this );
}
});
var tabsManager = new acf.Model({
priority: 50,
actions: {
'prepare': 'render',
'append': 'render',
'unload': 'onUnload',
'invalid_field': 'onInvalidField'
},
findTabs: function(){
return $('.acf-tab-wrap');
},
getTabs: function(){
return acf.getInstances( this.findTabs() );
},
render: function( $el ){
this.getTabs().map(function( tabs ){
if( !tabs.get('initialized') ) {
tabs.initializeTabs();
}
});
},
onInvalidField: function( field ){
// bail early if busy
if( this.busy ) {
return;
}
// ignore if not hidden by tab
if( !field.hiddenByTab ) {
return;
}
// toggle tab
field.hiddenByTab.toggle();
// ignore other invalid fields
this.busy = true;
this.setTimeout(function(){
this.busy = false;
}, 100);
},
onUnload: function(){
// vars
var order = [];
// loop
this.getTabs().map(function( group ){
var active = group.hasActive() ? group.getActive().index() : 0;
order.push(active);
});
// bail if no tabs
if( !order.length ) {
return;
}
// update
acf.setPreference('this.tabs', order);
}
});
})(jQuery);
(function($, undefined){
var Field = acf.models.SelectField.extend({
type: 'post_object',
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
var Field = acf.models.SelectField.extend({
type: 'page_link',
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
var Field = acf.models.SelectField.extend({
type: 'user',
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
var Field = acf.Field.extend({
type: 'taxonomy',
data: {
'ftype': 'select'
},
select2: false,
wait: 'load',
events: {
'click a[data-name="add"]': 'onClickAdd',
'click input[type="radio"]': 'onClickRadio',
'removeField': 'onRemove'
},
$control: function(){
return this.$('.acf-taxonomy-field');
},
$input: function(){
return this.getRelatedPrototype().$input.apply(this, arguments);
},
getRelatedType: function(){
// vars
var fieldType = this.get('ftype');
// normalize
if( fieldType == 'multi_select' ) {
fieldType = 'select';
}
// return
return fieldType;
},
getRelatedPrototype: function(){
return acf.getFieldType( this.getRelatedType() ).prototype;
},
getValue: function(){
return this.getRelatedPrototype().getValue.apply(this, arguments);
},
setValue: function(){
return this.getRelatedPrototype().setValue.apply(this, arguments);
},
initialize: function(){
this.getRelatedPrototype().initialize.apply(this, arguments);
},
onRemove: function(){
var proto = this.getRelatedPrototype();
if( proto.onRemove ) {
proto.onRemove.apply(this, arguments);
}
},
onClickAdd: function( e, $el ){
// vars
var field = this;
var popup = false;
var $form = false;
var $name = false;
var $parent = false;
var $button = false;
var $message = false;
var notice = false;
// step 1.
var step1 = function(){
// popup
popup = acf.newPopup({
title: $el.attr('title'),
loading: true,
width: '300px'
});
// ajax
var ajaxData = {
action: 'acf/fields/taxonomy/add_term',
field_key: field.get('key')
};
// get HTML
$.ajax({
url: acf.get('ajaxurl'),
data: acf.prepareForAjax(ajaxData),
type: 'post',
dataType: 'html',
success: step2
});
};
// step 2.
var step2 = function( html ){
// update popup
popup.loading(false);
popup.content(html);
// vars
$form = popup.$('form');
$name = popup.$('input[name="term_name"]');
$parent = popup.$('select[name="term_parent"]');
$button = popup.$('.acf-submit-button');
// focus
$name.focus();
// submit form
popup.on('submit', 'form', step3);
};
// step 3.
var step3 = function( e, $el ){
// prevent
e.preventDefault();
e.stopImmediatePropagation();
// basic validation
if( $name.val() === '' ) {
$name.focus();
return false;
}
// disable
acf.startButtonLoading( $button );
// ajax
var ajaxData = {
action: 'acf/fields/taxonomy/add_term',
field_key: field.get('key'),
term_name: $name.val(),
term_parent: $parent.length ? $parent.val() : 0
};
$.ajax({
url: acf.get('ajaxurl'),
data: acf.prepareForAjax(ajaxData),
type: 'post',
dataType: 'json',
success: step4
});
};
// step 4.
var step4 = function( json ){
// enable
acf.stopButtonLoading( $button );
// remove prev notice
if( notice ) {
notice.remove();
}
// success
if( acf.isAjaxSuccess(json) ) {
// clear name
$name.val('');
// update term lists
step5( json.data );
// notice
notice = acf.newNotice({
type: 'success',
text: acf.getAjaxMessage(json),
target: $form,
timeout: 2000,
dismiss: false
});
} else {
// notice
notice = acf.newNotice({
type: 'error',
text: acf.getAjaxError(json),
target: $form,
timeout: 2000,
dismiss: false
});
}
// focus
$name.focus();
};
// step 5.
var step5 = function( term ){
// update parent dropdown
var $option = $('<option value="' + term.term_id + '">' + term.term_label + '</option>');
if( term.term_parent ) {
$parent.children('option[value="' + term.term_parent + '"]').after( $option );
} else {
$parent.append( $option );
}
// add this new term to all taxonomy field
var fields = acf.getFields({
type: 'taxonomy'
});
fields.map(function( otherField ){
if( otherField.get('taxonomy') == field.get('taxonomy') ) {
otherField.appendTerm( term );
}
});
// select
field.selectTerm( term.term_id );
};
// run
step1();
},
appendTerm: function( term ){
if( this.getRelatedType() == 'select' ) {
this.appendTermSelect( term );
} else {
this.appendTermCheckbox( term );
}
},
appendTermSelect: function( term ){
this.select2.addOption({
id: term.term_id,
text: term.term_label
});
},
appendTermCheckbox: function( term ){
// vars
var name = this.$('[name]:first').attr('name');
var $ul = this.$('ul:first');
// allow multiple selection
if( this.getRelatedType() == 'checkbox' ) {
name += '[]';
}
// create new li
var $li = $([
'<li data-id="' + term.term_id + '">',
'<label>',
'<input type="' + this.get('ftype') + '" value="' + term.term_id + '" name="' + name + '" /> ',
'<span>' + term.term_name + '</span>',
'</label>',
'</li>'
].join(''));
// find parent
if( term.term_parent ) {
// vars
var $parent = $ul.find('li[data-id="' + term.term_parent + '"]');
// update vars
$ul = $parent.children('ul');
// create ul
if( !$ul.exists() ) {
$ul = $('<ul class="children acf-bl"></ul>');
$parent.append( $ul );
}
}
// append
$ul.append( $li );
},
selectTerm: function( id ){
if( this.getRelatedType() == 'select' ) {
this.select2.selectOption( id );
} else {
var $input = this.$('input[value="' + id + '"]');
$input.prop('checked', true).trigger('change');
}
},
onClickRadio: function( e, $el ){
// vars
var $label = $el.parent('label');
var selected = $label.hasClass('selected');
// remove previous selected
this.$('.selected').removeClass('selected');
// add active class
$label.addClass('selected');
// allow null
if( this.get('allow_null') && selected ) {
$label.removeClass('selected');
$el.prop('checked', false).trigger('change');
}
}
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
var Field = acf.models.DatePickerField.extend({
type: 'time_picker',
$control: function(){
return this.$('.acf-time-picker');
},
initialize: function(){
// vars
var $input = this.$input();
var $inputText = this.$inputText();
// args
var args = {
timeFormat: this.get('time_format'),
altField: $input,
altFieldTimeOnly: false,
altTimeFormat: 'HH:mm:ss',
showButtonPanel: true,
controlType: 'select',
oneLine: true,
closeText: acf.get('dateTimePickerL10n').selectText,
timeOnly: true,
};
// add custom 'Close = Select' functionality
args.onClose = function( value, dp_instance, t_instance ){
// vars
var $close = dp_instance.dpDiv.find('.ui-datepicker-close');
// if clicking close button
if( !value && $close.is(':hover') ) {
t_instance._updateDateTime();
}
};
// filter
args = acf.applyFilters('time_picker_args', args, this);
// add date time picker
acf.newTimePicker( $inputText, args );
// action
acf.doAction('time_picker_init', $inputText, args, this);
}
});
acf.registerFieldType( Field );
// add
acf.newTimePicker = function( $input, args ){
// bail ealry if no datepicker library
if( typeof $.timepicker === 'undefined' ) {
return false;
}
// defaults
args = args || {};
// initialize
$input.timepicker( args );
// wrap the datepicker (only if it hasn't already been wrapped)
if( $('body > #ui-datepicker-div').exists() ) {
$('body > #ui-datepicker-div').wrap('<div class="acf-ui-datepicker" />');
}
};
})(jQuery);
(function($, undefined){
var Field = acf.Field.extend({
type: 'true_false',
events: {
'change .acf-switch-input': 'onChange',
'focus .acf-switch-input': 'onFocus',
'blur .acf-switch-input': 'onBlur',
'keypress .acf-switch-input': 'onKeypress'
},
$input: function(){
return this.$('input[type="checkbox"]');
},
$switch: function(){
return this.$('.acf-switch');
},
getValue: function(){
return this.$input().prop('checked') ? 1 : 0;
},
initialize: function(){
this.render();
},
render: function(){
// vars
var $switch = this.$switch();
// bail ealry if no $switch
if( !$switch.length ) return;
// vars
var $on = $switch.children('.acf-switch-on');
var $off = $switch.children('.acf-switch-off');
var width = Math.max( $on.width(), $off.width() );
// bail ealry if no width
if( !width ) return;
// set widths
$on.css( 'min-width', width );
$off.css( 'min-width', width );
},
switchOn: function() {
this.$input().prop('checked', true);
this.$switch().addClass('-on');
},
switchOff: function() {
this.$input().prop('checked', false);
this.$switch().removeClass('-on');
},
onChange: function( e, $el ){
if( $el.prop('checked') ) {
this.switchOn();
} else {
this.switchOff();
}
},
onFocus: function( e, $el ){
this.$switch().addClass('-focus');
},
onBlur: function( e, $el ){
this.$switch().removeClass('-focus');
},
onKeypress: function( e, $el ){
// left
if( e.keyCode === 37 ) {
return this.switchOff();
}
// right
if( e.keyCode === 39 ) {
return this.switchOn();
}
}
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
var Field = acf.Field.extend({
type: 'url',
events: {
'keyup input[type="url"]': 'onkeyup'
},
$control: function(){
return this.$('.acf-input-wrap');
},
$input: function(){
return this.$('input[type="url"]');
},
initialize: function(){
this.render();
},
isValid: function(){
// vars
var val = this.val();
// bail early if no val
if( !val ) {
return false;
}
// url
if( val.indexOf('://') !== -1 ) {
return true;
}
// protocol relative url
if( val.indexOf('//') === 0 ) {
return true;
}
// return
return false;
},
render: function(){
// add class
if( this.isValid() ) {
this.$control().addClass('-valid');
} else {
this.$control().removeClass('-valid');
}
},
onkeyup: function( e, $el ){
this.render();
}
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
var Field = acf.Field.extend({
type: 'wysiwyg',
wait: 'load',
events: {
'mousedown .acf-editor-wrap.delay': 'onMousedown',
'unmountField': 'disableEditor',
'remountField': 'enableEditor',
'removeField': 'disableEditor'
},
$control: function(){
return this.$('.acf-editor-wrap');
},
$input: function(){
return this.$('textarea');
},
getMode: function(){
return this.$control().hasClass('tmce-active') ? 'visual' : 'text';
},
initialize: function(){
// initializeEditor if no delay
if( !this.$control().hasClass('delay') ) {
this.initializeEditor();
}
},
initializeEditor: function(){
// vars
var $wrap = this.$control();
var $textarea = this.$input();
var args = {
tinymce: true,
quicktags: true,
toolbar: this.get('toolbar'),
mode: this.getMode(),
field: this
};
// generate new id
var oldId = $textarea.attr('id');
var newId = acf.uniqueId('acf-editor-');
// Backup textarea data.
var inputData = $textarea.data();
var inputVal = $textarea.val();
// rename
acf.rename({
target: $wrap,
search: oldId,
replace: newId,
destructive: true
});
// update id
this.set('id', newId, true);
// apply data to new textarea (acf.rename creates a new textarea element due to destructive mode)
// fixes bug where conditional logic "disabled" is lost during "screen_check"
this.$input().data( inputData ).val( inputVal );
// initialize
acf.tinymce.initialize( newId, args );
},
onMousedown: function( e ){
// prevent default
e.preventDefault();
// remove delay class
var $wrap = this.$control();
$wrap.removeClass('delay');
$wrap.find('.acf-editor-toolbar').remove();
// initialize
this.initializeEditor();
},
enableEditor: function(){
if( this.getMode() == 'visual' ) {
acf.tinymce.enable( this.get('id') );
}
},
disableEditor: function(){
acf.tinymce.destroy( this.get('id') );
}
});
acf.registerFieldType( Field );
})(jQuery);
(function($, undefined){
// vars
var storage = [];
/**
* acf.Condition
*
* description
*
* @date 23/3/18
* @since 5.6.9
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.Condition = acf.Model.extend({
type: '', // used for model name
operator: '==', // rule operator
label: '', // label shown when editing fields
choiceType: 'input', // input, select
fieldTypes: [], // auto connect this conditions with these field types
data: {
conditions: false, // the parent instance
field: false, // the field which we query against
rule: {} // the rule [field, operator, value]
},
events: {
'change': 'change',
'keyup': 'change',
'enableField': 'change',
'disableField': 'change'
},
setup: function( props ){
$.extend(this.data, props);
},
getEventTarget: function( $el, event ){
return $el || this.get('field').$el;
},
change: function( e, $el ){
this.get('conditions').change( e );
},
match: function( rule, field ){
return false;
},
calculate: function(){
return this.match( this.get('rule'), this.get('field') );
},
choices: function( field ){
return '<input type="text" />';
}
});
/**
* acf.newCondition
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.newCondition = function( rule, conditions ){
// currently setting up conditions for fieldX, this field is the 'target'
var target = conditions.get('field');
// use the 'target' to find the 'trigger' field.
// - this field is used to setup the conditional logic events
var field = target.getField( rule.field );
// bail ealry if no target or no field (possible if field doesn't exist due to HTML error)
if( !target || !field ) {
return false;
}
// vars
var args = {
rule: rule,
target: target,
conditions: conditions,
field: field
};
// vars
var fieldType = field.get('type');
var operator = rule.operator;
// get avaibale conditions
var conditionTypes = acf.getConditionTypes({
fieldType: fieldType,
operator: operator,
});
// instantiate
var model = conditionTypes[0] || acf.Condition;
// instantiate
var condition = new model( args );
// return
return condition;
};
/**
* mid
*
* Calculates the model ID for a field type
*
* @date 15/12/17
* @since 5.6.5
*
* @param string type
* @return string
*/
var modelId = function( type ) {
return acf.strPascalCase( type || '' ) + 'Condition';
};
/**
* acf.registerConditionType
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.registerConditionType = function( model ){
// vars
var proto = model.prototype;
var type = proto.type;
var mid = modelId( type );
// store model
acf.models[ mid ] = model;
// store reference
storage.push( type );
};
/**
* acf.getConditionType
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.getConditionType = function( type ){
var mid = modelId( type );
return acf.models[ mid ] || false;
}
/**
* acf.registerConditionForFieldType
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.registerConditionForFieldType = function( conditionType, fieldType ){
// get model
var model = acf.getConditionType( conditionType );
// append
if( model ) {
model.prototype.fieldTypes.push( fieldType );
}
};
/**
* acf.getConditionTypes
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.getConditionTypes = function( args ){
// defaults
args = acf.parseArgs(args, {
fieldType: '',
operator: ''
});
// clonse available types
var types = [];
// loop
storage.map(function( type ){
// vars
var model = acf.getConditionType(type);
var ProtoFieldTypes = model.prototype.fieldTypes;
var ProtoOperator = model.prototype.operator;
// check fieldType
if( args.fieldType && ProtoFieldTypes.indexOf( args.fieldType ) === -1 ) {
return;
}
// check operator
if( args.operator && ProtoOperator !== args.operator ) {
return;
}
// append
types.push( model );
});
// return
return types;
};
})(jQuery);
(function($, undefined){
// vars
var CONTEXT = 'conditional_logic';
/**
* conditionsManager
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
var conditionsManager = new acf.Model({
id: 'conditionsManager',
priority: 20, // run actions later
actions: {
'new_field': 'onNewField',
},
onNewField: function( field ){
if( field.has('conditions') ) {
field.getConditions().render();
}
},
});
/**
* acf.Field.prototype.getField
*
* Finds a field that is related to another field
*
* @date 1/2/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
var getSiblingField = function( field, key ){
// find sibling (very fast)
var fields = acf.getFields({
key: key,
sibling: field.$el,
suppressFilters: true,
});
// find sibling-children (fast)
// needed for group fields, accordions, etc
if( !fields.length ) {
fields = acf.getFields({
key: key,
parent: field.$el.parent(),
suppressFilters: true,
});
}
// return
if( fields.length ) {
return fields[0];
}
return false;
};
acf.Field.prototype.getField = function( key ){
// get sibling field
var field = getSiblingField( this, key );
// return early
if( field ) {
return field;
}
// move up through each parent and try again
var parents = this.parents();
for( var i = 0; i < parents.length; i++ ) {
// get sibling field
field = getSiblingField( parents[i], key );
// return early
if( field ) {
return field;
}
}
// return
return false;
};
/**
* acf.Field.prototype.getConditions
*
* Returns the field's conditions instance
*
* @date 1/2/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.Field.prototype.getConditions = function(){
// instantiate
if( !this.conditions ) {
this.conditions = new Conditions( this );
}
// return
return this.conditions;
};
/**
* Conditions
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
var timeout = false;
var Conditions = acf.Model.extend({
id: 'Conditions',
data: {
field: false, // The field with "data-conditions" (target).
timeStamp: false, // Reference used during "change" event.
groups: [], // The groups of condition instances.
},
setup: function( field ){
// data
this.data.field = field;
// vars
var conditions = field.get('conditions');
// detect groups
if( conditions instanceof Array ) {
// detect groups
if( conditions[0] instanceof Array ) {
// loop
conditions.map(function(rules, i){
this.addRules( rules, i );
}, this);
// detect rules
} else {
this.addRules( conditions );
}
// detect rule
} else {
this.addRule( conditions );
}
},
change: function( e ){
// this function may be triggered multiple times per event due to multiple condition classes
// compare timestamp to allow only 1 trigger per event
if( this.get('timeStamp') === e.timeStamp ) {
return false;
} else {
this.set('timeStamp', e.timeStamp, true);
}
// render condition and store result
var changed = this.render();
},
render: function(){
return this.calculate() ? this.show() : this.hide();
},
show: function(){
return this.get('field').showEnable(this.cid, CONTEXT);
},
hide: function(){
return this.get('field').hideDisable(this.cid, CONTEXT);
},
calculate: function(){
// vars
var pass = false;
// loop
this.getGroups().map(function( group ){
// igrnore this group if another group passed
if( pass ) return;
// find passed
var passed = group.filter(function(condition){
return condition.calculate();
});
// if all conditions passed, update the global var
if( passed.length == group.length ) {
pass = true;
}
});
return pass;
},
hasGroups: function(){
return this.data.groups != null;
},
getGroups: function(){
return this.data.groups;
},
addGroup: function(){
var group = [];
this.data.groups.push( group );
return group;
},
hasGroup: function( i ){
return this.data.groups[i] != null;
},
getGroup: function( i ){
return this.data.groups[i];
},
removeGroup: function( i ){
this.data.groups[i].delete;
return this;
},
addRules: function( rules, group ){
rules.map(function( rule ){
this.addRule( rule, group );
}, this);
},
addRule: function( rule, group ){
// defaults
group = group || 0;
// vars
var groupArray;
// get group
if( this.hasGroup(group) ) {
groupArray = this.getGroup(group);
} else {
groupArray = this.addGroup();
}
// instantiate
var condition = acf.newCondition( rule, this );
// bail ealry if condition failed (field did not exist)
if( !condition ) {
return false;
}
// add rule
groupArray.push(condition);
},
hasRule: function(){
},
getRule: function( rule, group ){
// defaults
rule = rule || 0;
group = group || 0;
return this.data.groups[ group ][ rule ];
},
removeRule: function(){
}
});
})(jQuery);
(function($, undefined){
var __ = acf.__;
var parseString = function( val ){
return val ? '' + val : '';
};
var isEqualTo = function( v1, v2 ){
return ( parseString(v1).toLowerCase() === parseString(v2).toLowerCase() );
};
var isEqualToNumber = function( v1, v2 ){
return ( parseFloat(v1) === parseFloat(v2) );
};
var isGreaterThan = function( v1, v2 ){
return ( parseFloat(v1) > parseFloat(v2) );
};
var isLessThan = function( v1, v2 ){
return ( parseFloat(v1) < parseFloat(v2) );
};
var inArray = function( v1, array ){
// cast all values as string
array = array.map(function(v2){
return parseString(v2);
});
return (array.indexOf( v1 ) > -1);
}
var containsString = function( haystack, needle ){
return ( parseString(haystack).indexOf( parseString(needle) ) > -1 );
};
var matchesPattern = function( v1, pattern ){
var regexp = new RegExp(parseString(pattern), 'gi');
return parseString(v1).match( regexp );
};
/**
* hasValue
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param void
* @return void
*/
var HasValue = acf.Condition.extend({
type: 'hasValue',
operator: '!=empty',
label: __('Has any value'),
fieldTypes: [ 'text', 'textarea', 'number', 'range', 'email', 'url', 'password', 'image', 'file', 'wysiwyg', 'oembed', 'select', 'checkbox', 'radio', 'button_group', 'link', 'post_object', 'page_link', 'relationship', 'taxonomy', 'user', 'google_map', 'date_picker', 'date_time_picker', 'time_picker', 'color_picker' ],
match: function( rule, field ){
return (field.val() ? true : false);
},
choices: function( fieldObject ){
return '<input type="text" disabled="" />';
}
});
acf.registerConditionType( HasValue );
/**
* hasValue
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param void
* @return void
*/
var HasNoValue = HasValue.extend({
type: 'hasNoValue',
operator: '==empty',
label: __('Has no value'),
match: function( rule, field ){
return !HasValue.prototype.match.apply(this, arguments);
}
});
acf.registerConditionType( HasNoValue );
/**
* EqualTo
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param void
* @return void
*/
var EqualTo = acf.Condition.extend({
type: 'equalTo',
operator: '==',
label: __('Value is equal to'),
fieldTypes: [ 'text', 'textarea', 'number', 'range', 'email', 'url', 'password' ],
match: function( rule, field ){
if( acf.isNumeric(rule.value) ) {
return isEqualToNumber( rule.value, field.val() );
} else {
return isEqualTo( rule.value, field.val() );
}
},
choices: function( fieldObject ){
return '<input type="text" />';
}
});
acf.registerConditionType( EqualTo );
/**
* NotEqualTo
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param void
* @return void
*/
var NotEqualTo = EqualTo.extend({
type: 'notEqualTo',
operator: '!=',
label: __('Value is not equal to'),
match: function( rule, field ){
return !EqualTo.prototype.match.apply(this, arguments);
}
});
acf.registerConditionType( NotEqualTo );
/**
* PatternMatch
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param void
* @return void
*/
var PatternMatch = acf.Condition.extend({
type: 'patternMatch',
operator: '==pattern',
label: __('Value matches pattern'),
fieldTypes: [ 'text', 'textarea', 'email', 'url', 'password', 'wysiwyg' ],
match: function( rule, field ){
return matchesPattern( field.val(), rule.value );
},
choices: function( fieldObject ){
return '<input type="text" placeholder="[a-z0-9]" />';
}
});
acf.registerConditionType( PatternMatch );
/**
* Contains
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param void
* @return void
*/
var Contains = acf.Condition.extend({
type: 'contains',
operator: '==contains',
label: __('Value contains'),
fieldTypes: [ 'text', 'textarea', 'number', 'email', 'url', 'password', 'wysiwyg', 'oembed', 'select' ],
match: function( rule, field ){
return containsString( field.val(), rule.value );
},
choices: function( fieldObject ){
return '<input type="text" />';
}
});
acf.registerConditionType( Contains );
/**
* TrueFalseEqualTo
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param void
* @return void
*/
var TrueFalseEqualTo = EqualTo.extend({
type: 'trueFalseEqualTo',
choiceType: 'select',
fieldTypes: [ 'true_false' ],
choices: function( field ){
return [
{
id: 1,
text: __('Checked')
}
];
},
});
acf.registerConditionType( TrueFalseEqualTo );
/**
* TrueFalseNotEqualTo
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param void
* @return void
*/
var TrueFalseNotEqualTo = NotEqualTo.extend({
type: 'trueFalseNotEqualTo',
choiceType: 'select',
fieldTypes: [ 'true_false' ],
choices: function( field ){
return [
{
id: 1,
text: __('Checked')
}
];
},
});
acf.registerConditionType( TrueFalseNotEqualTo );
/**
* SelectEqualTo
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param void
* @return void
*/
var SelectEqualTo = acf.Condition.extend({
type: 'selectEqualTo',
operator: '==',
label: __('Value is equal to'),
fieldTypes: [ 'select', 'checkbox', 'radio', 'button_group' ],
match: function( rule, field ){
var val = field.val();
if( val instanceof Array ) {
return inArray( rule.value, val );
} else {
return isEqualTo( rule.value, val );
}
},
choices: function( fieldObject ){
// vars
var choices = [];
var lines = fieldObject.$setting('choices textarea').val().split("\n");
// allow null
if( fieldObject.$input('allow_null').prop('checked') ) {
choices.push({
id: '',
text: __('Null')
});
}
// loop
lines.map(function( line ){
// split
line = line.split(':');
// default label to value
line[1] = line[1] || line[0];
// append
choices.push({
id: line[0].trim(),
text: line[1].trim()
});
});
// return
return choices;
},
});
acf.registerConditionType( SelectEqualTo );
/**
* SelectNotEqualTo
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param void
* @return void
*/
var SelectNotEqualTo = SelectEqualTo.extend({
type: 'selectNotEqualTo',
operator: '!=',
label: __('Value is not equal to'),
match: function( rule, field ){
return !SelectEqualTo.prototype.match.apply(this, arguments);
}
});
acf.registerConditionType( SelectNotEqualTo );
/**
* GreaterThan
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param void
* @return void
*/
var GreaterThan = acf.Condition.extend({
type: 'greaterThan',
operator: '>',
label: __('Value is greater than'),
fieldTypes: [ 'number', 'range' ],
match: function( rule, field ){
var val = field.val();
if( val instanceof Array ) {
val = val.length;
}
return isGreaterThan( val, rule.value );
},
choices: function( fieldObject ){
return '<input type="number" />';
}
});
acf.registerConditionType( GreaterThan );
/**
* LessThan
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param void
* @return void
*/
var LessThan = GreaterThan.extend({
type: 'lessThan',
operator: '<',
label: __('Value is less than'),
match: function( rule, field ){
var val = field.val();
if( val instanceof Array ) {
val = val.length;
}
return isLessThan( val, rule.value );
},
choices: function( fieldObject ){
return '<input type="number" />';
}
});
acf.registerConditionType( LessThan );
/**
* SelectedGreaterThan
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param void
* @return void
*/
var SelectionGreaterThan = GreaterThan.extend({
type: 'selectionGreaterThan',
label: __('Selection is greater than'),
fieldTypes: [ 'checkbox', 'select', 'post_object', 'page_link', 'relationship', 'taxonomy', 'user' ],
});
acf.registerConditionType( SelectionGreaterThan );
/**
* SelectedGreaterThan
*
* description
*
* @date 1/2/18
* @since 5.6.5
*
* @param void
* @return void
*/
var SelectionLessThan = LessThan.extend({
type: 'selectionLessThan',
label: __('Selection is less than'),
fieldTypes: [ 'checkbox', 'select', 'post_object', 'page_link', 'relationship', 'taxonomy', 'user' ],
});
acf.registerConditionType( SelectionLessThan );
})(jQuery);
(function($, undefined){
acf.unload = new acf.Model({
wait: 'load',
active: true,
changed: false,
actions: {
'validation_failure': 'startListening',
'validation_success': 'stopListening'
},
events: {
'change form .acf-field': 'startListening',
'submit form': 'stopListening'
},
enable: function(){
this.active = true;
},
disable: function(){
this.active = false;
},
reset: function(){
this.stopListening();
},
startListening: function(){
// bail ealry if already changed, not active
if( this.changed || !this.active ) {
return;
}
// update
this.changed = true;
// add event
$(window).on('beforeunload', this.onUnload);
},
stopListening: function(){
// update
this.changed = false;
// remove event
$(window).off('beforeunload', this.onUnload);
},
onUnload: function(){
return acf.__('The changes you made will be lost if you navigate away from this page');
}
});
})(jQuery);
(function($, undefined){
/**
* postboxManager
*
* Manages postboxes on the screen.
*
* @date 25/5/19
* @since 5.8.1
*
* @param void
* @return void
*/
var postboxManager = new acf.Model({
wait: 'prepare',
priority: 1,
initialize: function(){
(acf.get('postboxes') || []).map( acf.newPostbox );
},
});
/**
* acf.getPostbox
*
* Returns a postbox instance.
*
* @date 23/9/18
* @since 5.7.7
*
* @param mixed $el Either a jQuery element or the postbox id.
* @return object
*/
acf.getPostbox = function( $el ){
// allow string parameter
if( typeof arguments[0] == 'string' ) {
$el = $('#' + arguments[0]);
}
// return instance
return acf.getInstance( $el );
};
/**
* acf.getPostboxes
*
* Returns an array of postbox instances.
*
* @date 23/9/18
* @since 5.7.7
*
* @param void
* @return array
*/
acf.getPostboxes = function(){
return acf.getInstances( $('.acf-postbox') );
};
/**
* acf.newPostbox
*
* Returns a new postbox instance for the given props.
*
* @date 20/9/18
* @since 5.7.6
*
* @param object props The postbox properties.
* @return object
*/
acf.newPostbox = function( props ){
return new acf.models.Postbox( props );
};
/**
* acf.models.Postbox
*
* The postbox model.
*
* @date 20/9/18
* @since 5.7.6
*
* @param void
* @return void
*/
acf.models.Postbox = acf.Model.extend({
data: {
id: '',
key: '',
style: 'default',
label: 'top',
edit: ''
},
setup: function( props ){
// compatibilty
if( props.editLink ) {
props.edit = props.editLink;
}
// extend data
$.extend(this.data, props);
// set $el
this.$el = this.$postbox();
},
$postbox: function(){
return $('#' + this.get('id'));
},
$hide: function(){
return $('#' + this.get('id') + '-hide');
},
$hideLabel: function(){
return this.$hide().parent();
},
$hndle: function(){
return this.$('> .hndle');
},
$handleActions: function(){
return this.$('> .postbox-header .handle-actions');
},
$inside: function(){
return this.$('> .inside');
},
isVisible: function(){
return this.$el.hasClass('acf-hidden');
},
initialize: function(){
// Add default class.
this.$el.addClass('acf-postbox');
// Remove 'hide-if-js class.
// This class is added by WP to postboxes that are hidden via the "Screen Options" tab.
this.$el.removeClass('hide-if-js');
// Add field group style class (ignore in block editor).
if( acf.get('editor') !== 'block' ) {
var style = this.get('style');
if( style !== 'default' ) {
this.$el.addClass( style );
}
}
// Add .inside class.
this.$inside().addClass('acf-fields').addClass('-' + this.get('label'));
// Append edit link.
var edit = this.get('edit');
if( edit ) {
var html = '<a href="' + edit + '" class="dashicons dashicons-admin-generic acf-hndle-cog acf-js-tooltip" title="' + acf.__('Edit field group') + '"></a>';
var $handleActions = this.$handleActions();
if( $handleActions.length ) {
$handleActions.prepend( html );
} else {
this.$hndle().append( html );
}
}
// Show postbox.
this.show();
},
show: function(){
// Show label.
this.$hideLabel().show();
// toggle on checkbox
this.$hide().prop('checked', true);
// Show postbox
this.$el.show().removeClass('acf-hidden');
// Do action.
acf.doAction('show_postbox', this);
},
enable: function(){
acf.enable( this.$el, 'postbox' );
},
showEnable: function(){
this.enable();
this.show();
},
hide: function(){
// Hide label.
this.$hideLabel().hide();
// Hide postbox
this.$el.hide().addClass('acf-hidden');
// Do action.
acf.doAction('hide_postbox', this);
},
disable: function(){
acf.disable( this.$el, 'postbox' );
},
hideDisable: function(){
this.disable();
this.hide();
},
html: function( html ){
// Update HTML.
this.$inside().html( html );
// Do action.
acf.doAction('append', this.$el);
}
});
})(jQuery);
(function($, undefined){
/**
* acf.newMediaPopup
*
* description
*
* @date 10/1/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.newMediaPopup = function( args ){
// args
var popup = null;
var args = acf.parseArgs(args, {
mode: 'select', // 'select', 'edit'
title: '', // 'Upload Image'
button: '', // 'Select Image'
type: '', // 'image', ''
field: false, // field instance
allowedTypes: '', // '.jpg, .png, etc'
library: 'all', // 'all', 'uploadedTo'
multiple: false, // false, true, 'add'
attachment: 0, // the attachment to edit
autoOpen: true, // open the popup automatically
open: function(){}, // callback after close
select: function(){}, // callback after select
close: function(){} // callback after close
});
// initialize
if( args.mode == 'edit' ) {
popup = new acf.models.EditMediaPopup( args );
} else {
popup = new acf.models.SelectMediaPopup( args );
}
// open popup (allow frame customization before opening)
if( args.autoOpen ) {
setTimeout(function(){
popup.open();
}, 1);
}
// action
acf.doAction('new_media_popup', popup);
// return
return popup;
};
/**
* getPostID
*
* description
*
* @date 10/1/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
var getPostID = function() {
var postID = acf.get('post_id');
return acf.isNumeric(postID) ? postID : 0;
}
/**
* acf.getMimeTypes
*
* description
*
* @date 11/1/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.getMimeTypes = function(){
return this.get('mimeTypes');
};
acf.getMimeType = function( name ){
// vars
var allTypes = acf.getMimeTypes();
// search
if( allTypes[name] !== undefined ) {
return allTypes[name];
}
// some types contain a mixed key such as "jpg|jpeg|jpe"
for( var key in allTypes ) {
if( key.indexOf(name) !== -1 ) {
return allTypes[key];
}
}
// return
return false;
};
/**
* MediaPopup
*
* description
*
* @date 10/1/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
var MediaPopup = acf.Model.extend({
id: 'MediaPopup',
data: {},
defaults: {},
frame: false,
setup: function( props ){
$.extend(this.data, props);
},
initialize: function(){
// vars
var options = this.getFrameOptions();
// add states
this.addFrameStates( options );
// create frame
var frame = wp.media( options );
// add args reference
frame.acf = this;
// add events
this.addFrameEvents( frame, options );
// strore frame
this.frame = frame;
},
open: function(){
this.frame.open();
},
close: function(){
this.frame.close();
},
remove: function(){
this.frame.detach();
this.frame.remove();
},
getFrameOptions: function(){
// vars
var options = {
title: this.get('title'),
multiple: this.get('multiple'),
library: {},
states: []
};
// type
if( this.get('type') ) {
options.library.type = this.get('type');
}
// type
if( this.get('library') === 'uploadedTo' ) {
options.library.uploadedTo = getPostID();
}
// attachment
if( this.get('attachment') ) {
options.library.post__in = [ this.get('attachment') ];
}
// button
if( this.get('button') ) {
options.button = {
text: this.get('button')
};
}
// return
return options;
},
addFrameStates: function( options ){
// create query
var Query = wp.media.query( options.library );
// add _acfuploader
// this is super wack!
// if you add _acfuploader to the options.library args, new uploads will not be added to the library view.
// this has been traced back to the wp.media.model.Query initialize function (which can't be overriden)
// Adding any custom args will cause the Attahcments to not observe the uploader queue
// To bypass this security issue, we add in the args AFTER the Query has been initialized
// options.library._acfuploader = settings.field;
if( this.get('field') && acf.isset(Query, 'mirroring', 'args') ) {
Query.mirroring.args._acfuploader = this.get('field');
}
// add states
options.states.push(
// main state
new wp.media.controller.Library({
library: Query,
multiple: this.get('multiple'),
title: this.get('title'),
priority: 20,
filterable: 'all',
editable: true,
allowLocalEdits: true
})
);
// edit image functionality (added in WP 3.9)
if( acf.isset(wp, 'media', 'controller', 'EditImage') ) {
options.states.push( new wp.media.controller.EditImage() );
}
},
addFrameEvents: function( frame, options ){
// log all events
//frame.on('all', function( e ) {
// console.log( 'frame all: %o', e );
//});
// add class
frame.on('open',function() {
this.$el.closest('.media-modal').addClass('acf-media-modal -' + this.acf.get('mode') );
}, frame);
// edit image view
// source: media-views.js:2410 editImageContent()
frame.on('content:render:edit-image', function(){
var image = this.state().get('image');
var view = new wp.media.view.EditImage({ model: image, controller: this }).render();
this.content.set( view );
// after creating the wrapper view, load the actual editor via an ajax call
view.loadEditor();
}, frame);
// update toolbar button
//frame.on( 'toolbar:create:select', function( toolbar ) {
// toolbar.view = new wp.media.view.Toolbar.Select({
// text: frame.options._button,
// controller: this
// });
//}, frame );
// on select
frame.on('select', function() {
// vars
var selection = frame.state().get('selection');
// if selecting images
if( selection ) {
// loop
selection.each(function( attachment, i ){
frame.acf.get('select').apply( frame.acf, [attachment, i] );
});
}
});
// on close
frame.on('close',function(){
// callback and remove
setTimeout(function(){
frame.acf.get('close').apply( frame.acf );
frame.acf.remove();
}, 1);
});
}
});
/**
* acf.models.SelectMediaPopup
*
* description
*
* @date 10/1/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.models.SelectMediaPopup = MediaPopup.extend({
id: 'SelectMediaPopup',
setup: function( props ){
// default button
if( !props.button ) {
props.button = acf._x('Select', 'verb');
}
// parent
MediaPopup.prototype.setup.apply(this, arguments);
},
addFrameEvents: function( frame, options ){
// plupload
// adds _acfuploader param to validate uploads
if( acf.isset(_wpPluploadSettings, 'defaults', 'multipart_params') ) {
// add _acfuploader so that Uploader will inherit
_wpPluploadSettings.defaults.multipart_params._acfuploader = this.get('field');
// remove acf_field so future Uploaders won't inherit
frame.on('open', function(){
delete _wpPluploadSettings.defaults.multipart_params._acfuploader;
});
}
// browse
frame.on('content:activate:browse', function(){
// vars
var toolbar = false;
// populate above vars making sure to allow for failure
// perhaps toolbar does not exist because the frame open is Upload Files
try {
toolbar = frame.content.get().toolbar;
} catch(e) {
console.log(e);
return;
}
// callback
frame.acf.customizeFilters.apply(frame.acf, [toolbar]);
});
// parent
MediaPopup.prototype.addFrameEvents.apply(this, arguments);
},
customizeFilters: function( toolbar ){
// vars
var filters = toolbar.get('filters');
// image
if( this.get('type') == 'image' ) {
// update all
filters.filters.all.text = acf.__('All images');
// remove some filters
delete filters.filters.audio;
delete filters.filters.video;
delete filters.filters.image;
// update all filters to show images
$.each(filters.filters, function( i, filter ){
filter.props.type = filter.props.type || 'image';
});
}
// specific types
if( this.get('allowedTypes') ) {
// convert ".jpg, .png" into ["jpg", "png"]
var allowedTypes = this.get('allowedTypes').split(' ').join('').split('.').join('').split(',');
// loop
allowedTypes.map(function( name ){
// get type
var mimeType = acf.getMimeType( name );
// bail early if no type
if( !mimeType ) return;
// create new filter
var newFilter = {
text: mimeType,
props: {
status: null,
type: mimeType,
uploadedTo: null,
orderby: 'date',
order: 'DESC'
},
priority: 20
};
// append
filters.filters[ mimeType ] = newFilter;
});
}
// uploaded to post
if( this.get('library') === 'uploadedTo' ) {
// vars
var uploadedTo = this.frame.options.library.uploadedTo;
// remove some filters
delete filters.filters.unattached;
delete filters.filters.uploaded;
// add uploadedTo to filters
$.each(filters.filters, function( i, filter ){
filter.text += ' (' + acf.__('Uploaded to this post') + ')';
filter.props.uploadedTo = uploadedTo;
});
}
// add _acfuploader to filters
var field = this.get('field');
$.each(filters.filters, function( k, filter ){
filter.props._acfuploader = field;
});
// add _acfuplaoder to search
var search = toolbar.get('search');
search.model.attributes._acfuploader = field;
// render (custom function added to prototype)
if( filters.renderFilters ) {
filters.renderFilters();
}
}
});
/**
* acf.models.EditMediaPopup
*
* description
*
* @date 10/1/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.models.EditMediaPopup = MediaPopup.extend({
id: 'SelectMediaPopup',
setup: function( props ){
// default button
if( !props.button ) {
props.button = acf._x('Update', 'verb');
}
// parent
MediaPopup.prototype.setup.apply(this, arguments);
},
addFrameEvents: function( frame, options ){
// add class
frame.on('open',function() {
// add class
this.$el.closest('.media-modal').addClass('acf-expanded');
// set to browse
if( this.content.mode() != 'browse' ) {
this.content.mode('browse');
}
// set selection
var state = this.state();
var selection = state.get('selection');
var attachment = wp.media.attachment( frame.acf.get('attachment') );
selection.add( attachment );
}, frame);
// parent
MediaPopup.prototype.addFrameEvents.apply(this, arguments);
}
});
/**
* customizePrototypes
*
* description
*
* @date 11/1/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
var customizePrototypes = new acf.Model({
id: 'customizePrototypes',
wait: 'ready',
initialize: function(){
// bail early if no media views
if( !acf.isset(window, 'wp', 'media', 'view') ) {
return;
}
// fix bug where CPT without "editor" does not set post.id setting which then prevents uploadedTo from working
var postID = getPostID();
if( postID && acf.isset(wp, 'media', 'view', 'settings', 'post') ) {
wp.media.view.settings.post.id = postID;
}
// customize
this.customizeAttachmentsButton();
this.customizeAttachmentsRouter();
this.customizeAttachmentFilters();
this.customizeAttachmentCompat();
this.customizeAttachmentLibrary();
},
customizeAttachmentsButton: function(){
// validate
if( !acf.isset(wp, 'media', 'view', 'Button') ) {
return;
}
// Extend
var Button = wp.media.view.Button;
wp.media.view.Button = Button.extend({
// Fix bug where "Select" button appears blank after editing an image.
// Do this by simplifying Button initialize function and avoid deleting this.options.
initialize: function() {
var options = _.defaults( this.options, this.defaults );
this.model = new Backbone.Model( options );
this.listenTo( this.model, 'change', this.render );
}
});
},
customizeAttachmentsRouter: function(){
// validate
if( !acf.isset(wp, 'media', 'view', 'Router') ) {
return;
}
// vars
var Parent = wp.media.view.Router;
// extend
wp.media.view.Router = Parent.extend({
addExpand: function(){
// vars
var $a = $([
'<a href="#" class="acf-expand-details">',
'<span class="is-closed"><i class="acf-icon -left -small"></i>' + acf.__('Expand Details') + '</span>',
'<span class="is-open"><i class="acf-icon -right -small"></i>' + acf.__('Collapse Details') + '</span>',
'</a>'
].join(''));
// add events
$a.on('click', function( e ){
e.preventDefault();
var $div = $(this).closest('.media-modal');
if( $div.hasClass('acf-expanded') ) {
$div.removeClass('acf-expanded');
} else {
$div.addClass('acf-expanded');
}
});
// append
this.$el.append( $a );
},
initialize: function(){
// initialize
Parent.prototype.initialize.apply( this, arguments );
// add buttons
this.addExpand();
// return
return this;
}
});
},
customizeAttachmentFilters: function(){
// validate
if( !acf.isset(wp, 'media', 'view', 'AttachmentFilters', 'All') ) {
return;
}
// vars
var Parent = wp.media.view.AttachmentFilters.All;
// renderFilters
// copied from media-views.js:6939
Parent.prototype.renderFilters = function(){
// Build `<option>` elements.
this.$el.html( _.chain( this.filters ).map( function( filter, value ) {
return {
el: $( '<option></option>' ).val( value ).html( filter.text )[0],
priority: filter.priority || 50
};
}, this ).sortBy('priority').pluck('el').value() );
};
},
customizeAttachmentCompat: function(){
// validate
if( !acf.isset(wp, 'media', 'view', 'AttachmentCompat') ) {
return;
}
// vars
var AttachmentCompat = wp.media.view.AttachmentCompat;
var timeout = false;
// extend
wp.media.view.AttachmentCompat = AttachmentCompat.extend({
render: function() {
// WP bug
// When multiple media frames exist on the same page (WP content, WYSIWYG, image, file ),
// WP creates multiple instances of this AttachmentCompat view.
// Each instance will attempt to render when a new modal is created.
// Use a property to avoid this and only render once per instance.
if( this.rendered ) {
return this;
}
// render HTML
AttachmentCompat.prototype.render.apply( this, arguments );
// when uploading, render is called twice.
// ignore first render by checking for #acf-form-data element
if( !this.$('#acf-form-data').length ) {
return this;
}
// clear timeout
clearTimeout( timeout );
// setTimeout
timeout = setTimeout($.proxy(function(){
this.rendered = true;
acf.doAction('append', this.$el);
}, this), 50);
// return
return this;
},
save: function( event ) {
var data = {};
if ( event ) {
event.preventDefault();
}
//_.each( this.$el.serializeArray(), function( pair ) {
// data[ pair.name ] = pair.value;
//});
// Serialize data more thoroughly to allow chckbox inputs to save.
data = acf.serializeForAjax(this.$el);
this.controller.trigger( 'attachment:compat:waiting', ['waiting'] );
this.model.saveCompat( data ).always( _.bind( this.postSave, this ) );
}
});
},
customizeAttachmentLibrary: function(){
// validate
if( !acf.isset(wp, 'media', 'view', 'Attachment', 'Library') ) {
return;
}
// vars
var AttachmentLibrary = wp.media.view.Attachment.Library;
// extend
wp.media.view.Attachment.Library = AttachmentLibrary.extend({
render: function() {
// vars
var popup = acf.isget(this, 'controller', 'acf');
var attributes = acf.isget(this, 'model', 'attributes');
// check vars exist to avoid errors
if( popup && attributes ) {
// show errors
if( attributes.acf_errors ) {
this.$el.addClass('acf-disabled');
}
// disable selected
var selected = popup.get('selected');
if( selected && selected.indexOf(attributes.id) > -1 ) {
this.$el.addClass('acf-selected');
}
}
// render
return AttachmentLibrary.prototype.render.apply( this, arguments );
},
/*
* toggleSelection
*
* This function is called before an attachment is selected
* A good place to check for errors and prevent the 'select' function from being fired
*
* @type function
* @date 29/09/2016
* @since 5.4.0
*
* @param options (object)
* @return n/a
*/
toggleSelection: function( options ) {
// vars
// source: wp-includes/js/media-views.js:2880
var collection = this.collection,
selection = this.options.selection,
model = this.model,
single = selection.single();
// vars
var frame = this.controller;
var errors = acf.isget(this, 'model', 'attributes', 'acf_errors');
var $sidebar = frame.$el.find('.media-frame-content .media-sidebar');
// remove previous error
$sidebar.children('.acf-selection-error').remove();
// show attachment details
$sidebar.children().removeClass('acf-hidden');
// add message
if( frame && errors ) {
// vars
var filename = acf.isget(this, 'model', 'attributes', 'filename');
// hide attachment details
// Gallery field continues to show previously selected attachment...
$sidebar.children().addClass('acf-hidden');
// append message
$sidebar.prepend([
'<div class="acf-selection-error">',
'<span class="selection-error-label">' + acf.__('Restricted') +'</span>',
'<span class="selection-error-filename">' + filename + '</span>',
'<span class="selection-error-message">' + errors + '</span>',
'</div>'
].join(''));
// reset selection (unselects all attachments)
selection.reset();
// set single (attachment displayed in sidebar)
selection.single( model );
// return and prevent 'select' form being fired
return;
}
// return
return AttachmentLibrary.prototype.toggleSelection.apply( this, arguments );
}
});
}
});
})(jQuery);
(function($, undefined){
acf.screen = new acf.Model({
active: true,
xhr: false,
timeout: false,
wait: 'load',
events: {
'change #page_template': 'onChange',
'change #parent_id': 'onChange',
'change #post-formats-select': 'onChange',
'change .categorychecklist': 'onChange',
'change .tagsdiv': 'onChange',
'change .acf-taxonomy-field[data-save="1"]': 'onChange',
'change #product-type': 'onChange'
},
isPost: function(){
return acf.get('screen') === 'post';
},
isUser: function(){
return acf.get('screen') === 'user';
},
isTaxonomy: function(){
return acf.get('screen') === 'taxonomy';
},
isAttachment: function(){
return acf.get('screen') === 'attachment';
},
isNavMenu: function(){
return acf.get('screen') === 'nav_menu';
},
isWidget: function(){
return acf.get('screen') === 'widget';
},
isComment: function(){
return acf.get('screen') === 'comment';
},
getPageTemplate: function(){
var $el = $('#page_template');
return $el.length ? $el.val() : null;
},
getPageParent: function( e, $el ){
var $el = $('#parent_id');
return $el.length ? $el.val() : null;
},
getPageType: function( e, $el ){
return this.getPageParent() ? 'child' : 'parent';
},
getPostType: function(){
return $('#post_type').val();
},
getPostFormat: function( e, $el ){
var $el = $('#post-formats-select input:checked');
if( $el.length ) {
var val = $el.val();
return (val == '0') ? 'standard' : val;
}
return null;
},
getPostCoreTerms: function(){
// vars
var terms = {};
// serialize WP taxonomy postboxes
var data = acf.serialize( $('.categorydiv, .tagsdiv') );
// use tax_input (tag, custom-taxonomy) when possible.
// this data is already formatted in taxonomy => [terms].
if( data.tax_input ) {
terms = data.tax_input;
}
// append "category" which uses a different name
if( data.post_category ) {
terms.category = data.post_category;
}
// convert any string values (tags) into array format
for( var tax in terms ) {
if( !acf.isArray(terms[tax]) ) {
terms[tax] = terms[tax].split(/,[\s]?/);
}
}
// return
return terms;
},
getPostTerms: function(){
// Get core terms.
var terms = this.getPostCoreTerms();
// loop over taxonomy fields and add their values
acf.getFields({type: 'taxonomy'}).map(function( field ){
// ignore fields that don't save
if( !field.get('save') ) {
return;
}
// vars
var val = field.val();
var tax = field.get('taxonomy');
// check val
if( val ) {
// ensure terms exists
terms[ tax ] = terms[ tax ] || [];
// ensure val is an array
val = acf.isArray(val) ? val : [val];
// append
terms[ tax ] = terms[ tax ].concat( val );
}
});
// add WC product type
if( (productType = this.getProductType()) !== null ) {
terms.product_type = [productType];
}
// remove duplicate values
for( var tax in terms ) {
terms[tax] = acf.uniqueArray(terms[tax]);
}
// return
return terms;
},
getProductType: function(){
var $el = $('#product-type');
return $el.length ? $el.val() : null;
},
check: function(){
// bail early if not for post
if( acf.get('screen') !== 'post' ) {
return;
}
// abort XHR if is already loading AJAX data
if( this.xhr ) {
this.xhr.abort();
}
// vars
var ajaxData = acf.parseArgs(this.data, {
action: 'acf/ajax/check_screen',
screen: acf.get('screen'),
exists: []
});
// post id
if( this.isPost() ) {
ajaxData.post_id = acf.get('post_id');
}
// post type
if( (postType = this.getPostType()) !== null ) {
ajaxData.post_type = postType;
}
// page template
if( (pageTemplate = this.getPageTemplate()) !== null ) {
ajaxData.page_template = pageTemplate;
}
// page parent
if( (pageParent = this.getPageParent()) !== null ) {
ajaxData.page_parent = pageParent;
}
// page type
if( (pageType = this.getPageType()) !== null ) {
ajaxData.page_type = pageType;
}
// post format
if( (postFormat = this.getPostFormat()) !== null ) {
ajaxData.post_format = postFormat;
}
// post terms
if( (postTerms = this.getPostTerms()) !== null ) {
ajaxData.post_terms = postTerms;
}
// add array of existing postboxes to increase performance and reduce JSON HTML
acf.getPostboxes().map(function( postbox ){
ajaxData.exists.push( postbox.get('key') );
});
// filter
ajaxData = acf.applyFilters('check_screen_args', ajaxData);
// success
var onSuccess = function( json ){
// Render post screen.
if( acf.get('screen') == 'post' ) {
this.renderPostScreen( json );
// Render user screen.
} else if( acf.get('screen') == 'user' ) {
this.renderUserScreen( json );
}
// action
acf.doAction('check_screen_complete', json, ajaxData);
};
// ajax
this.xhr = $.ajax({
url: acf.get('ajaxurl'),
data: acf.prepareForAjax( ajaxData ),
type: 'post',
dataType: 'json',
context: this,
success: onSuccess
});
},
onChange: function( e, $el ){
this.setTimeout(this.check, 1);
},
renderPostScreen: function( data ){
// Helper function to copy events
var copyEvents = function( $from, $to ){
var events = $._data($from[0]).events;
for( var type in events ) {
for( var i = 0; i < events[type].length; i++ ) {
$to.on( type, events[type][i].handler );
}
}
}
// Helper function to sort metabox.
var sortMetabox = function( id, ids ){
// Find position of id within ids.
var index = ids.indexOf( id );
// Bail early if index not found.
if( index == -1 ) {
return false;
}
// Loop over metaboxes behind (in reverse order).
for( var i = index-1; i >= 0; i-- ) {
if( $('#'+ids[i]).length ) {
return $('#'+ids[i]).after( $('#'+id) );
}
}
// Loop over metaboxes infront.
for( var i = index+1; i < ids.length; i++ ) {
if( $('#'+ids[i]).length ) {
return $('#'+ids[i]).before( $('#'+id) );
}
}
// Return false if not sorted.
return false;
};
// Keep track of visible and hidden postboxes.
data.visible = [];
data.hidden = [];
// Show these postboxes.
data.results = data.results.map(function( result, i ){
// vars
var postbox = acf.getPostbox( result.id );
// Prevent "acf_after_title" position in Block Editor.
if( acf.isGutenberg() && result.position == "acf_after_title" ) {
result.position = 'normal';
}
// Create postbox if doesn't exist.
if( !postbox ) {
var wpMinorVersion = parseFloat( acf.get('wp_version') );
if( wpMinorVersion >= 5.5 ) {
var postboxHeader = [
'<div class="postbox-header">',
'<h2 class="hndle ui-sortable-handle">',
'<span>' + acf.escHtml( result.title ) + '</span>',
'</h2>',
'<div class="handle-actions hide-if-no-js">',
'<button type="button" class="handlediv" aria-expanded="true">',
'<span class="screen-reader-text">Toggle panel: ' + acf.escHtml( result.title ) + '</span>',
'<span class="toggle-indicator" aria-hidden="true"></span>',
'</button>',
'</div>',
'</div>'
].join('');
} else {
var postboxHeader = [
'<button type="button" class="handlediv" aria-expanded="true">',
'<span class="screen-reader-text">Toggle panel: ' + acf.escHtml( result.title ) + '</span>',
'<span class="toggle-indicator" aria-hidden="true"></span>',
'</button>',
'<h2 class="hndle ui-sortable-handle">',
'<span>' + acf.escHtml( result.title ) + '</span>',
'</h2>',
].join('');
}
// Create it.
var $postbox = $([
'<div id="' + result.id + '" class="postbox">',
postboxHeader,
'<div class="inside">',
result.html,
'</div>',
'</div>'
].join(''));
// Create new hide toggle.
if( $('#adv-settings').length ) {
var $prefs = $('#adv-settings .metabox-prefs');
var $label = $([
'<label for="' + result.id + '-hide">',
'<input class="hide-postbox-tog" name="' + result.id + '-hide" type="checkbox" id="' + result.id + '-hide" value="' + result.id + '" checked="checked">',
' ' + result.title,
'</label>'
].join(''));
// Copy default WP events onto checkbox.
copyEvents( $prefs.find('input').first(), $label.find('input') );
// Append hide label
$prefs.append( $label );
}
// Copy default WP events onto metabox.
if( $('.postbox').length ) {
copyEvents( $('.postbox .handlediv').first(), $postbox.children('.handlediv') );
copyEvents( $('.postbox .hndle').first(), $postbox.children('.hndle') );
}
// Append metabox to the bottom of "side-sortables".
if( result.position === 'side' ) {
$('#' + result.position + '-sortables').append( $postbox );
// Prepend metabox to the top of "normal-sortbables".
} else {
$('#' + result.position + '-sortables').prepend( $postbox );
}
// Position metabox amongst existing ACF metaboxes within the same location.
var order = [];
data.results.map(function( _result ){
if( result.position === _result.position && $('#' + result.position + '-sortables #' + _result.id).length ) {
order.push( _result.id );
}
});
sortMetabox(result.id, order)
// Check 'sorted' for user preference.
if( data.sorted ) {
// Loop over each position (acf_after_title, side, normal).
for( var position in data.sorted ) {
// Explode string into array of ids.
var order = data.sorted[position].split(',');
// Position metabox relative to order.
if( sortMetabox(result.id, order) ) {
break;
}
}
}
// Initalize it (modifies HTML).
postbox = acf.newPostbox( result );
// Trigger action.
acf.doAction('append', $postbox);
acf.doAction('append_postbox', postbox);
}
// show postbox
postbox.showEnable();
// append
data.visible.push( result.id );
// Return result (may have changed).
return result;
});
// Hide these postboxes.
acf.getPostboxes().map(function( postbox ){
if( data.visible.indexOf( postbox.get('id') ) === -1 ) {
// Hide postbox.
postbox.hideDisable();
// Append to data.
data.hidden.push( postbox.get('id') );
}
});
// Update style.
$('#acf-style').html( data.style );
// Do action.
acf.doAction( 'refresh_post_screen', data );
},
renderUserScreen: function( json ){
}
});
/**
* gutenScreen
*
* Adds compatibility with the Gutenberg edit screen.
*
* @date 11/12/18
* @since 5.8.0
*
* @param void
* @return void
*/
var gutenScreen = new acf.Model({
// Keep a reference to the most recent post attributes.
postEdits: {},
// Wait until assets have been loaded.
wait: 'prepare',
initialize: function(){
// Bail early if not Gutenberg.
if( !acf.isGutenberg() ) {
return;
}
// Listen for changes (use debounced version as this can fires often).
wp.data.subscribe( acf.debounce(this.onChange).bind(this) );
// Customize "acf.screen.get" functions.
acf.screen.getPageTemplate = this.getPageTemplate;
acf.screen.getPageParent = this.getPageParent;
acf.screen.getPostType = this.getPostType;
acf.screen.getPostFormat = this.getPostFormat;
acf.screen.getPostCoreTerms = this.getPostCoreTerms;
// Disable unload
acf.unload.disable();
// Refresh metaboxes since WP 5.3.
var wpMinorVersion = parseFloat( acf.get('wp_version') );
if( wpMinorVersion >= 5.3 ) {
this.addAction( 'refresh_post_screen', this.onRefreshPostScreen );
}
// Trigger "refresh" after WP has moved metaboxes into place.
wp.domReady( acf.refresh );
},
onChange: function(){
// Determine attributes that can trigger a refresh.
var attributes = [ 'template', 'parent', 'format' ];
// Append taxonomy attribute names to this list.
( wp.data.select( 'core' ).getTaxonomies() || [] ).map(function( taxonomy ){
attributes.push( taxonomy.rest_base );
});
// Get relevant current post edits.
var _postEdits = wp.data.select( 'core/editor' ).getPostEdits();
var postEdits = {};
attributes.map(function( k ){
if( _postEdits[k] !== undefined ) {
postEdits[k] = _postEdits[k];
}
});
// Detect change.
if( JSON.stringify(postEdits) !== JSON.stringify(this.postEdits) ) {
this.postEdits = postEdits;
// Check screen.
acf.screen.check();
}
},
getPageTemplate: function(){
return wp.data.select( 'core/editor' ).getEditedPostAttribute( 'template' );
},
getPageParent: function( e, $el ){
return wp.data.select( 'core/editor' ).getEditedPostAttribute( 'parent' );
},
getPostType: function(){
return wp.data.select( 'core/editor' ).getEditedPostAttribute( 'type' );
},
getPostFormat: function( e, $el ){
return wp.data.select( 'core/editor' ).getEditedPostAttribute( 'format' );
},
getPostCoreTerms: function(){
// vars
var terms = {};
// Loop over taxonomies.
var taxonomies = wp.data.select( 'core' ).getTaxonomies() || [];
taxonomies.map(function( taxonomy ){
// Append selected taxonomies to terms object.
var postTerms = wp.data.select( 'core/editor' ).getEditedPostAttribute( taxonomy.rest_base );
if( postTerms ) {
terms[ taxonomy.slug ] = postTerms;
}
});
// return
return terms;
},
/**
* onRefreshPostScreen
*
* Fires after the Post edit screen metaboxs are refreshed to update the Block Editor API state.
*
* @date 11/11/19
* @since 5.8.7
*
* @param object data The "check_screen" JSON response data.
* @return void
*/
onRefreshPostScreen: function( data ) {
// Extract vars.
var select = wp.data.select( 'core/edit-post' );
var dispatch = wp.data.dispatch( 'core/edit-post' );
// Load current metabox locations and data.
var locations = {};
select.getActiveMetaBoxLocations().map(function( location ){
locations[ location ] = select.getMetaBoxesPerLocation( location );
});
// Generate flat array of existing ids.
var ids = [];
for( var k in locations ) {
locations[k].map(function( m ){
ids.push( m.id );
});
}
// Append new ACF metaboxes (ignore those which already exist).
data.results.filter(function( r ){
return ( ids.indexOf( r.id ) === -1 );
}).map(function( result, i ){
// Ensure location exists.
var location = result.position;
locations[ location ] = locations[ location ] || [];
// Append.
locations[ location ].push({
id: result.id,
title: result.title
});
});
// Remove hidden ACF metaboxes.
for( var k in locations ) {
locations[k] = locations[k].filter(function( m ){
return ( data.hidden.indexOf( m.id ) === -1 );
});
}
// Update state.
dispatch.setAvailableMetaBoxesPerLocation( locations );
}
});
})(jQuery);
(function($, undefined){
/**
* acf.newSelect2
*
* description
*
* @date 13/1/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.newSelect2 = function( $select, props ){
// defaults
props = acf.parseArgs(props, {
allowNull: false,
placeholder: '',
multiple: false,
field: false,
ajax: false,
ajaxAction: '',
ajaxData: function( data ){ return data; },
ajaxResults: function( json ){ return json; },
});
// initialize
if( getVersion() == 4 ) {
var select2 = new Select2_4( $select, props );
} else {
var select2 = new Select2_3( $select, props );
}
// actions
acf.doAction('new_select2', select2);
// return
return select2;
};
/**
* getVersion
*
* description
*
* @date 13/1/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
function getVersion() {
// v4
if( acf.isset(window, 'jQuery', 'fn', 'select2', 'amd') ) {
return 4;
}
// v3
if( acf.isset(window, 'Select2') ) {
return 3;
}
// return
return false;
}
/**
* Select2
*
* description
*
* @date 13/1/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
var Select2 = acf.Model.extend({
setup: function( $select, props ){
$.extend(this.data, props);
this.$el = $select;
},
initialize: function(){
},
selectOption: function( value ){
var $option = this.getOption( value );
if( !$option.prop('selected') ) {
$option.prop('selected', true).trigger('change');
}
},
unselectOption: function( value ){
var $option = this.getOption( value );
if( $option.prop('selected') ) {
$option.prop('selected', false).trigger('change');
}
},
getOption: function( value ){
return this.$('option[value="' + value + '"]');
},
addOption: function( option ){
// defaults
option = acf.parseArgs(option, {
id: '',
text: '',
selected: false
});
// vars
var $option = this.getOption( option.id );
// append
if( !$option.length ) {
$option = $('<option></option>');
$option.html( option.text );
$option.attr('value', option.id);
$option.prop('selected', option.selected);
this.$el.append($option);
}
// chain
return $option;
},
getValue: function(){
// vars
var val = [];
var $options = this.$el.find('option:selected');
// bail early if no selected
if( !$options.exists() ) {
return val;
}
// sort by attribute
$options = $options.sort(function(a, b) {
return +a.getAttribute('data-i') - +b.getAttribute('data-i');
});
// loop
$options.each(function(){
var $el = $(this);
val.push({
$el: $el,
id: $el.attr('value'),
text: $el.text(),
});
});
// return
return val;
},
mergeOptions: function(){
},
getChoices: function(){
// callback
var crawl = function( $parent ){
// vars
var choices = [];
// loop
$parent.children().each(function(){
// vars
var $child = $(this);
// optgroup
if( $child.is('optgroup') ) {
choices.push({
text: $child.attr('label'),
children: crawl( $child )
});
// option
} else {
choices.push({
id: $child.attr('value'),
text: $child.text()
});
}
});
// return
return choices;
};
// crawl
return crawl( this.$el );
},
getAjaxData: function( params ){
// vars
var ajaxData = {
action: this.get('ajaxAction'),
s: params.term || '',
paged: params.page || 1
};
// field helper
var field = this.get('field');
if( field ) {
ajaxData.field_key = field.get('key');
}
// callback
var callback = this.get('ajaxData');
if( callback ) {
ajaxData = callback.apply( this, [ajaxData, params] );
}
// filter
ajaxData = acf.applyFilters( 'select2_ajax_data', ajaxData, this.data, this.$el, (field || false), this );
// return
return acf.prepareForAjax(ajaxData);
},
getAjaxResults: function( json, params ){
// defaults
json = acf.parseArgs(json, {
results: false,
more: false,
});
// callback
var callback = this.get('ajaxResults');
if( callback ) {
json = callback.apply( this, [json, params] );
}
// filter
json = acf.applyFilters( 'select2_ajax_results', json, params, this );
// return
return json;
},
processAjaxResults: function( json, params ){
// vars
var json = this.getAjaxResults( json, params );
// change more to pagination
if( json.more ) {
json.pagination = { more: true };
}
// merge together groups
setTimeout($.proxy(this.mergeOptions, this), 1);
// return
return json;
},
destroy: function(){
// destroy via api
if( this.$el.data('select2') ) {
this.$el.select2('destroy');
}
// destory via HTML (duplicating HTML does not contain data)
this.$el.siblings('.select2-container').remove();
}
});
/**
* Select2_4
*
* description
*
* @date 13/1/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
var Select2_4 = Select2.extend({
initialize: function(){
// vars
var $select = this.$el;
var options = {
width: '100%',
allowClear: this.get('allowNull'),
placeholder: this.get('placeholder'),
multiple: this.get('multiple'),
data: [],
escapeMarkup: function( string ){
return acf.escHtml( string );
},
};
// multiple
if( options.multiple ) {
// reorder options
this.getValue().map(function( item ){
item.$el.detach().appendTo( $select );
});
}
// Temporarily remove conflicting attribute.
var attrAjax = $select.attr( 'data-ajax' );
if( attrAjax !== undefined ) {
$select.removeData('ajax');
$select.removeAttr('data-ajax');
}
// ajax
if( this.get('ajax') ) {
options.ajax = {
url: acf.get('ajaxurl'),
delay: 250,
dataType: 'json',
type: 'post',
cache: false,
data: $.proxy(this.getAjaxData, this),
processResults: $.proxy(this.processAjaxResults, this),
};
}
// filter for 3rd party customization
//options = acf.applyFilters( 'select2_args', options, $select, this );
var field = this.get('field');
options = acf.applyFilters( 'select2_args', options, $select, this.data, (field || false), this );
// add select2
$select.select2( options );
// get container (Select2 v4 does not return this from constructor)
var $container = $select.next('.select2-container');
// multiple
if( options.multiple ) {
// vars
var $ul = $container.find('ul');
// sortable
$ul.sortable({
stop: function( e ) {
// loop
$ul.find('.select2-selection__choice').each(function() {
// vars
var $option = $( $(this).data('data').element );
// detach and re-append to end
$option.detach().appendTo( $select );
});
// trigger change on input (JS error if trigger on select)
$select.trigger('change');
}
});
// on select, move to end
$select.on('select2:select', this.proxy(function( e ){
this.getOption( e.params.data.id ).detach().appendTo( this.$el );
}));
}
// add class
$container.addClass('-acf');
// Add back temporarily removed attr.
if( attrAjax !== undefined ) {
$select.attr('data-ajax', attrAjax);
}
// action for 3rd party customization
acf.doAction('select2_init', $select, options, this.data, (field || false), this);
},
mergeOptions: function(){
// vars
var $prevOptions = false;
var $prevGroup = false;
// loop
$('.select2-results__option[role="group"]').each(function(){
// vars
var $options = $(this).children('ul');
var $group = $(this).children('strong');
// compare to previous
if( $prevGroup && $prevGroup.text() === $group.text() ) {
$prevOptions.append( $options.children() );
$(this).remove();
return;
}
// update vars
$prevOptions = $options;
$prevGroup = $group;
});
},
});
/**
* Select2_3
*
* description
*
* @date 13/1/18
* @since 5.6.5
*
* @param type $var Description. Default.
* @return type Description.
*/
var Select2_3 = Select2.extend({
initialize: function(){
// vars
var $select = this.$el;
var value = this.getValue();
var multiple = this.get('multiple');
var options = {
width: '100%',
allowClear: this.get('allowNull'),
placeholder: this.get('placeholder'),
separator: '||',
multiple: this.get('multiple'),
data: this.getChoices(),
escapeMarkup: function( string ){
return acf.escHtml( string );
},
dropdownCss: {
'z-index': '999999999'
},
initSelection: function( element, callback ) {
if( multiple ) {
callback( value );
} else {
callback( value.shift() );
}
}
};
// get hidden input
var $input = $select.siblings('input');
if( !$input.length ) {
$input = $('<input type="hidden" />');
$select.before( $input );
}
// set input value
inputValue = value.map(function(item){ return item.id }).join('||');
$input.val( inputValue );
// multiple
if( options.multiple ) {
// reorder options
value.map(function( item ){
item.$el.detach().appendTo( $select );
});
}
// remove blank option as we have a clear all button
if( options.allowClear ) {
options.data = options.data.filter(function(item){
return item.id !== '';
});
}
// remove conflicting atts
$select.removeData('ajax');
$select.removeAttr('data-ajax');
// ajax
if( this.get('ajax') ) {
options.ajax = {
url: acf.get('ajaxurl'),
quietMillis: 250,
dataType: 'json',
type: 'post',
cache: false,
data: $.proxy(this.getAjaxData, this),
results: $.proxy(this.processAjaxResults, this),
};
}
// filter for 3rd party customization
var field = this.get('field');
options = acf.applyFilters( 'select2_args', options, $select, this.data, (field || false), this );
// add select2
$input.select2( options );
// get container
var $container = $input.select2('container');
// helper to find this select's option
var getOption = $.proxy(this.getOption, this);
// multiple
if( options.multiple ) {
// vars
var $ul = $container.find('ul');
// sortable
$ul.sortable({
stop: function() {
// loop
$ul.find('.select2-search-choice').each(function() {
// vars
var data = $(this).data('select2Data');
var $option = getOption( data.id );
// detach and re-append to end
$option.detach().appendTo( $select );
});
// trigger change on input (JS error if trigger on select)
$select.trigger('change');
}
});
}
// on select, create option and move to end
$input.on('select2-selecting', function( e ){
// vars
var item = e.choice;
var $option = getOption( item.id );
// create if doesn't exist
if( !$option.length ) {
$option = $('<option value="' + item.id + '">' + item.text + '</option>');
}
// detach and re-append to end
$option.detach().appendTo( $select );
});
// add class
$container.addClass('-acf');
// action for 3rd party customization
acf.doAction('select2_init', $select, options, this.data, (field || false), this);
// change
$input.on('change', function(){
var val = $input.val();
if( val.indexOf('||') ) {
val = val.split('||');
}
$select.val( val ).trigger('change');
});
// hide select
$select.hide();
},
mergeOptions: function(){
// vars
var $prevOptions = false;
var $prevGroup = false;
// loop
$('#select2-drop .select2-result-with-children').each(function(){
// vars
var $options = $(this).children('ul');
var $group = $(this).children('.select2-result-label');
// compare to previous
if( $prevGroup && $prevGroup.text() === $group.text() ) {
$prevGroup.append( $options.children() );
$(this).remove();
return;
}
// update vars
$prevOptions = $options;
$prevGroup = $group;
});
},
getAjaxData: function( term, page ){
// create Select2 v4 params
var params = {
term: term,
page: page
}
// return
return Select2.prototype.getAjaxData.apply(this, [params]);
},
});
// manager
var select2Manager = new acf.Model({
priority: 5,
wait: 'prepare',
actions: {
'duplicate': 'onDuplicate'
},
initialize: function(){
// vars
var locale = acf.get('locale');
var rtl = acf.get('rtl');
var l10n = acf.get('select2L10n');
var version = getVersion();
// bail ealry if no l10n
if( !l10n ) {
return false;
}
// bail early if 'en'
if( locale.indexOf('en') === 0 ) {
return false;
}
// initialize
if( version == 4 ) {
this.addTranslations4();
} else if( version == 3 ) {
this.addTranslations3();
}
},
addTranslations4: function(){
// vars
var l10n = acf.get('select2L10n');
var locale = acf.get('locale');
// modify local to match html[lang] attribute (used by Select2)
locale = locale.replace('_', '-');
// select2L10n
var select2L10n = {
errorLoading: function () {
return l10n.load_fail;
},
inputTooLong: function (args) {
var overChars = args.input.length - args.maximum;
if( overChars > 1 ) {
return l10n.input_too_long_n.replace( '%d', overChars );
}
return l10n.input_too_long_1;
},
inputTooShort: function( args ){
var remainingChars = args.minimum - args.input.length;
if( remainingChars > 1 ) {
return l10n.input_too_short_n.replace( '%d', remainingChars );
}
return l10n.input_too_short_1;
},
loadingMore: function () {
return l10n.load_more;
},
maximumSelected: function( args ) {
var maximum = args.maximum;
if( maximum > 1 ) {
return l10n.selection_too_long_n.replace( '%d', maximum );
}
return l10n.selection_too_long_1;
},
noResults: function () {
return l10n.matches_0;
},
searching: function () {
return l10n.searching;
}
};
// append
jQuery.fn.select2.amd.define('select2/i18n/' + locale, [], function(){
return select2L10n;
});
},
addTranslations3: function(){
// vars
var l10n = acf.get('select2L10n');
var locale = acf.get('locale');
// modify local to match html[lang] attribute (used by Select2)
locale = locale.replace('_', '-');
// select2L10n
var select2L10n = {
formatMatches: function( matches ) {
if( matches > 1 ) {
return l10n.matches_n.replace( '%d', matches );
}
return l10n.matches_1;
},
formatNoMatches: function() {
return l10n.matches_0;
},
formatAjaxError: function() {
return l10n.load_fail;
},
formatInputTooShort: function( input, min ) {
var remainingChars = min - input.length;
if( remainingChars > 1 ) {
return l10n.input_too_short_n.replace( '%d', remainingChars );
}
return l10n.input_too_short_1;
},
formatInputTooLong: function( input, max ) {
var overChars = input.length - max;
if( overChars > 1 ) {
return l10n.input_too_long_n.replace( '%d', overChars );
}
return l10n.input_too_long_1;
},
formatSelectionTooBig: function( maximum ) {
if( maximum > 1 ) {
return l10n.selection_too_long_n.replace( '%d', maximum );
}
return l10n.selection_too_long_1;
},
formatLoadMore: function() {
return l10n.load_more;
},
formatSearching: function() {
return l10n.searching;
}
};
// ensure locales exists
$.fn.select2.locales = $.fn.select2.locales || {};
// append
$.fn.select2.locales[ locale ] = select2L10n;
$.extend($.fn.select2.defaults, select2L10n);
},
onDuplicate: function( $el, $el2 ){
$el2.find('.select2-container').remove();
}
});
})(jQuery);
(function($, undefined){
acf.tinymce = {
/*
* defaults
*
* This function will return default mce and qt settings
*
* @type function
* @date 18/8/17
* @since 5.6.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
defaults: function(){
// bail early if no tinyMCEPreInit
if( typeof tinyMCEPreInit === 'undefined' ) return false;
// vars
var defaults = {
tinymce: tinyMCEPreInit.mceInit.acf_content,
quicktags: tinyMCEPreInit.qtInit.acf_content
};
// return
return defaults;
},
/*
* initialize
*
* This function will initialize the tinymce and quicktags instances
*
* @type function
* @date 18/8/17
* @since 5.6.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
initialize: function( id, args ){
// defaults
args = acf.parseArgs(args, {
tinymce: true,
quicktags: true,
toolbar: 'full',
mode: 'visual', // visual,text
field: false
});
// tinymce
if( args.tinymce ) {
this.initializeTinymce( id, args );
}
// quicktags
if( args.quicktags ) {
this.initializeQuicktags( id, args );
}
},
/*
* initializeTinymce
*
* This function will initialize the tinymce instance
*
* @type function
* @date 18/8/17
* @since 5.6.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
initializeTinymce: function( id, args ){
// vars
var $textarea = $('#'+id);
var defaults = this.defaults();
var toolbars = acf.get('toolbars');
var field = args.field || false;
var $field = field.$el || false;
// bail early
if( typeof tinymce === 'undefined' ) return false;
if( !defaults ) return false;
// check if exists
if( tinymce.get(id) ) {
return this.enable( id );
}
// settings
var init = $.extend( {}, defaults.tinymce, args.tinymce );
init.id = id;
init.selector = '#' + id;
// toolbar
var toolbar = args.toolbar;
if( toolbar && toolbars && toolbars[toolbar] ) {
for( var i = 1; i <= 4; i++ ) {
init[ 'toolbar' + i ] = toolbars[toolbar][i] || '';
}
}
// event
init.setup = function( ed ){
ed.on('change', function(e) {
ed.save(); // save to textarea
$textarea.trigger('change');
});
// Fix bug where Gutenberg does not hear "mouseup" event and tries to select multiple blocks.
ed.on('mouseup', function(e) {
var event = new MouseEvent('mouseup');
window.dispatchEvent(event);
});
// Temporarily comment out. May not be necessary due to wysiwyg field actions.
//ed.on('unload', function(e) {
// acf.tinymce.remove( id );
//});
};
// disable wp_autoresize_on (no solution yet for fixed toolbar)
init.wp_autoresize_on = false;
// Enable wpautop allowing value to save without <p> tags.
// Only if the "TinyMCE Advanced" plugin hasn't already set this functionality.
if( !init.tadv_noautop ) {
init.wpautop = true;
}
// hook for 3rd party customization
init = acf.applyFilters('wysiwyg_tinymce_settings', init, id, field);
// z-index fix (caused too many conflicts)
//if( acf.isset(tinymce,'ui','FloatPanel') ) {
// tinymce.ui.FloatPanel.zIndex = 900000;
//}
// store settings
tinyMCEPreInit.mceInit[ id ] = init;
// visual tab is active
if( args.mode == 'visual' ) {
// init
var result = tinymce.init( init );
// get editor
var ed = tinymce.get( id );
// validate
if( !ed ) {
return false;
}
// add reference
ed.acf = args.field;
// action
acf.doAction('wysiwyg_tinymce_init', ed, ed.id, init, field);
}
},
/*
* initializeQuicktags
*
* This function will initialize the quicktags instance
*
* @type function
* @date 18/8/17
* @since 5.6.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
initializeQuicktags: function( id, args ){
// vars
var defaults = this.defaults();
// bail early
if( typeof quicktags === 'undefined' ) return false;
if( !defaults ) return false;
// settings
var init = $.extend( {}, defaults.quicktags, args.quicktags );
init.id = id;
// filter
var field = args.field || false;
var $field = field.$el || false;
init = acf.applyFilters('wysiwyg_quicktags_settings', init, init.id, field);
// store settings
tinyMCEPreInit.qtInit[ id ] = init;
// init
var ed = quicktags( init );
// validate
if( !ed ) {
return false;
}
// generate HTML
this.buildQuicktags( ed );
// action for 3rd party customization
acf.doAction('wysiwyg_quicktags_init', ed, ed.id, init, field);
},
/*
* buildQuicktags
*
* This function will build the quicktags HTML
*
* @type function
* @date 18/8/17
* @since 5.6.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
buildQuicktags: function( ed ){
var canvas, name, settings, theButtons, html, ed, id, i, use, instanceId,
defaults = ',strong,em,link,block,del,ins,img,ul,ol,li,code,more,close,';
canvas = ed.canvas;
name = ed.name;
settings = ed.settings;
html = '';
theButtons = {};
use = '';
instanceId = ed.id;
// set buttons
if ( settings.buttons ) {
use = ','+settings.buttons+',';
}
for ( i in edButtons ) {
if ( ! edButtons[i] ) {
continue;
}
id = edButtons[i].id;
if ( use && defaults.indexOf( ',' + id + ',' ) !== -1 && use.indexOf( ',' + id + ',' ) === -1 ) {
continue;
}
if ( ! edButtons[i].instance || edButtons[i].instance === instanceId ) {
theButtons[id] = edButtons[i];
if ( edButtons[i].html ) {
html += edButtons[i].html( name + '_' );
}
}
}
if ( use && use.indexOf(',dfw,') !== -1 ) {
theButtons.dfw = new QTags.DFWButton();
html += theButtons.dfw.html( name + '_' );
}
if ( 'rtl' === document.getElementsByTagName( 'html' )[0].dir ) {
theButtons.textdirection = new QTags.TextDirectionButton();
html += theButtons.textdirection.html( name + '_' );
}
ed.toolbar.innerHTML = html;
ed.theButtons = theButtons;
if ( typeof jQuery !== 'undefined' ) {
jQuery( document ).triggerHandler( 'quicktags-init', [ ed ] );
}
},
disable: function( id ){
this.destroyTinymce( id );
},
remove: function( id ){
this.destroyTinymce( id );
},
destroy: function( id ){
this.destroyTinymce( id );
},
destroyTinymce: function( id ){
// bail early
if( typeof tinymce === 'undefined' ) return false;
// get editor
var ed = tinymce.get( id );
// bail early if no editor
if( !ed ) return false;
// save
ed.save();
// destroy editor
ed.destroy();
// return
return true;
},
enable: function( id ){
this.enableTinymce( id );
},
enableTinymce: function( id ){
// bail early
if( typeof switchEditors === 'undefined' ) return false;
// bail ealry if not initialized
if( typeof tinyMCEPreInit.mceInit[ id ] === 'undefined' ) return false;
// Ensure textarea element is visible
// - Fixes bug in block editor when switching between "Block" and "Document" tabs.
$('#'+id).show();
// toggle
switchEditors.go( id, 'tmce');
// return
return true;
}
};
var editorManager = new acf.Model({
// hook in before fieldsEventManager, conditions, etc
priority: 5,
actions: {
'prepare': 'onPrepare',
'ready': 'onReady',
},
onPrepare: function(){
// find hidden editor which may exist within a field
var $div = $('#acf-hidden-wp-editor');
// move to footer
if( $div.exists() ) {
$div.appendTo('body');
}
},
onReady: function(){
// Restore wp.editor functions used by tinymce removed in WP5.
if( acf.isset(window,'wp','oldEditor') ) {
wp.editor.autop = wp.oldEditor.autop;
wp.editor.removep = wp.oldEditor.removep;
}
// bail early if no tinymce
if( !acf.isset(window,'tinymce','on') ) return;
// restore default activeEditor
tinymce.on('AddEditor', function( data ){
// vars
var editor = data.editor;
// bail early if not 'acf'
if( editor.id.substr(0, 3) !== 'acf' ) return;
// override if 'content' exists
editor = tinymce.editors.content || editor;
// update vars
tinymce.activeEditor = editor;
wpActiveEditor = editor.id;
});
}
});
})(jQuery);
(function($, undefined){
/**
* Validator
*
* The model for validating forms
*
* @date 4/9/18
* @since 5.7.5
*
* @param void
* @return void
*/
var Validator = acf.Model.extend({
/** @var string The model identifier. */
id: 'Validator',
/** @var object The model data. */
data: {
/** @var array The form errors. */
errors: [],
/** @var object The form notice. */
notice: null,
/** @var string The form status. loading, invalid, valid */
status: ''
},
/** @var object The model events. */
events: {
'changed:status': 'onChangeStatus'
},
/**
* addErrors
*
* Adds errors to the form.
*
* @date 4/9/18
* @since 5.7.5
*
* @param array errors An array of errors.
* @return void
*/
addErrors: function( errors ){
errors.map( this.addError, this );
},
/**
* addError
*
* Adds and error to the form.
*
* @date 4/9/18
* @since 5.7.5
*
* @param object error An error object containing input and message.
* @return void
*/
addError: function( error ){
this.data.errors.push( error );
},
/**
* hasErrors
*
* Returns true if the form has errors.
*
* @date 4/9/18
* @since 5.7.5
*
* @param void
* @return bool
*/
hasErrors: function(){
return this.data.errors.length;
},
/**
* clearErrors
*
* Removes any errors.
*
* @date 4/9/18
* @since 5.7.5
*
* @param void
* @return void
*/
clearErrors: function(){
return this.data.errors = [];
},
/**
* getErrors
*
* Returns the forms errors.
*
* @date 4/9/18
* @since 5.7.5
*
* @param void
* @return array
*/
getErrors: function(){
return this.data.errors;
},
/**
* getFieldErrors
*
* Returns the forms field errors.
*
* @date 4/9/18
* @since 5.7.5
*
* @param void
* @return array
*/
getFieldErrors: function(){
// vars
var errors = [];
var inputs = [];
// loop
this.getErrors().map(function(error){
// bail early if global
if( !error.input ) return;
// update if exists
var i = inputs.indexOf(error.input);
if( i > -1 ) {
errors[ i ] = error;
// update
} else {
errors.push( error );
inputs.push( error.input );
}
});
// return
return errors;
},
/**
* getGlobalErrors
*
* Returns the forms global errors (errors without a specific input).
*
* @date 4/9/18
* @since 5.7.5
*
* @param void
* @return array
*/
getGlobalErrors: function(){
// return array of errors that contain no input
return this.getErrors().filter(function(error){
return !error.input;
});
},
/**
* showErrors
*
* Displays all errors for this form.
*
* @date 4/9/18
* @since 5.7.5
*
* @param void
* @return void
*/
showErrors: function(){
// bail early if no errors
if( !this.hasErrors() ) {
return;
}
// vars
var fieldErrors = this.getFieldErrors();
var globalErrors = this.getGlobalErrors();
// vars
var errorCount = 0;
var $scrollTo = false;
// loop
fieldErrors.map(function( error ){
// get input
var $input = this.$('[name="' + error.input + '"]').first();
// if $_POST value was an array, this $input may not exist
if( !$input.length ) {
$input = this.$('[name^="' + error.input + '"]').first();
}
// bail early if input doesn't exist
if( !$input.length ) {
return;
}
// increase
errorCount++;
// get field
var field = acf.getClosestField( $input );
// show error
field.showError( error.message );
// set $scrollTo
if( !$scrollTo ) {
$scrollTo = field.$el;
}
}, this);
// errorMessage
var errorMessage = acf.__('Validation failed');
globalErrors.map(function( error ){
errorMessage += '. ' + error.message;
});
if( errorCount == 1 ) {
errorMessage += '. ' + acf.__('1 field requires attention');
} else if( errorCount > 1 ) {
errorMessage += '. ' + acf.__('%d fields require attention').replace('%d', errorCount);
}
// notice
if( this.has('notice') ) {
this.get('notice').update({
type: 'error',
text: errorMessage
});
} else {
var notice = acf.newNotice({
type: 'error',
text: errorMessage,
target: this.$el
});
this.set('notice', notice);
}
// if no $scrollTo, set to message
if( !$scrollTo ) {
$scrollTo = this.get('notice').$el;
}
// timeout
setTimeout(function(){
$("html, body").animate({ scrollTop: $scrollTo.offset().top - ( $(window).height() / 2 ) }, 500);
}, 10);
},
/**
* onChangeStatus
*
* Update the form class when changing the 'status' data
*
* @date 4/9/18
* @since 5.7.5
*
* @param object e The event object.
* @param jQuery $el The form element.
* @param string value The new status.
* @param string prevValue The old status.
* @return void
*/
onChangeStatus: function( e, $el, value, prevValue ){
this.$el.removeClass('is-'+prevValue).addClass('is-'+value);
},
/**
* validate
*
* Vaildates the form via AJAX.
*
* @date 4/9/18
* @since 5.7.5
*
* @param object args A list of settings to customize the validation process.
* @return bool True if the form is valid.
*/
validate: function( args ){
// default args
args = acf.parseArgs(args, {
// trigger event
event: false,
// reset the form after submit
reset: false,
// loading callback
loading: function(){},
// complete callback
complete: function(){},
// failure callback
failure: function(){},
// success callback
success: function( $form ){
$form.submit();
}
});
// return true if is valid - allows form submit
if( this.get('status') == 'valid' ) {
return true;
}
// return false if is currently validating - prevents form submit
if( this.get('status') == 'validating' ) {
return false;
}
// return true if no ACF fields exist (no need to validate)
if( !this.$('.acf-field').length ) {
return true;
}
// if event is provided, create a new success callback.
if( args.event ) {
var event = $.Event(null, args.event);
args.success = function(){
acf.enableSubmit( $(event.target) ).trigger( event );
}
}
// action for 3rd party
acf.doAction('validation_begin', this.$el);
// lock form
acf.lockForm( this.$el );
// loading callback
args.loading( this.$el, this );
// update status
this.set('status', 'validating');
// success callback
var onSuccess = function( json ){
// validate
if( !acf.isAjaxSuccess(json) ) {
return;
}
// filter
var data = acf.applyFilters('validation_complete', json.data, this.$el, this);
// add errors
if( !data.valid ) {
this.addErrors( data.errors );
}
};
// complete
var onComplete = function(){
// unlock form
acf.unlockForm( this.$el );
// failure
if( this.hasErrors() ) {
// update status
this.set('status', 'invalid');
// action
acf.doAction('validation_failure', this.$el, this);
// display errors
this.showErrors();
// failure callback
args.failure( this.$el, this );
// success
} else {
// update status
this.set('status', 'valid');
// remove previous error message
if( this.has('notice') ) {
this.get('notice').update({
type: 'success',
text: acf.__('Validation successful'),
timeout: 1000
});
}
// action
acf.doAction('validation_success', this.$el, this);
acf.doAction('submit', this.$el);
// success callback (submit form)
args.success( this.$el, this );
// lock form
acf.lockForm( this.$el );
// reset
if( args.reset ) {
this.reset();
}
}
// complete callback
args.complete( this.$el, this );
// clear errors
this.clearErrors();
};
// serialize form data
var data = acf.serialize( this.$el );
data.action = 'acf/validate_save_post';
// ajax
$.ajax({
url: acf.get('ajaxurl'),
data: acf.prepareForAjax(data),
type: 'post',
dataType: 'json',
context: this,
success: onSuccess,
complete: onComplete
});
// return false to fail validation and allow AJAX
return false
},
/**
* setup
*
* Called during the constructor function to setup this instance
*
* @date 4/9/18
* @since 5.7.5
*
* @param jQuery $form The form element.
* @return void
*/
setup: function( $form ){
// set $el
this.$el = $form;
},
/**
* reset
*
* Rests the validation to be used again.
*
* @date 6/9/18
* @since 5.7.5
*
* @param void
* @return void
*/
reset: function(){
// reset data
this.set('errors', []);
this.set('notice', null);
this.set('status', '');
// unlock form
acf.unlockForm( this.$el );
}
});
/**
* getValidator
*
* Returns the instance for a given form element.
*
* @date 4/9/18
* @since 5.7.5
*
* @param jQuery $el The form element.
* @return object
*/
var getValidator = function( $el ){
// instantiate
var validator = $el.data('acf');
if( !validator ) {
validator = new Validator( $el );
}
// return
return validator;
};
/**
* acf.validateForm
*
* A helper function for the Validator.validate() function.
* Returns true if form is valid, or fetches a validation request and returns false.
*
* @date 4/4/18
* @since 5.6.9
*
* @param object args A list of settings to customize the validation process.
* @return bool
*/
acf.validateForm = function( args ){
return getValidator( args.form ).validate( args );
};
/**
* acf.enableSubmit
*
* Enables a submit button and returns the element.
*
* @date 30/8/18
* @since 5.7.4
*
* @param jQuery $submit The submit button.
* @return jQuery
*/
acf.enableSubmit = function( $submit ){
return $submit.removeClass('disabled');
};
/**
* acf.disableSubmit
*
* Disables a submit button and returns the element.
*
* @date 30/8/18
* @since 5.7.4
*
* @param jQuery $submit The submit button.
* @return jQuery
*/
acf.disableSubmit = function( $submit ){
return $submit.addClass('disabled');
};
/**
* acf.showSpinner
*
* Shows the spinner element.
*
* @date 4/9/18
* @since 5.7.5
*
* @param jQuery $spinner The spinner element.
* @return jQuery
*/
acf.showSpinner = function( $spinner ){
$spinner.addClass('is-active'); // add class (WP > 4.2)
$spinner.css('display', 'inline-block'); // css (WP < 4.2)
return $spinner;
};
/**
* acf.hideSpinner
*
* Hides the spinner element.
*
* @date 4/9/18
* @since 5.7.5
*
* @param jQuery $spinner The spinner element.
* @return jQuery
*/
acf.hideSpinner = function( $spinner ){
$spinner.removeClass('is-active'); // add class (WP > 4.2)
$spinner.css('display', 'none'); // css (WP < 4.2)
return $spinner;
};
/**
* acf.lockForm
*
* Locks a form by disabeling its primary inputs and showing a spinner.
*
* @date 4/9/18
* @since 5.7.5
*
* @param jQuery $form The form element.
* @return jQuery
*/
acf.lockForm = function( $form ){
// vars
var $wrap = findSubmitWrap( $form );
var $submit = $wrap.find('.button, [type="submit"]');
var $spinner = $wrap.find('.spinner, .acf-spinner');
// hide all spinners (hides the preview spinner)
acf.hideSpinner( $spinner );
// lock
acf.disableSubmit( $submit );
acf.showSpinner( $spinner.last() );
return $form;
};
/**
* acf.unlockForm
*
* Unlocks a form by enabeling its primary inputs and hiding all spinners.
*
* @date 4/9/18
* @since 5.7.5
*
* @param jQuery $form The form element.
* @return jQuery
*/
acf.unlockForm = function( $form ){
// vars
var $wrap = findSubmitWrap( $form );
var $submit = $wrap.find('.button, [type="submit"]');
var $spinner = $wrap.find('.spinner, .acf-spinner');
// unlock
acf.enableSubmit( $submit );
acf.hideSpinner( $spinner );
return $form;
};
/**
* findSubmitWrap
*
* An internal function to find the 'primary' form submit wrapping element.
*
* @date 4/9/18
* @since 5.7.5
*
* @param jQuery $form The form element.
* @return jQuery
*/
var findSubmitWrap = function( $form ){
// default post submit div
var $wrap = $form.find('#submitdiv');
if( $wrap.length ) {
return $wrap;
}
// 3rd party publish box
var $wrap = $form.find('#submitpost');
if( $wrap.length ) {
return $wrap;
}
// term, user
var $wrap = $form.find('p.submit').last();
if( $wrap.length ) {
return $wrap;
}
// front end form
var $wrap = $form.find('.acf-form-submit');
if( $wrap.length ) {
return $wrap;
}
// default
return $form;
};
/**
* A debounced function to trigger a form submission.
*
* @date 15/07/2020
* @since 5.9.0
*
* @param type Var Description.
* @return type Description.
*/
var submitFormDebounced = acf.debounce(function( $form ){
$form.submit();
});
/**
* acf.validation
*
* Global validation logic
*
* @date 4/4/18
* @since 5.6.9
*
* @param void
* @return void
*/
acf.validation = new acf.Model({
/** @var string The model identifier. */
id: 'validation',
/** @var bool The active state. Set to false before 'prepare' to prevent validation. */
active: true,
/** @var string The model initialize time. */
wait: 'prepare',
/** @var object The model actions. */
actions: {
'ready': 'addInputEvents',
'append': 'addInputEvents'
},
/** @var object The model events. */
events: {
'click input[type="submit"]': 'onClickSubmit',
'click button[type="submit"]': 'onClickSubmit',
//'click #editor .editor-post-publish-button': 'onClickSubmitGutenberg',
'click #save-post': 'onClickSave',
'submit form#post': 'onSubmitPost',
'submit form': 'onSubmit',
},
/**
* initialize
*
* Called when initializing the model.
*
* @date 4/9/18
* @since 5.7.5
*
* @param void
* @return void
*/
initialize: function(){
// check 'validation' setting
if( !acf.get('validation') ) {
this.active = false;
this.actions = {};
this.events = {};
}
},
/**
* enable
*
* Enables validation.
*
* @date 4/9/18
* @since 5.7.5
*
* @param void
* @return void
*/
enable: function(){
this.active = true;
},
/**
* disable
*
* Disables validation.
*
* @date 4/9/18
* @since 5.7.5
*
* @param void
* @return void
*/
disable: function(){
this.active = false;
},
/**
* reset
*
* Rests the form validation to be used again
*
* @date 6/9/18
* @since 5.7.5
*
* @param jQuery $form The form element.
* @return void
*/
reset: function( $form ){
getValidator( $form ).reset();
},
/**
* addInputEvents
*
* Adds 'invalid' event listeners to HTML inputs.
*
* @date 4/9/18
* @since 5.7.5
*
* @param jQuery $el The element being added / readied.
* @return void
*/
addInputEvents: function( $el ){
// Bug exists in Safari where custom "invalid" handeling prevents draft from saving.
if( acf.get('browser') === 'safari' )
return;
// vars
var $inputs = $('.acf-field [name]', $el);
// check
if( $inputs.length ) {
this.on( $inputs, 'invalid', 'onInvalid' );
}
},
/**
* onInvalid
*
* Callback for the 'invalid' event.
*
* @date 4/9/18
* @since 5.7.5
*
* @param object e The event object.
* @param jQuery $el The input element.
* @return void
*/
onInvalid: function( e, $el ){
// prevent default
// - prevents browser error message
// - also fixes chrome bug where 'hidden-by-tab' field throws focus error
e.preventDefault();
// vars
var $form = $el.closest('form');
// check form exists
if( $form.length ) {
// add error to validator
getValidator( $form ).addError({
input: $el.attr('name'),
message: acf.strEscape( e.target.validationMessage )
});
// trigger submit on $form
// - allows for "save", "preview" and "publish" to work
submitFormDebounced( $form );
}
},
/**
* onClickSubmit
*
* Callback when clicking submit.
*
* @date 4/9/18
* @since 5.7.5
*
* @param object e The event object.
* @param jQuery $el The input element.
* @return void
*/
onClickSubmit: function( e, $el ){
// store the "click event" for later use in this.onSubmit()
this.set('originalEvent', e);
},
/**
* onClickSave
*
* Set ignore to true when saving a draft.
*
* @date 4/9/18
* @since 5.7.5
*
* @param object e The event object.
* @param jQuery $el The input element.
* @return void
*/
onClickSave: function( e, $el ) {
this.set('ignore', true);
},
/**
* onClickSubmitGutenberg
*
* Custom validation event for the gutenberg editor.
*
* @date 29/10/18
* @since 5.8.0
*
* @param object e The event object.
* @param jQuery $el The input element.
* @return void
*/
onClickSubmitGutenberg: function( e, $el ){
// validate
var valid = acf.validateForm({
form: $('#editor'),
event: e,
reset: true,
failure: function( $form, validator ){
var $notice = validator.get('notice').$el;
$notice.appendTo('.components-notice-list');
$notice.find('.acf-notice-dismiss').removeClass('small');
}
});
// if not valid, stop event and allow validation to continue
if( !valid ) {
e.preventDefault();
e.stopImmediatePropagation();
}
},
/**
* onSubmitPost
*
* Callback when the 'post' form is submit.
*
* @date 5/3/19
* @since 5.7.13
*
* @param object e The event object.
* @param jQuery $el The input element.
* @return void
*/
onSubmitPost: function( e, $el ) {
// Check if is preview.
if( $('input#wp-preview').val() === 'dopreview' ) {
// Ignore validation.
this.set('ignore', true);
// Unlock form to fix conflict with core "submit.edit-post" event causing all submit buttons to be disabled.
acf.unlockForm( $el )
}
},
/**
* onSubmit
*
* Callback when the form is submit.
*
* @date 4/9/18
* @since 5.7.5
*
* @param object e The event object.
* @param jQuery $el The input element.
* @return void
*/
onSubmit: function( e, $el ){
// Allow form to submit if...
if(
// Validation has been disabled.
!this.active
// Or this event is to be ignored.
|| this.get('ignore')
// Or this event has already been prevented.
|| e.isDefaultPrevented()
) {
// Return early and call reset function.
return this.allowSubmit();
}
// Validate form.
var valid = acf.validateForm({
form: $el,
event: this.get('originalEvent')
});
// If not valid, stop event to prevent form submit.
if( !valid ) {
e.preventDefault();
}
},
/**
* allowSubmit
*
* Resets data during onSubmit when the form is allowed to submit.
*
* @date 5/3/19
* @since 5.7.13
*
* @param void
* @return void
*/
allowSubmit: function(){
// Reset "ignore" state.
this.set('ignore', false);
// Reset "originalEvent" object.
this.set('originalEvent', false);
// Return true
return true;
}
});
var gutenbergValidation = new acf.Model({
wait: 'prepare',
initialize: function(){
// Bail early if not Gutenberg.
if( !acf.isGutenberg() ) {
return;
}
// Custommize the editor.
this.customizeEditor();
},
customizeEditor: function(){
// Extract vars.
var editor = wp.data.dispatch( 'core/editor' );
var editorSelect = wp.data.select( 'core/editor' );
var notices = wp.data.dispatch( 'core/notices' );
// Backup original method.
var savePost = editor.savePost;
// Listen for changes to post status and perform actions:
// a) Enable validation for "publish" action.
// b) Remember last non "publish" status used for restoring after validation fail.
var useValidation = false;
var lastPostStatus = '';
wp.data.subscribe(function() {
var postStatus = editorSelect.getEditedPostAttribute( 'status' );
useValidation = ( postStatus === 'publish' );
lastPostStatus = ( postStatus !== 'publish' ) ? postStatus : lastPostStatus;
});
// Create validation version.
editor.savePost = function( options ){
options = options || {};
// Backup vars.
var _this = this;
var _args = arguments;
// Perform validation within a Promise.
return new Promise(function( resolve, reject ) {
// Bail early if is autosave or preview.
if( options.isAutosave || options.isPreview ) {
return resolve( 'Validation ignored (autosave).' );
}
// Bail early if validation is not neeed.
if( !useValidation ) {
return resolve( 'Validation ignored (draft).' );
}
// Validate the editor form.
var valid = acf.validateForm({
form: $('#editor'),
reset: true,
complete: function( $form, validator ){
// Always unlock the form after AJAX.
editor.unlockPostSaving( 'acf' );
},
failure: function( $form, validator ){
// Get validation error and append to Gutenberg notices.
var notice = validator.get('notice');
notices.createErrorNotice( notice.get('text'), {
id: 'acf-validation',
isDismissible: true
});
notice.remove();
// Restore last non "publish" status.
if( lastPostStatus ) {
editor.editPost({
status: lastPostStatus
});
}
// Rejext promise and prevent savePost().
reject( 'Validation failed.' );
},
success: function(){
notices.removeNotice( 'acf-validation' );
// Resolve promise and allow savePost().
resolve( 'Validation success.' );
}
});
// Resolve promise and allow savePost() if no validation is needed.
if( valid ) {
resolve( 'Validation bypassed.' );
// Otherwise, lock the form and wait for AJAX response.
} else {
editor.lockPostSaving( 'acf' );
}
}).then(function(){
return savePost.apply(_this, _args);
});
};
}
});
})(jQuery);
(function($, undefined){
/**
* refreshHelper
*
* description
*
* @date 1/7/18
* @since 5.6.9
*
* @param type $var Description. Default.
* @return type Description.
*/
var refreshHelper = new acf.Model({
priority: 90,
actions: {
'new_field': 'refresh',
'show_field': 'refresh',
'hide_field': 'refresh',
'remove_field': 'refresh',
'unmount_field': 'refresh',
'remount_field': 'refresh',
},
refresh: function(){
acf.refresh();
}
});
/**
* mountHelper
*
* Adds compatiblity for the 'unmount' and 'remount' actions added in 5.8.0
*
* @date 7/3/19
* @since 5.7.14
*
* @param void
* @return void
*/
var mountHelper = new acf.Model({
priority: 1,
actions: {
'sortstart': 'onSortstart',
'sortstop': 'onSortstop'
},
onSortstart: function( $item ){
acf.doAction('unmount', $item);
},
onSortstop: function( $item ){
acf.doAction('remount', $item);
}
});
/**
* sortableHelper
*
* Adds compatibility for sorting a <tr> element
*
* @date 6/3/18
* @since 5.6.9
*
* @param void
* @return void
*/
var sortableHelper = new acf.Model({
actions: {
'sortstart': 'onSortstart'
},
onSortstart: function( $item, $placeholder ){
// if $item is a tr, apply some css to the elements
if( $item.is('tr') ) {
// replace $placeholder children with a single td
// fixes "width calculation issues" due to conditional logic hiding some children
$placeholder.html('<td style="padding:0;" colspan="' + $placeholder.children().length + '"></td>');
// add helper class to remove absolute positioning
$item.addClass('acf-sortable-tr-helper');
// set fixed widths for children
$item.children().each(function(){
$(this).width( $(this).width() );
});
// mimic height
$placeholder.height( $item.height() + 'px' );
// remove class
$item.removeClass('acf-sortable-tr-helper');
}
}
});
/**
* duplicateHelper
*
* Fixes browser bugs when duplicating an element
*
* @date 6/3/18
* @since 5.6.9
*
* @param void
* @return void
*/
var duplicateHelper = new acf.Model({
actions: {
'after_duplicate': 'onAfterDuplicate'
},
onAfterDuplicate: function( $el, $el2 ){
// get original values
var vals = [];
$el.find('select').each(function(i){
vals.push( $(this).val() );
});
// set duplicate values
$el2.find('select').each(function(i){
$(this).val( vals[i] );
});
}
});
/**
* tableHelper
*
* description
*
* @date 6/3/18
* @since 5.6.9
*
* @param type $var Description. Default.
* @return type Description.
*/
var tableHelper = new acf.Model({
id: 'tableHelper',
priority: 20,
actions: {
'refresh': 'renderTables'
},
renderTables: function( $el ){
// loop
var self = this;
$('.acf-table:visible').each(function(){
self.renderTable( $(this) );
});
},
renderTable: function( $table ){
// vars
var $ths = $table.find('> thead > tr:visible > th[data-key]');
var $tds = $table.find('> tbody > tr:visible > td[data-key]');
// bail early if no thead
if( !$ths.length || !$tds.length ) {
return false;
}
// visiblity
$ths.each(function( i ){
// vars
var $th = $(this);
var key = $th.data('key');
var $cells = $tds.filter('[data-key="' + key + '"]');
var $hidden = $cells.filter('.acf-hidden');
// always remove empty and allow cells to be hidden
$cells.removeClass('acf-empty');
// hide $th if all cells are hidden
if( $cells.length === $hidden.length ) {
acf.hide( $th );
// force all hidden cells to appear empty
} else {
acf.show( $th );
$hidden.addClass('acf-empty');
}
});
// clear width
$ths.css('width', 'auto');
// get visible
$ths = $ths.not('.acf-hidden');
// vars
var availableWidth = 100;
var colspan = $ths.length;
// set custom widths first
var $fixedWidths = $ths.filter('[data-width]');
$fixedWidths.each(function(){
var width = $(this).data('width');
$(this).css('width', width + '%');
availableWidth -= width;
});
// set auto widths
var $auoWidths = $ths.not('[data-width]');
if( $auoWidths.length ) {
var width = availableWidth / $auoWidths.length;
$auoWidths.css('width', width + '%');
availableWidth = 0;
}
// avoid stretching issue
if( availableWidth > 0 ) {
$ths.last().css('width', 'auto');
}
// update colspan on collapsed
$tds.filter('.-collapsed-target').each(function(){
// vars
var $td = $(this);
// check if collapsed
if( $td.parent().hasClass('-collapsed') ) {
$td.attr('colspan', $ths.length);
} else {
$td.removeAttr('colspan');
}
});
}
});
/**
* fieldsHelper
*
* description
*
* @date 6/3/18
* @since 5.6.9
*
* @param type $var Description. Default.
* @return type Description.
*/
var fieldsHelper = new acf.Model({
id: 'fieldsHelper',
priority: 30,
actions: {
'refresh': 'renderGroups'
},
renderGroups: function(){
// loop
var self = this;
$('.acf-fields:visible').each(function(){
self.renderGroup( $(this) );
});
},
renderGroup: function( $el ){
// vars
var top = 0;
var height = 0;
var $row = $();
// get fields
var $fields = $el.children('.acf-field[data-width]:visible');
// bail early if no fields
if( !$fields.length ) {
return false;
}
// bail ealry if is .-left
if( $el.hasClass('-left') ) {
$fields.removeAttr('data-width');
$fields.css('width', 'auto');
return false;
}
// reset fields
$fields.removeClass('-r0 -c0').css({'min-height': 0});
// loop
$fields.each(function( i ){
// vars
var $field = $(this);
var position = $field.position();
var thisTop = Math.ceil( position.top );
var thisLeft = Math.ceil( position.left );
// detect change in row
if( $row.length && thisTop > top ) {
// set previous heights
$row.css({'min-height': height+'px'});
// update position due to change in row above
position = $field.position();
thisTop = Math.ceil( position.top );
thisLeft = Math.ceil( position.left );
// reset vars
top = 0;
height = 0;
$row = $();
}
// rtl
if( acf.get('rtl') ) {
thisLeft = Math.ceil( $field.parent().width() - (position.left + $field.outerWidth()) );
}
// add classes
if( thisTop == 0 ) {
$field.addClass('-r0');
} else if( thisLeft == 0 ) {
$field.addClass('-c0');
}
// get height after class change
// - add 1 for subpixel rendering
var thisHeight = Math.ceil( $field.outerHeight() ) + 1;
// set height
height = Math.max( height, thisHeight );
// set y
top = Math.max( top, thisTop );
// append
$row = $row.add( $field );
});
// clean up
if( $row.length ) {
$row.css({'min-height': height+'px'});
}
}
});
/**
* Adds a body class when holding down the "shift" key.
*
* @date 06/05/2020
* @since 5.9.0
*/
var bodyClassShiftHelper = new acf.Model({
id: 'bodyClassShiftHelper',
events: {
'keydown': 'onKeyDown',
'keyup': 'onKeyUp'
},
isShiftKey: function( e ){
return ( e.keyCode === 16 );
},
onKeyDown: function( e ){
if( this.isShiftKey(e) ) {
$('body').addClass('acf-keydown-shift');
}
},
onKeyUp: function( e ){
if( this.isShiftKey(e) ) {
$('body').removeClass('acf-keydown-shift');
}
},
});
})(jQuery);
(function($, undefined){
/**
* acf.newCompatibility
*
* Inserts a new __proto__ object compatibility layer
*
* @date 15/2/18
* @since 5.6.9
*
* @param object instance The object to modify.
* @param object compatibilty Optional. The compatibilty layer.
* @return object compatibilty
*/
acf.newCompatibility = function( instance, compatibilty ){
// defaults
compatibilty = compatibilty || {};
// inherit __proto_-
compatibilty.__proto__ = instance.__proto__;
// inject
instance.__proto__ = compatibilty;
// reference
instance.compatibility = compatibilty;
// return
return compatibilty;
};
/**
* acf.getCompatibility
*
* Returns the compatibility layer for a given instance
*
* @date 13/3/18
* @since 5.6.9
*
* @param object instance The object to look in.
* @return object|null compatibility The compatibility object or null on failure.
*/
acf.getCompatibility = function( instance ) {
return instance.compatibility || null;
};
/**
* acf (compatibility)
*
* Compatibility layer for the acf object
*
* @date 15/2/18
* @since 5.6.9
*
* @param void
* @return void
*/
var _acf = acf.newCompatibility(acf, {
// storage
l10n: {},
o: {},
fields: {},
// changed function names
update: acf.set,
add_action: acf.addAction,
remove_action: acf.removeAction,
do_action: acf.doAction,
add_filter: acf.addFilter,
remove_filter: acf.removeFilter,
apply_filters: acf.applyFilters,
parse_args: acf.parseArgs,
disable_el: acf.disable,
disable_form: acf.disable,
enable_el: acf.enable,
enable_form: acf.enable,
update_user_setting: acf.updateUserSetting,
prepare_for_ajax: acf.prepareForAjax,
is_ajax_success: acf.isAjaxSuccess,
remove_el: acf.remove,
remove_tr: acf.remove,
str_replace: acf.strReplace,
render_select: acf.renderSelect,
get_uniqid: acf.uniqid,
serialize_form: acf.serialize,
esc_html: acf.strEscape,
str_sanitize: acf.strSanitize,
});
_acf._e = function( k1, k2 ){
// defaults
k1 = k1 || '';
k2 = k2 || '';
// compability
var compatKey = k2 ? k1 + '.' + k2 : k1;
var compats = {
'image.select': 'Select Image',
'image.edit': 'Edit Image',
'image.update': 'Update Image'
};
if( compats[compatKey] ) {
return acf.__(compats[compatKey]);
}
// try k1
var string = this.l10n[ k1 ] || '';
// try k2
if( k2 ) {
string = string[ k2 ] || '';
}
// return
return string;
};
_acf.get_selector = function( s ) {
// vars
var selector = '.acf-field';
// bail early if no search
if( !s ) {
return selector;
}
// compatibility with object
if( $.isPlainObject(s) ) {
if( $.isEmptyObject(s) ) {
return selector;
} else {
for( var k in s ) { s = s[k]; break; }
}
}
// append
selector += '-' + s;
// replace underscores (split/join replaces all and is faster than regex!)
selector = acf.strReplace('_', '-', selector);
// remove potential double up
selector = acf.strReplace('field-field-', 'field-', selector);
// return
return selector;
};
_acf.get_fields = function( s, $el, all ){
// args
var args = {
is: s || '',
parent: $el || false,
suppressFilters: all || false,
};
// change 'field_123' to '.acf-field-123'
if( args.is ) {
args.is = this.get_selector( args.is );
}
// return
return acf.findFields(args);
};
_acf.get_field = function( s, $el ){
// get fields
var $fields = this.get_fields.apply(this, arguments);
// return
if( $fields.length ) {
return $fields.first();
} else {
return false;
}
};
_acf.get_closest_field = function( $el, s ){
return $el.closest( this.get_selector(s) );
};
_acf.get_field_wrap = function( $el ){
return $el.closest( this.get_selector() );
};
_acf.get_field_key = function( $field ){
return $field.data('key');
};
_acf.get_field_type = function( $field ){
return $field.data('type');
};
_acf.get_data = function( $el, defaults ){
return acf.parseArgs( $el.data(), defaults );
};
_acf.maybe_get = function( obj, key, value ){
// default
if( value === undefined ) {
value = null;
}
// get keys
keys = String(key).split('.');
// acf.isget
for( var i = 0; i < keys.length; i++ ) {
if( !obj.hasOwnProperty(keys[i]) ) {
return value;
}
obj = obj[ keys[i] ];
}
return obj;
};
/**
* hooks
*
* Modify add_action and add_filter functions to add compatibility with changed $field parameter
* Using the acf.add_action() or acf.add_filter() functions will interpret new field parameters as jQuery $field
*
* @date 12/5/18
* @since 5.6.9
*
* @param void
* @return void
*/
var compatibleArgument = function( arg ){
return ( arg instanceof acf.Field ) ? arg.$el : arg;
};
var compatibleArguments = function( args ){
return acf.arrayArgs( args ).map( compatibleArgument );
}
var compatibleCallback = function( origCallback ){
return function(){
// convert to compatible arguments
if( arguments.length ) {
var args = compatibleArguments(arguments);
// add default argument for 'ready', 'append' and 'load' events
} else {
var args = [ $(document) ];
}
// return
return origCallback.apply(this, args);
}
}
_acf.add_action = function( action, callback, priority, context ){
// handle multiple actions
var actions = action.split(' ');
var length = actions.length;
if( length > 1 ) {
for( var i = 0; i < length; i++) {
action = actions[i];
_acf.add_action.apply(this, arguments);
}
return this;
}
// single
var callback = compatibleCallback(callback);
return acf.addAction.apply(this, arguments);
};
_acf.add_filter = function( action, callback, priority, context ){
var callback = compatibleCallback(callback);
return acf.addFilter.apply(this, arguments);
};
/*
* acf.model
*
* This model acts as a scafold for action.event driven modules
*
* @type object
* @date 8/09/2014
* @since 5.0.0
*
* @param (object)
* @return (object)
*/
_acf.model = {
actions: {},
filters: {},
events: {},
extend: function( args ){
// extend
var model = $.extend( {}, this, args );
// setup actions
$.each(model.actions, function( name, callback ){
model._add_action( name, callback );
});
// setup filters
$.each(model.filters, function( name, callback ){
model._add_filter( name, callback );
});
// setup events
$.each(model.events, function( name, callback ){
model._add_event( name, callback );
});
// return
return model;
},
_add_action: function( name, callback ) {
// split
var model = this,
data = name.split(' ');
// add missing priority
var name = data[0] || '',
priority = data[1] || 10;
// add action
acf.add_action(name, model[ callback ], priority, model);
},
_add_filter: function( name, callback ) {
// split
var model = this,
data = name.split(' ');
// add missing priority
var name = data[0] || '',
priority = data[1] || 10;
// add action
acf.add_filter(name, model[ callback ], priority, model);
},
_add_event: function( name, callback ) {
// vars
var model = this,
i = name.indexOf(' '),
event = (i > 0) ? name.substr(0,i) : name,
selector = (i > 0) ? name.substr(i+1) : '';
// event
var fn = function( e ){
// append $el to event object
e.$el = $(this);
// append $field to event object (used in field group)
if( acf.field_group ) {
e.$field = e.$el.closest('.acf-field-object');
}
// event
if( typeof model.event === 'function' ) {
e = model.event( e );
}
// callback
model[ callback ].apply(model, arguments);
};
// add event
if( selector ) {
$(document).on(event, selector, fn);
} else {
$(document).on(event, fn);
}
},
get: function( name, value ){
// defaults
value = value || null;
// get
if( typeof this[ name ] !== 'undefined' ) {
value = this[ name ];
}
// return
return value;
},
set: function( name, value ){
// set
this[ name ] = value;
// function for 3rd party
if( typeof this[ '_set_' + name ] === 'function' ) {
this[ '_set_' + name ].apply(this);
}
// return for chaining
return this;
}
};
/*
* field
*
* This model sets up many of the field's interactions
*
* @type function
* @date 21/02/2014
* @since 3.5.1
*
* @param n/a
* @return n/a
*/
_acf.field = acf.model.extend({
type: '',
o: {},
$field: null,
_add_action: function( name, callback ) {
// vars
var model = this;
// update name
name = name + '_field/type=' + model.type;
// add action
acf.add_action(name, function( $field ){
// focus
model.set('$field', $field);
// callback
model[ callback ].apply(model, arguments);
});
},
_add_filter: function( name, callback ) {
// vars
var model = this;
// update name
name = name + '_field/type=' + model.type;
// add action
acf.add_filter(name, function( $field ){
// focus
model.set('$field', $field);
// callback
model[ callback ].apply(model, arguments);
});
},
_add_event: function( name, callback ) {
// vars
var model = this,
event = name.substr(0,name.indexOf(' ')),
selector = name.substr(name.indexOf(' ')+1),
context = acf.get_selector(model.type);
// add event
$(document).on(event, context + ' ' + selector, function( e ){
// vars
var $el = $(this);
var $field = acf.get_closest_field( $el, model.type );
// bail early if no field
if( !$field.length ) return;
// focus
if( !$field.is(model.$field) ) {
model.set('$field', $field);
}
// append to event
e.$el = $el;
e.$field = $field;
// callback
model[ callback ].apply(model, [e]);
});
},
_set_$field: function(){
// callback
if( typeof this.focus === 'function' ) {
this.focus();
}
},
// depreciated
doFocus: function( $field ){
return this.set('$field', $field);
}
});
/**
* validation
*
* description
*
* @date 15/2/18
* @since 5.6.9
*
* @param type $var Description. Default.
* @return type Description.
*/
var _validation = acf.newCompatibility(acf.validation, {
remove_error: function( $field ){
acf.getField( $field ).removeError();
},
add_warning: function( $field, message ){
acf.getField( $field ).showNotice({
text: message,
type: 'warning',
timeout: 1000
});
},
fetch: acf.validateForm,
enableSubmit: acf.enableSubmit,
disableSubmit: acf.disableSubmit,
showSpinner: acf.showSpinner,
hideSpinner: acf.hideSpinner,
unlockForm: acf.unlockForm,
lockForm: acf.lockForm
});
/**
* tooltip
*
* description
*
* @date 15/2/18
* @since 5.6.9
*
* @param type $var Description. Default.
* @return type Description.
*/
_acf.tooltip = {
tooltip: function( text, $el ){
var tooltip = acf.newTooltip({
text: text,
target: $el
});
// return
return tooltip.$el;
},
temp: function( text, $el ){
var tooltip = acf.newTooltip({
text: text,
target: $el,
timeout: 250
});
},
confirm: function( $el, callback, text, button_y, button_n ){
var tooltip = acf.newTooltip({
confirm: true,
text: text,
target: $el,
confirm: function(){
callback(true);
},
cancel: function(){
callback(false);
}
});
},
confirm_remove: function( $el, callback ){
var tooltip = acf.newTooltip({
confirmRemove: true,
target: $el,
confirm: function(){
callback(true);
},
cancel: function(){
callback(false);
}
});
},
};
/**
* tooltip
*
* description
*
* @date 15/2/18
* @since 5.6.9
*
* @param type $var Description. Default.
* @return type Description.
*/
_acf.media = new acf.Model({
activeFrame: false,
actions: {
'new_media_popup': 'onNewMediaPopup'
},
frame: function(){
return this.activeFrame;
},
onNewMediaPopup: function( popup ){
this.activeFrame = popup.frame;
},
popup: function( props ){
// update props
if( props.mime_types ) {
props.allowedTypes = props.mime_types;
}
if( props.id ) {
props.attachment = props.id;
}
// new
var popup = acf.newMediaPopup( props );
// append
/*
if( props.selected ) {
popup.selected = props.selected;
}
*/
// return
return popup.frame;
}
});
/**
* Select2
*
* description
*
* @date 11/6/18
* @since 5.6.9
*
* @param type $var Description. Default.
* @return type Description.
*/
_acf.select2 = {
init: function( $select, args, $field ){
// compatible args
if( args.allow_null ) {
args.allowNull = args.allow_null;
}
if( args.ajax_action ) {
args.ajaxAction = args.ajax_action;
}
if( $field ) {
args.field = acf.getField($field);
}
// return
return acf.newSelect2( $select, args );
},
destroy: function( $select ){
return acf.getInstance( $select ).destroy();
},
};
/**
* postbox
*
* description
*
* @date 11/6/18
* @since 5.6.9
*
* @param type $var Description. Default.
* @return type Description.
*/
_acf.postbox = {
render: function( args ){
// compatible args
if( args.edit_url ) {
args.editLink = args.edit_url;
}
if( args.edit_title ) {
args.editTitle = args.edit_title;
}
// return
return acf.newPostbox( args );
}
};
/**
* acf.screen
*
* description
*
* @date 11/6/18
* @since 5.6.9
*
* @param type $var Description. Default.
* @return type Description.
*/
acf.newCompatibility(acf.screen, {
update: function(){
return this.set.apply(this, arguments);
},
fetch: acf.screen.check
});
_acf.ajax = acf.screen;
})(jQuery);
// @codekit-prepend "_acf-field.js";
// @codekit-prepend "_acf-fields.js";
// @codekit-prepend "_acf-field-accordion.js";
// @codekit-prepend "_acf-field-button-group.js";
// @codekit-prepend "_acf-field-checkbox.js";
// @codekit-prepend "_acf-field-color-picker.js";
// @codekit-prepend "_acf-field-date-picker.js";
// @codekit-prepend "_acf-field-date-time-picker.js";
// @codekit-prepend "_acf-field-google-map.js";
// @codekit-prepend "_acf-field-image.js";
// @codekit-prepend "_acf-field-file.js";
// @codekit-prepend "_acf-field-link.js";
// @codekit-prepend "_acf-field-oembed.js";
// @codekit-prepend "_acf-field-radio.js";
// @codekit-prepend "_acf-field-range.js";
// @codekit-prepend "_acf-field-relationship.js";
// @codekit-prepend "_acf-field-select.js";
// @codekit-prepend "_acf-field-tab.js";
// @codekit-prepend "_acf-field-post-object.js";
// @codekit-prepend "_acf-field-page-link.js";
// @codekit-prepend "_acf-field-user.js";
// @codekit-prepend "_acf-field-taxonomy.js";
// @codekit-prepend "_acf-field-time-picker.js";
// @codekit-prepend "_acf-field-true-false.js";
// @codekit-prepend "_acf-field-url.js";
// @codekit-prepend "_acf-field-wysiwyg.js";
// @codekit-prepend "_acf-condition.js";
// @codekit-prepend "_acf-conditions.js";
// @codekit-prepend "_acf-condition-types.js";
// @codekit-prepend "_acf-unload.js";
// @codekit-prepend "_acf-postbox.js";
// @codekit-prepend "_acf-media.js";
// @codekit-prepend "_acf-screen.js";
// @codekit-prepend "_acf-select2.js";
// @codekit-prepend "_acf-tinymce.js";
// @codekit-prepend "_acf-validation.js";
// @codekit-prepend "_acf-helpers.js";
// @codekit-prepend "_acf-compatibility"; | gpl-3.0 |
BigBoss424/a-zplumbing | Magento-CE-2/vendor/magento/module-catalog/Controller/Adminhtml/Category/Add.php | 1228 | <?php
/**
*
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Controller\Adminhtml\Category;
class Add extends \Magento\Catalog\Controller\Adminhtml\Category
{
/**
* @var \Magento\Backend\Model\View\Result\ForwardFactory
*/
protected $resultForwardFactory;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory
) {
parent::__construct($context);
$this->resultForwardFactory = $resultForwardFactory;
}
/**
* Add new category form
*
* @return \Magento\Backend\Model\View\Result\Forward
*/
public function execute()
{
$this->_objectManager->get('Magento\Backend\Model\Auth\Session')->unsActiveTabId();
/** @var \Magento\Backend\Model\View\Result\Forward $resultForward */
$resultForward = $this->resultForwardFactory->create();
return $resultForward->forward('edit');
}
}
| gpl-3.0 |
BigBoss424/a-zplumbing | Magento-CE-2/vendor/magento/framework/Filesystem/File/ReadFactory.php | 990 | <?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\Filesystem\File;
use Magento\Framework\Filesystem\DriverInterface;
use Magento\Framework\Filesystem\DriverPool;
class ReadFactory
{
/**
* Pool of filesystem drivers
*
* @var DriverPool
*/
private $driverPool;
/**
* Constructor
*
* @param DriverPool $driverPool
*/
public function __construct(DriverPool $driverPool)
{
$this->driverPool = $driverPool;
}
/**
* Create a readable file
*
* @param string $path
* @param DriverInterface|string $driver Driver or driver code
* @return \Magento\Framework\Filesystem\File\ReadInterface
*/
public function create($path, $driver)
{
if (is_string($driver)) {
return new Read($path, $this->driverPool->getDriver($driver));
}
return new Read($path, $driver);
}
}
| gpl-3.0 |
wiki2014/Learning-Summary | alps/art/tools/dexfuzz/src/dexfuzz/rawdex/HeaderItem.java | 4744 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dexfuzz.rawdex;
import dexfuzz.Log;
import java.io.IOException;
public class HeaderItem implements RawDexObject {
public byte[] magic;
public int checksum;
public byte[] signature; // Verification doesn't depend on this, so we don't update it.
public int fileSize;
public int headerSize;
public int endianTag;
public int linkSize;
public Offset linkOff;
public Offset mapOff;
public int stringIdsSize;
public Offset stringIdsOff;
public int typeIdsSize;
public Offset typeIdsOff;
public int protoIdsSize;
public Offset protoIdsOff;
public int fieldIdsSize;
public Offset fieldIdsOff;
public int methodIdsSize;
public Offset methodIdsOff;
public int classDefsSize;
public Offset classDefsOff;
public int dataSize;
public Offset dataOff;
@Override
public void read(DexRandomAccessFile file) throws IOException {
file.getOffsetTracker().getNewOffsettable(file, this);
magic = new byte[8];
for (int i = 0; i < 8; i++) {
magic[i] = file.readByte();
}
checksum = file.readUInt();
signature = new byte[20];
for (int i = 0; i < 20; i++) {
signature[i] = file.readByte();
}
fileSize = file.readUInt();
headerSize = file.readUInt();
endianTag = file.readUInt();
linkSize = file.readUInt();
linkOff = file.getOffsetTracker().getNewOffset(file.readUInt());
mapOff = file.getOffsetTracker().getNewOffset(file.readUInt());
stringIdsSize = file.readUInt();
stringIdsOff = file.getOffsetTracker().getNewOffset(file.readUInt());
typeIdsSize = file.readUInt();
typeIdsOff = file.getOffsetTracker().getNewOffset(file.readUInt());
protoIdsSize = file.readUInt();
protoIdsOff = file.getOffsetTracker().getNewOffset(file.readUInt());
fieldIdsSize = file.readUInt();
fieldIdsOff = file.getOffsetTracker().getNewOffset(file.readUInt());
methodIdsSize = file.readUInt();
methodIdsOff = file.getOffsetTracker().getNewOffset(file.readUInt());
classDefsSize = file.readUInt();
classDefsOff = file.getOffsetTracker().getNewOffset(file.readUInt());
dataSize = file.readUInt();
dataOff = file.getOffsetTracker().getNewOffset(file.readUInt());
if (headerSize != 0x70) {
Log.errorAndQuit("Invalid header size in header.");
}
if (file.getFilePointer() != headerSize) {
Log.errorAndQuit("Read a different amount than expected in header: "
+ file.getFilePointer());
}
}
@Override
public void write(DexRandomAccessFile file) throws IOException {
file.getOffsetTracker().updatePositionOfNextOffsettable(file);
for (int i = 0; i < 8; i++) {
file.writeByte(magic[i]);
}
// Will be recalculated later!
file.writeUInt(checksum);
for (int i = 0; i < 20; i++) {
file.writeByte(signature[i]);
}
// Will be recalculated later!
file.writeUInt(fileSize);
file.writeUInt(headerSize);
file.writeUInt(endianTag);
file.writeUInt(linkSize);
file.getOffsetTracker().tryToWriteOffset(linkOff, file, false /* ULEB128 */);
file.getOffsetTracker().tryToWriteOffset(mapOff, file, false /* ULEB128 */);
file.writeUInt(stringIdsSize);
file.getOffsetTracker().tryToWriteOffset(stringIdsOff, file, false /* ULEB128 */);
file.writeUInt(typeIdsSize);
file.getOffsetTracker().tryToWriteOffset(typeIdsOff, file, false /* ULEB128 */);
file.writeUInt(protoIdsSize);
file.getOffsetTracker().tryToWriteOffset(protoIdsOff, file, false /* ULEB128 */);
file.writeUInt(fieldIdsSize);
file.getOffsetTracker().tryToWriteOffset(fieldIdsOff, file, false /* ULEB128 */);
file.writeUInt(methodIdsSize);
file.getOffsetTracker().tryToWriteOffset(methodIdsOff, file, false /* ULEB128 */);
file.writeUInt(classDefsSize);
file.getOffsetTracker().tryToWriteOffset(classDefsOff, file, false /* ULEB128 */);
// will be recalculated later
file.writeUInt(dataSize);
file.getOffsetTracker().tryToWriteOffset(dataOff, file, false /* ULEB128 */);
}
@Override
public void incrementIndex(IndexUpdateKind kind, int insertedIdx) {
// Do nothing
}
}
| gpl-3.0 |
technologiescollege/Blockly-rduino-communication | scripts_XP/Lib/site-packages/autobahn/__init__.py | 1399 | ###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Crossbar.io Technologies GmbH
#
# 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 __future__ import absolute_import
from autobahn._version import __version__
version = __version__
| gpl-3.0 |
Passw/gn_GFW | buildtools/third_party/libc++/trunk/test/std/containers/associative/multimap/multimap.ops/count0.pass.cpp | 1050 | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// XFAIL: c++98, c++03, c++11
// <map>
// class multimap
// iterator find(const key_type& k);
// const_iterator find(const key_type& k) const;
//
// The member function templates find, count, lower_bound, upper_bound, and
// equal_range shall not participate in overload resolution unless the
// qualified-id Compare::is_transparent is valid and denotes a type
#include <map>
#include <cassert>
#include "is_transparent.h"
int main()
{
{
typedef std::multimap<int, double, transparent_less> M;
assert(M().count(C2Int{5}) == 0);
}
{
typedef std::multimap<int, double, transparent_less_not_referenceable> M;
assert(M().count(C2Int{5}) == 0);
}
}
| gpl-3.0 |
MrNuggles/HeyBoet-Telegram-Bot | temboo/Library/RunKeeper/GeneralMeasurements/__init__.py | 1018 | from temboo.Library.RunKeeper.GeneralMeasurements.CreateEntry import CreateEntry, CreateEntryInputSet, CreateEntryResultSet, CreateEntryChoreographyExecution
from temboo.Library.RunKeeper.GeneralMeasurements.DeleteEntry import DeleteEntry, DeleteEntryInputSet, DeleteEntryResultSet, DeleteEntryChoreographyExecution
from temboo.Library.RunKeeper.GeneralMeasurements.RetrieveEntries import RetrieveEntries, RetrieveEntriesInputSet, RetrieveEntriesResultSet, RetrieveEntriesChoreographyExecution
from temboo.Library.RunKeeper.GeneralMeasurements.RetrieveEntry import RetrieveEntry, RetrieveEntryInputSet, RetrieveEntryResultSet, RetrieveEntryChoreographyExecution
from temboo.Library.RunKeeper.GeneralMeasurements.RetrieveLatestEntry import RetrieveLatestEntry, RetrieveLatestEntryInputSet, RetrieveLatestEntryResultSet, RetrieveLatestEntryChoreographyExecution
from temboo.Library.RunKeeper.GeneralMeasurements.UpdateEntry import UpdateEntry, UpdateEntryInputSet, UpdateEntryResultSet, UpdateEntryChoreographyExecution
| gpl-3.0 |
darius/mccarthy-to-bryant | dimacs.py | 1359 | """
Read or write the DIMACS CNF file format.
"""
def save(filename, problem):
save_file(open(filename, 'w'), problem)
def save_file(f, problem):
nvariables = reduce(max,
(abs(literal) for clause in problem for literal in clause),
0)
nclauses = len(problem)
print >>f, 'p cnf', nvariables, nclauses
for clause in problem:
for literal in clause:
print >>f, literal,
print >>f, 0
def load(filename):
return load_file(open(filename))
def load_file(f):
nvariables = None
nclauses = None
clauses = []
clause = []
for line in f:
if line.startswith('c'):
continue
if line.startswith('p'):
f1, f2, f3, f4 = line.split()
if f1 != 'p' or f2 != 'cnf':
raise Exception('Not in DIMACS CNF format')
nvariables = int(f3)
nclauses = int(f4)
else:
lits = map(int, line.split())
for lit in lits:
if lit == 0:
clauses.append(clause)
clause = []
else:
assert 1 <= abs(lit) <= nvariables
clause.append(lit)
if clause:
clauses.append(clause)
assert nclauses == len(clauses)
return nvariables, clauses
| gpl-3.0 |
ariely78/wabit | src/main/java/ca/sqlpower/wabit/swingui/ServerListMenu.java | 6833 | /*
* Copyright (c) 2009, SQL Power Group Inc.
*
* This file is part of Wabit.
*
* Wabit is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Wabit is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ca.sqlpower.wabit.swingui;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.util.List;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceListener;
import javax.swing.AbstractAction;
import javax.swing.JDialog;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import ca.sqlpower.enterprise.client.SPServerInfo;
import ca.sqlpower.swingui.SPSUtils;
import ca.sqlpower.wabit.ServerListEvent;
import ca.sqlpower.wabit.ServerListListener;
import ca.sqlpower.wabit.WabitSessionContext;
import ca.sqlpower.wabit.swingui.enterprise.ServerInfoManager;
/**
* A JMenu which maintains its own set of entries based on services discovered by mDNS information.
*/
public class ServerListMenu extends JMenu {
private static final Logger logger = Logger.getLogger(ServerListMenu.class);
private final WabitSwingSessionContext context;
private final Component dialogOwner;
private final ServerListMenuItemFactory itemFactory;
/**
* The server manager action that is used in the dynamically changing popup
* menus. We avoid making many of these in an attempt to avoid a
* proliferation of ServerInfoManager instances.
*/
private final AbstractAction serverManagerAction;
/**
* Creates a throwaway popup menu containing the current list of servers.
* The resulting popup menu will not change over time like the regular
* ServerListMenu does, so you should make a new popup instance every time
* you need one.
*/
public static JPopupMenu createPopupInstance(
final WabitSwingSessionContext context,
final Component dialogOwner) {
JPopupMenu popup = new JPopupMenu();
List<SPServerInfo> servers = context.getEnterpriseServers(true);
AbstractAction configureServersAction = makeServerManagerAction(context, dialogOwner);
popup.add(configureServersAction);
if (servers.isEmpty()) {
JMenuItem mi = new JMenuItem("Searching for servers...");
mi.setEnabled(false);
popup.add(mi);
} else {
for (SPServerInfo si : servers) {
popup.add(new LogInToServerAction(dialogOwner, si, context));
}
}
return popup;
}
private static AbstractAction makeServerManagerAction(
final WabitSwingSessionContext context,
final Component dialogOwner) {
return new AbstractAction("Configure Server Connections...") {
public void actionPerformed(ActionEvent e) {
final JDialog d = SPSUtils.makeOwnedDialog(dialogOwner, "Server Connections");
Runnable closeAction = new Runnable() {
public void run() {
d.dispose();
}
};
ServerInfoManager sim = new ServerInfoManager(context, dialogOwner, closeAction);
d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
d.setContentPane(sim.getPanel());
SPSUtils.makeJDialogCancellable(d, null);
d.pack();
d.setLocationRelativeTo(dialogOwner);
d.setVisible(true);
}
};
}
/**
* Creates a new server list menu that registers itself as a listener on the
* context's JmDNS instance. This menu will alter its contents to match the
* set of currently-available servers on the network.
*
* @param context
* The context whose JmDNS instance to use. This is also the
* context that will own any sessions created on the server.
*/
public ServerListMenu(
WabitSwingSessionContext context,
String name,
Component dialogOwner,
ServerListMenuItemFactory itemFactory) {
super(name);
super.setIcon(SPSUtils.createIcon("wabitServer-16", ""));
this.context = context;
this.dialogOwner = dialogOwner;
this.itemFactory = itemFactory;
this.serverManagerAction = makeServerManagerAction(context, dialogOwner);
refillMenu.run();
if (context.getJmDNS() != null) {
context.getJmDNS().addServiceListener(
WabitSessionContext.WABIT_ENTERPRISE_SERVER_MDNS_TYPE, serviceListener);
}
//XXX This listener should be removed from the context when the session is closed
//XXX and the list goes away. We are changing this list to be in the context in
//XXX the UI remake which will make this change unnecessary then.
context.addServerListListener(new ServerListListener() {
public void serverRemoved(ServerListEvent e) {
SwingUtilities.invokeLater(refillMenu);
}
public void serverAdded(ServerListEvent e) {
SwingUtilities.invokeLater(refillMenu);
}
});
}
private final Runnable refillMenu = new Runnable() {
public void run() {
List<SPServerInfo> servers = context.getEnterpriseServers(true);
logger.debug("Refilling server menu. servers = " + servers);
removeAll();
add(serverManagerAction);
if (servers.isEmpty()) {
JMenuItem mi = new JMenuItem("Searching for servers...");
mi.setEnabled(false);
add(mi);
} else {
for (SPServerInfo si : servers) {
add(itemFactory.createMenuEntry(si, dialogOwner));
}
}
}
};
private final ServiceListener serviceListener = new ServiceListener() {
public void serviceAdded(ServiceEvent event) {
rebuildMenu();
}
public void serviceRemoved(ServiceEvent event) {
rebuildMenu();
}
public void serviceResolved(ServiceEvent event) {
rebuildMenu();
}
private void rebuildMenu() {
SwingUtilities.invokeLater(refillMenu);
}
};
}
| gpl-3.0 |
Ninjistix/darkstar | scripts/zones/Konschtat_Highlands/Zone.lua | 2668 | -----------------------------------
--
-- Zone: Konschtat_Highlands (108)
--
-----------------------------------
package.loaded["scripts/zones/Konschtat_Highlands/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Konschtat_Highlands/TextIDs");
require("scripts/globals/icanheararainbow");
require("scripts/globals/chocobo_digging");
require("scripts/globals/conquest");
require("scripts/globals/missions");
local itemMap =
{
-- itemid, abundance, requirement
{ 847, 13, DIGREQ_NONE },
{ 880, 165, DIGREQ_NONE },
{ 690, 68, DIGREQ_NONE },
{ 864, 80, DIGREQ_NONE },
{ 768, 90, DIGREQ_NONE },
{ 869, 63, DIGREQ_NONE },
{ 749, 14, DIGREQ_NONE },
{ 17296, 214, DIGREQ_NONE },
{ 844, 14, DIGREQ_NONE },
{ 868, 45, DIGREQ_NONE },
{ 642, 71, DIGREQ_NONE },
{ 4096, 100, DIGREQ_NONE }, -- all crystals
{ 845, 28, DIGREQ_BORE },
{ 842, 27, DIGREQ_BORE },
{ 843, 23, DIGREQ_BORE },
{ 1845, 22, DIGREQ_BORE },
{ 838, 19, DIGREQ_BORE },
{ 4570, 10, DIGREQ_MODIFIER },
{ 4487, 11, DIGREQ_MODIFIER },
{ 4409, 12, DIGREQ_MODIFIER },
{ 1188, 10, DIGREQ_MODIFIER },
{ 4532, 12, DIGREQ_MODIFIER },
};
local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED };
function onChocoboDig(player, precheck)
return chocoboDig(player, itemMap, precheck, messageArray);
end;
function onInitialize(zone)
end;
function onZoneIn( player, prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos( 521.922, 28.361, 747.85, 45);
end
if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow
cs = 104;
elseif (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then
cs = 106;
end
return cs;
end;
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
function onRegionEnter( player, region)
end;
function onEventUpdate( player, csid, option)
if (csid == 104) then
lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow
elseif (csid == 106) then
if (player:getZPos() > 855) then
player:updateEvent(0,0,0,0,0,2);
elseif (player:getXPos() > 32 and player:getXPos() < 370) then
player:updateEvent(0,0,0,0,0,1);
end
end
end;
function onEventFinish( player, csid, option)
if (csid == 104) then
lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow
end
end;
| gpl-3.0 |
arborrow/moodle-patch_jsea | mod/quiz/backup/moodle2/backup_quiz_stepslib.php | 5635 | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package moodlecore
* @subpackage backup-moodle2
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Define all the backup steps that will be used by the backup_quiz_activity_task
*/
/**
* Define the complete quiz structure for backup, with file and id annotations
*/
class backup_quiz_activity_structure_step extends backup_questions_activity_structure_step {
protected function define_structure() {
// To know if we are including userinfo
$userinfo = $this->get_setting_value('userinfo');
// Define each element separated
$quiz = new backup_nested_element('quiz', array('id'), array(
'name', 'intro', 'introformat', 'timeopen',
'timeclose', 'optionflags', 'penaltyscheme', 'attempts_number',
'attemptonlast', 'grademethod', 'decimalpoints', 'questiondecimalpoints',
'review', 'questionsperpage', 'shufflequestions', 'shuffleanswers',
'questions', 'sumgrades', 'grade', 'timecreated',
'timemodified', 'timelimit', 'password', 'subnet',
'popup', 'delay1', 'delay2', 'showuserpicture',
'showblocks'));
$qinstances = new backup_nested_element('question_instances');
$qinstance = new backup_nested_element('question_instance', array('id'), array(
'question', 'grade'));
$feedbacks = new backup_nested_element('feedbacks');
$feedback = new backup_nested_element('feedback', array('id'), array(
'feedbacktext', 'feedbacktextformat', 'mingrade', 'maxgrade'));
$overrides = new backup_nested_element('overrides');
$override = new backup_nested_element('override', array('id'), array(
'userid', 'groupid', 'timeopen', 'timeclose',
'timelimit', 'attempts', 'password'));
$grades = new backup_nested_element('grades');
$grade = new backup_nested_element('grade', array('id'), array(
'userid', 'gradeval', 'timemodified'));
$attempts = new backup_nested_element('attempts');
$attempt = new backup_nested_element('attempt', array('id'), array(
'uniqueid', 'userid', 'attemptnum', 'sumgrades',
'timestart', 'timefinish', 'timemodified', 'layout',
'preview'));
// This module is using questions, so produce the related question states and sessions
// attaching them to the $attempt element based in 'uniqueid' matching
$this->add_question_attempts_states($attempt, 'uniqueid');
$this->add_question_attempts_sessions($attempt, 'uniqueid');
// Build the tree
$quiz->add_child($qinstances);
$qinstances->add_child($qinstance);
$quiz->add_child($feedbacks);
$feedbacks->add_child($feedback);
$quiz->add_child($overrides);
$overrides->add_child($override);
$quiz->add_child($grades);
$grades->add_child($grade);
$quiz->add_child($attempts);
$attempts->add_child($attempt);
// Define sources
$quiz->set_source_table('quiz', array('id' => backup::VAR_ACTIVITYID));
$qinstance->set_source_table('quiz_question_instances', array('quiz' => backup::VAR_PARENTID));
$feedback->set_source_table('quiz_feedback', array('quizid' => backup::VAR_PARENTID));
// Quiz overrides to backup are different depending of user info
$overrideparams = array('quiz' => backup::VAR_PARENTID);
if (!$userinfo) { // Without userinfo, skip user overrides
$overrideparams['userid'] = backup_helper::is_sqlparam(null);
}
$override->set_source_table('quiz_overrides', $overrideparams);
// All the rest of elements only happen if we are including user info
if ($userinfo) {
$grade->set_source_table('quiz_grades', array('quiz' => backup::VAR_PARENTID));
$attempt->set_source_table('quiz_attempts', array('quiz' => backup::VAR_PARENTID));
}
// Define source alias
$quiz->set_source_alias('attempts', 'attempts_number');
$grade->set_source_alias('grade', 'gradeval');
$attempt->set_source_alias('attempt', 'attemptnum');
// Define id annotations
$qinstance->annotate_ids('question', 'question');
$override->annotate_ids('user', 'userid');
$override->annotate_ids('group', 'groupid');
$grade->annotate_ids('user', 'userid');
$attempt->annotate_ids('user', 'userid');
// Define file annotations
$quiz->annotate_files('mod_quiz', 'intro', null); // This file area hasn't itemid
$feedback->annotate_files('mod_quiz', 'feedback', 'id');
// Return the root element (quiz), wrapped into standard activity structure
return $this->prepare_activity_structure($quiz);
}
}
| gpl-3.0 |
rneiss/PocketTorah | ios/Pods/Flipper-RSocket/rsocket/framing/Framer.cpp | 6389 | // Copyright (c) Facebook, Inc. and its affiliates.
//
// 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.
#include "rsocket/framing/Framer.h"
#include <folly/io/Cursor.h>
#include "rsocket/framing/FrameSerializer_v1_0.h"
namespace rsocket {
namespace {
constexpr size_t kFrameLengthFieldLengthV1_0 = 3;
constexpr auto kMaxFrameLength = 0xFFFFFF; // 24bit max value
template <typename TWriter>
void writeFrameLength(
TWriter& cur,
size_t frameLength,
size_t frameSizeFieldLength) {
DCHECK(frameSizeFieldLength > 0);
// starting from the highest byte
// frameSizeFieldLength == 3 => shift = [16,8,0]
// frameSizeFieldLength == 4 => shift = [24,16,8,0]
auto shift = (frameSizeFieldLength - 1) * 8;
while (frameSizeFieldLength--) {
const auto byte = (frameLength >> shift) & 0xFF;
cur.write(static_cast<uint8_t>(byte));
shift -= 8;
}
}
} // namespace
/// Get the byte size of the frame length field in an RSocket frame.
size_t Framer::frameSizeFieldLength() const {
DCHECK_NE(protocolVersion_, ProtocolVersion::Unknown);
if (protocolVersion_ < FrameSerializerV1_0::Version) {
return sizeof(int32_t);
} else {
return 3; // bytes
}
}
/// Get the minimum size for a valid RSocket frame (including its frame length
/// field).
size_t Framer::minimalFrameLength() const {
DCHECK_NE(protocolVersion_, ProtocolVersion::Unknown);
return FrameSerializerV1_0::kFrameHeaderSize;
}
/// Compute the length of the entire frame (including its frame length field),
/// if given only its frame length field.
size_t Framer::frameSizeWithLengthField(size_t frameSize) const {
return protocolVersion_ < FrameSerializerV1_0::Version
? frameSize
: frameSize + frameSizeFieldLength();
}
/// Compute the length of the frame (excluding its frame length field), if given
/// only its frame length field.
size_t Framer::frameSizeWithoutLengthField(size_t frameSize) const {
DCHECK_NE(protocolVersion_, ProtocolVersion::Unknown);
return protocolVersion_ < FrameSerializerV1_0::Version
? frameSize - frameSizeFieldLength()
: frameSize;
}
size_t Framer::readFrameLength() const {
const auto fieldLength = frameSizeFieldLength();
DCHECK_GT(fieldLength, 0);
folly::io::Cursor cur{payloadQueue_.front()};
size_t frameLength = 0;
// Reading of arbitrary-sized big-endian integer.
for (size_t i = 0; i < fieldLength; ++i) {
frameLength <<= 8;
frameLength |= cur.read<uint8_t>();
}
return frameLength;
}
void Framer::addFrameChunk(std::unique_ptr<folly::IOBuf> payload) {
payloadQueue_.append(std::move(payload));
parseFrames();
}
void Framer::parseFrames() {
if (payloadQueue_.empty() || !ensureOrAutodetectProtocolVersion()) {
// At this point we dont have enough bytes on the wire or we errored out.
return;
}
while (!payloadQueue_.empty()) {
auto const frameSizeFieldLen = frameSizeFieldLength();
if (payloadQueue_.chainLength() < frameSizeFieldLen) {
// We don't even have the next frame size value.
break;
}
auto const nextFrameSize = readFrameLength();
if (nextFrameSize < minimalFrameLength()) {
error("Invalid frame - Frame size smaller than minimum");
break;
}
if (payloadQueue_.chainLength() < frameSizeWithLengthField(nextFrameSize)) {
// Need to accumulate more data.
break;
}
auto payloadSize = frameSizeWithoutLengthField(nextFrameSize);
if (stripFrameLengthField_) {
payloadQueue_.trimStart(frameSizeFieldLen);
} else {
payloadSize += frameSizeFieldLen;
}
DCHECK_GT(payloadSize, 0)
<< "folly::IOBufQueue::split(0) returns a nullptr, can't have that";
auto nextFrame = payloadQueue_.split(payloadSize);
onFrame(std::move(nextFrame));
}
}
bool Framer::ensureOrAutodetectProtocolVersion() {
if (protocolVersion_ != ProtocolVersion::Unknown) {
return true;
}
const auto minBytesNeeded =
FrameSerializerV1_0::kMinBytesNeededForAutodetection;
DCHECK_GT(minBytesNeeded, 0);
if (payloadQueue_.chainLength() < minBytesNeeded) {
return false;
}
DCHECK_GT(minBytesNeeded, kFrameLengthFieldLengthV1_0);
auto const& firstFrame = *payloadQueue_.front();
const auto detectedV1 = FrameSerializerV1_0::detectProtocolVersion(
firstFrame, kFrameLengthFieldLengthV1_0);
if (detectedV1 != ProtocolVersion::Unknown) {
protocolVersion_ = FrameSerializerV1_0::Version;
return true;
}
error("Could not detect protocol version from data");
return false;
}
std::unique_ptr<folly::IOBuf> Framer::prependSize(
std::unique_ptr<folly::IOBuf> payload) {
CHECK(payload);
const auto frameSizeFieldLengthValue = frameSizeFieldLength();
const auto payloadLength = payload->computeChainDataLength();
CHECK_LE(payloadLength, kMaxFrameLength)
<< "payloadLength: " << payloadLength
<< " kMaxFrameLength: " << kMaxFrameLength;
if (payload->headroom() >= frameSizeFieldLengthValue) {
// move the data pointer back and write value to the payload
payload->prepend(frameSizeFieldLengthValue);
folly::io::RWPrivateCursor cur(payload.get());
writeFrameLength(cur, payloadLength, frameSizeFieldLengthValue);
return payload;
} else {
auto newPayload = folly::IOBuf::createCombined(frameSizeFieldLengthValue);
folly::io::Appender appender(newPayload.get(), /* do not grow */ 0);
writeFrameLength(appender, payloadLength, frameSizeFieldLengthValue);
newPayload->appendChain(std::move(payload));
return newPayload;
}
}
StreamId Framer::peekStreamId(
const folly::IOBuf& frame,
bool skipFrameLengthBytes) const {
return FrameSerializer::peekStreamId(
protocolVersion_, frame, skipFrameLengthBytes)
.value();
}
std::unique_ptr<folly::IOBuf> Framer::drainPayloadQueue() {
return payloadQueue_.move();
}
} // namespace rsocket
| gpl-3.0 |
bhattis/native-script-demo | node_modules/tns-core-modules/file-system/file-system-access.android.js | 12845 | var textModule = require("text");
var utils = require("utils/utils");
var FileSystemAccess = (function () {
function FileSystemAccess() {
this._pathSeparator = "/";
}
FileSystemAccess.prototype.getLastModified = function (path) {
var javaFile = new java.io.File(path);
return new Date(javaFile.lastModified());
};
FileSystemAccess.prototype.getParent = function (path, onError) {
try {
var javaFile = new java.io.File(path);
var parent = javaFile.getParentFile();
return { path: parent.getAbsolutePath(), name: parent.getName() };
}
catch (exception) {
if (onError) {
onError(exception);
}
return undefined;
}
};
FileSystemAccess.prototype.getFile = function (path, onError) {
return this.ensureFile(new java.io.File(path), false, onError);
};
FileSystemAccess.prototype.getFolder = function (path, onError) {
var javaFile = new java.io.File(path);
var dirInfo = this.ensureFile(javaFile, true, onError);
if (!dirInfo) {
return undefined;
}
return { path: dirInfo.path, name: dirInfo.name };
};
FileSystemAccess.prototype.eachEntity = function (path, onEntity, onError) {
if (!onEntity) {
return;
}
this.enumEntities(path, onEntity, onError);
};
FileSystemAccess.prototype.getEntities = function (path, onError) {
var fileInfos = new Array();
var onEntity = function (entity) {
fileInfos.push(entity);
return true;
};
var errorOccurred;
var localError = function (error) {
if (onError) {
onError(error);
}
errorOccurred = true;
};
this.enumEntities(path, onEntity, localError);
if (!errorOccurred) {
return fileInfos;
}
return null;
};
FileSystemAccess.prototype.fileExists = function (path) {
var file = new java.io.File(path);
return file.exists();
};
FileSystemAccess.prototype.folderExists = function (path) {
var file = new java.io.File(path);
return file.exists() && file.isDirectory();
};
FileSystemAccess.prototype.deleteFile = function (path, onError) {
try {
var javaFile = new java.io.File(path);
if (!javaFile.isFile()) {
if (onError) {
onError({ message: "The specified parameter is not a File entity." });
}
return;
}
if (!javaFile.delete()) {
if (onError) {
onError({ message: "File deletion failed" });
}
}
}
catch (exception) {
if (onError) {
onError(exception);
}
}
};
FileSystemAccess.prototype.deleteFolder = function (path, onError) {
try {
var javaFile = new java.io.File(path);
if (!javaFile.getCanonicalFile().isDirectory()) {
if (onError) {
onError({ message: "The specified parameter is not a Folder entity." });
}
return;
}
this.deleteFolderContent(javaFile);
if (!javaFile.delete()) {
if (onError) {
onError({ message: "Folder deletion failed." });
}
}
}
catch (exception) {
if (onError) {
onError(exception);
}
}
};
FileSystemAccess.prototype.emptyFolder = function (path, onError) {
try {
var javaFile = new java.io.File(path);
if (!javaFile.getCanonicalFile().isDirectory()) {
if (onError) {
onError({ message: "The specified parameter is not a Folder entity." });
}
return;
}
this.deleteFolderContent(javaFile);
}
catch (exception) {
if (onError) {
onError(exception);
}
}
};
FileSystemAccess.prototype.rename = function (path, newPath, onError) {
var javaFile = new java.io.File(path);
if (!javaFile.exists()) {
if (onError) {
onError(new Error("The file to rename does not exist"));
}
return;
}
var newFile = new java.io.File(newPath);
if (newFile.exists()) {
if (onError) {
onError(new Error("A file with the same name already exists."));
}
return;
}
if (!javaFile.renameTo(newFile)) {
if (onError) {
onError(new Error("Failed to rename file '" + path + "' to '" + newPath + "'"));
}
}
};
FileSystemAccess.prototype.getDocumentsFolderPath = function () {
var dir = utils.ad.getApplicationContext().getFilesDir();
return dir.getAbsolutePath();
};
FileSystemAccess.prototype.getLogicalRootPath = function () {
var dir = utils.ad.getApplicationContext().getFilesDir();
return dir.getCanonicalPath();
};
FileSystemAccess.prototype.getTempFolderPath = function () {
var dir = utils.ad.getApplicationContext().getCacheDir();
return dir.getAbsolutePath();
};
FileSystemAccess.prototype.getCurrentAppPath = function () {
return this.getLogicalRootPath() + "/app";
};
FileSystemAccess.prototype.read = function (path, onError) {
try {
var javaFile = new java.io.File(path);
var stream = new java.io.FileInputStream(javaFile);
var bytes = Array.create("byte", javaFile.length());
var dataInputStream = new java.io.DataInputStream(stream);
dataInputStream.readFully(bytes);
return bytes;
}
catch (exception) {
if (onError) {
onError(exception);
}
}
};
FileSystemAccess.prototype.write = function (path, bytes, onError) {
try {
var javaFile = new java.io.File(path);
var stream = new java.io.FileOutputStream(javaFile);
stream.write(bytes, 0, bytes.length);
stream.close();
}
catch (exception) {
if (onError) {
onError(exception);
}
}
};
FileSystemAccess.prototype.readText = function (path, onError, encoding) {
try {
var types = require("utils/types");
var javaFile = new java.io.File(path);
var stream = new java.io.FileInputStream(javaFile);
var actualEncoding = encoding;
if (!actualEncoding) {
actualEncoding = textModule.encoding.UTF_8;
}
var reader = new java.io.InputStreamReader(stream, actualEncoding);
var bufferedReader = new java.io.BufferedReader(reader);
var line = undefined;
var result = "";
while (true) {
line = bufferedReader.readLine();
if (types.isNullOrUndefined(line)) {
break;
}
if (result.length > 0) {
result += "\n";
}
result += line;
}
if (actualEncoding === textModule.encoding.UTF_8) {
result = FileSystemAccess._removeUtf8Bom(result);
}
bufferedReader.close();
return result;
}
catch (exception) {
if (onError) {
onError(exception);
}
}
};
FileSystemAccess._removeUtf8Bom = function (s) {
if (s.charCodeAt(0) === 0xFEFF) {
s = s.slice(1);
}
return s;
};
FileSystemAccess.prototype.writeText = function (path, content, onError, encoding) {
try {
var javaFile = new java.io.File(path);
var stream = new java.io.FileOutputStream(javaFile);
var actualEncoding = encoding;
if (!actualEncoding) {
actualEncoding = textModule.encoding.UTF_8;
}
var writer = new java.io.OutputStreamWriter(stream, actualEncoding);
writer.write(content);
writer.close();
}
catch (exception) {
if (onError) {
onError(exception);
}
}
};
FileSystemAccess.prototype.deleteFolderContent = function (file) {
var filesList = file.listFiles();
if (filesList.length === 0) {
return true;
}
var i, childFile, success = false;
for (i = 0; i < filesList.length; i++) {
childFile = filesList[i];
if (childFile.getCanonicalFile().isDirectory()) {
success = this.deleteFolderContent(childFile);
if (!success) {
break;
}
}
success = childFile.delete();
}
return success;
};
FileSystemAccess.prototype.ensureFile = function (javaFile, isFolder, onError) {
try {
if (!javaFile.exists()) {
var created;
if (isFolder) {
created = javaFile.mkdirs();
}
else {
javaFile.getParentFile().mkdirs();
created = javaFile.createNewFile();
}
if (!created) {
if (onError) {
onError("Failed to create new java File for path " + javaFile.getAbsolutePath());
}
return undefined;
}
else {
javaFile.setReadable(true);
javaFile.setWritable(true);
}
}
var path = javaFile.getAbsolutePath();
return { path: path, name: javaFile.getName(), extension: this.getFileExtension(path) };
}
catch (exception) {
if (onError) {
onError(exception);
}
return undefined;
}
};
FileSystemAccess.prototype.getFileExtension = function (path) {
var dotIndex = path.lastIndexOf(".");
if (dotIndex && dotIndex >= 0 && dotIndex < path.length) {
return path.substring(dotIndex);
}
return "";
};
FileSystemAccess.prototype.enumEntities = function (path, callback, onError) {
try {
var javaFile = new java.io.File(path);
if (!javaFile.getCanonicalFile().isDirectory()) {
if (onError) {
onError("There is no folder existing at path " + path);
}
return;
}
var filesList = javaFile.listFiles();
var length = filesList.length;
var i;
var info;
var retVal;
for (i = 0; i < length; i++) {
javaFile = filesList[i];
info = {
path: javaFile.getAbsolutePath(),
name: javaFile.getName()
};
if (javaFile.isFile()) {
info.extension = this.getFileExtension(info.path);
}
retVal = callback(info);
if (retVal === false) {
break;
}
}
}
catch (exception) {
if (onError) {
onError(exception);
}
}
};
FileSystemAccess.prototype.getPathSeparator = function () {
return this._pathSeparator;
};
FileSystemAccess.prototype.normalizePath = function (path) {
var file = new java.io.File(path);
return file.getAbsolutePath();
};
FileSystemAccess.prototype.joinPath = function (left, right) {
var file1 = new java.io.File(left);
var file2 = new java.io.File(file1, right);
return file2.getAbsolutePath();
};
FileSystemAccess.prototype.joinPaths = function (paths) {
if (!paths || paths.length === 0) {
return "";
}
if (paths.length === 1) {
return paths[0];
}
var i, result = paths[0];
for (i = 1; i < paths.length; i++) {
result = this.joinPath(result, paths[i]);
}
return this.normalizePath(result);
};
return FileSystemAccess;
}());
exports.FileSystemAccess = FileSystemAccess;
//# sourceMappingURL=file-system-access.android.js.map | gpl-3.0 |
xiaoxianlink/zhideinfo | simplewind/Lib/Extend/ThinkSDK/sdk/DiandianSDK.class.php | 2475 | <?php
// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://topthink.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 杨维杰 <zuojiazi.cn@gmail.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
// | SinaSDK.class.php 2013-03-01
// +----------------------------------------------------------------------
class DiandianSDK extends ThinkOauth{
/**
* 获取requestCode的api接口
* @var string
*/
protected $GetRequestCodeURL = 'https://api.diandian.com/oauth/authorize';
/**
* 获取access_token的api接口
* @var string
*/
protected $GetAccessTokenURL = 'https://api.diandian.com/oauth/token';
/**
* API根路径
* @var string
*/
protected $ApiBase = 'https://api.diandian.com/v1/';
/**
* 组装接口调用参数 并调用接口
* @param string $api 点点网API
* @param string $param 调用API的额外参数
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'GET', $multi = false){
/* 点点网调用公共参数 */
$params = array(
'access_token' => $this->Token['access_token'],
);
$data = $this->http($this->url($api, '.json'), $this->param($params, $param), $method);
return json_decode($data, true);
}
/**
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result, $extend){
$data = json_decode($result, true);
if($data['access_token'] && $data['expires_in'] && $data['token_type'] && $data['uid']){
$data['openid'] = $data['uid'];
unset($data['uid']);
return $data;
} else
throw new Exception("获取点点网ACCESS_TOKEN出错:{$data['error']}");
}
/**
* 获取当前授权应用的openid
* @return string
*/
public function openid(){
$data = $this->Token;
if(isset($data['openid']))
return $data['openid'];
else
throw new Exception('没有获取到点点网用户ID!');
}
} | gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/scroll_of_aero_v.lua | 473 | -----------------------------------------
-- ID: 4766
-- Scroll of Aero V
-- Teaches the black magic Aero V
-----------------------------------------
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
return target:canLearnSpell(158);
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addSpell(158);
end; | gpl-3.0 |
kwanghoon/MySmallBasic | MySmallBasic/blockly/msg/js/bcc.js | 39019 | // This file was automatically generated. Do not modify.
'use strict';
goog.provide('Blockly.Msg.bcc');
goog.require('Blockly.Msg');
Blockly.Msg.ADD_COMMENT = "افزودن نظر";
Blockly.Msg.CANNOT_DELETE_VARIABLE_PROCEDURE = "Can't delete the variable '%1' because it's part of the definition of the function '%2'"; // untranslated
Blockly.Msg.CHANGE_VALUE_TITLE = "تغییر مقدار:";
Blockly.Msg.CLEAN_UP = "Clean up Blocks"; // untranslated
Blockly.Msg.COLLAPSE_ALL = "فروپاشی بلوکها";
Blockly.Msg.COLLAPSE_BLOCK = "فروپاشی بلوک";
Blockly.Msg.COLOUR_BLEND_COLOUR1 = "رنگ ۱";
Blockly.Msg.COLOUR_BLEND_COLOUR2 = "رنگ ۲";
Blockly.Msg.COLOUR_BLEND_HELPURL = "http://meyerweb.com/eric/tools/color-blend/"; // untranslated
Blockly.Msg.COLOUR_BLEND_RATIO = "نسبت";
Blockly.Msg.COLOUR_BLEND_TITLE = "مخلوط";
Blockly.Msg.COLOUR_BLEND_TOOLTIP = "دو رنگ را با نسبت مشخصشده مخلوط میکند (۰٫۰ - ۱٫۰)";
Blockly.Msg.COLOUR_PICKER_HELPURL = "https://fa.wikipedia.org/wiki/%D8%B1%D9%86%DA%AF";
Blockly.Msg.COLOUR_PICKER_TOOLTIP = "انتخاب یک رنگ از تختهرنگ.";
Blockly.Msg.COLOUR_RANDOM_HELPURL = "http://randomcolour.com"; // untranslated
Blockly.Msg.COLOUR_RANDOM_TITLE = "رنگ تصادفی";
Blockly.Msg.COLOUR_RANDOM_TOOLTIP = "انتخاب یک رنگ به شکل تصادفی.";
Blockly.Msg.COLOUR_RGB_BLUE = "آبی";
Blockly.Msg.COLOUR_RGB_GREEN = "سبز";
Blockly.Msg.COLOUR_RGB_HELPURL = "http://www.december.com/html/spec/colorper.html"; // untranslated
Blockly.Msg.COLOUR_RGB_RED = "قرمز";
Blockly.Msg.COLOUR_RGB_TITLE = "رنگ با";
Blockly.Msg.COLOUR_RGB_TOOLTIP = "ساخت یک رنگ با مقدار مشخصشدهای از قرمز، سبز و آبی. همهٔ مقادیر باید بین ۰ تا ۱۰۰ باشند.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = "https://github.com/google/blockly/wiki/Loops#loop-termination-blocks"; // untranslated
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = "شکستن حلقه";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = "ادامه با تکرار بعدی حلقه";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = "شکستن حلقهٔ شامل.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = "پریدن از بقیهٔ حلقه و ادامه با تکرار بعدی.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = "اخطار: این بلوک ممکن است فقط داخل یک حلقه استفاده شود.";
Blockly.Msg.CONTROLS_FOREACH_HELPURL = "https://github.com/google/blockly/wiki/Loops#for-each"; // untranslated
Blockly.Msg.CONTROLS_FOREACH_TITLE = "برای هر مورد %1 در فهرست %2";
Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = "برای هر مورد در این فهرست، تنظیم متغیر «%1» به مورد و انجام تعدادی عبارت.";
Blockly.Msg.CONTROLS_FOR_HELPURL = "https://github.com/google/blockly/wiki/Loops#count-with"; // untranslated
Blockly.Msg.CONTROLS_FOR_TITLE = "با تعداد %1 از %2 به %3 با گامهای %4";
Blockly.Msg.CONTROLS_FOR_TOOLTIP = "متغیر %1 را در مقادیر شروعشده از عدد انتهای به عدد انتهایی را دارد، با فواصل مشخصشده میشمارد و این بلوک مشخصشده را انجام میدهد.";
Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "افزودن یک شرط به بلوک اگر.";
Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "اضافهکردن نهایی، گرفتن همهٔ شرایط به بلوک اگر.";
Blockly.Msg.CONTROLS_IF_HELPURL = "https://github.com/google/blockly/wiki/IfElse"; // untranslated
Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "اضافه، حذف یا ترتیبسازی قسمتها برای تنظیم مجدد این بلوک اگر مسدود است.";
Blockly.Msg.CONTROLS_IF_MSG_ELSE = "آنگاه";
Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "اگر آنگاه";
Blockly.Msg.CONTROLS_IF_MSG_IF = "اگر";
Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "اگر یک مقدار صحیح است، سپس چند عبارت را انجام بده.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "اگر یک مقدار صحیح است، اول بلوک اول عبارات را انجام بده. در غیر این صورت بلوک دوم عبارات انجام بده.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "اگر مقدار اول صحیح بود، از آن بلوک اول عبارات را انجام بده. در غیر این صورت، اگر مقدار دوم صحیح است، بلوک دوم عبارات را انجام بده.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "اگر مقدار اول درست است، بلوک اول عبارات را انجام بده. در غیر این صورت، اگر مقدار دوم درست باشد بلوک دوم عبارات را انجام بده. اگر هیچ از مقادیر درست نبود، آخرین بلوک عبارات را انجام بده.";
Blockly.Msg.CONTROLS_REPEAT_HELPURL = "https://fa.wikipedia.org/wiki/%D8%AD%D9%84%D9%82%D9%87_%D9%81%D9%88%D8%B1";
Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = "انجام";
Blockly.Msg.CONTROLS_REPEAT_TITLE = "%1 بار تکرار";
Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "انجام چند عبارت چندین بار.";
Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = "https://github.com/google/blockly/wiki/Loops#repeat"; // untranslated
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = "تکرار تا";
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = "تکرار در حالی که";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "تا زمانی که یک مقدار ناصحیح است، چند عبارت را انجام بده.";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "تا زمانی که یک مقدار صحیح است، چند عبارت را انجام بده.";
Blockly.Msg.DELETE_ALL_BLOCKS = "Delete all %1 blocks?"; // untranslated
Blockly.Msg.DELETE_BLOCK = "حذف بلوک";
Blockly.Msg.DELETE_VARIABLE = "Delete the '%1' variable"; // untranslated
Blockly.Msg.DELETE_VARIABLE_CONFIRMATION = "Delete %1 uses of the '%2' variable?"; // untranslated
Blockly.Msg.DELETE_X_BLOCKS = "حذف بلوکهای %1";
Blockly.Msg.DISABLE_BLOCK = "غیرفعالسازی بلوک";
Blockly.Msg.DUPLICATE_BLOCK = "تکراری";
Blockly.Msg.ENABLE_BLOCK = "فعالسازی بلوک";
Blockly.Msg.EXPAND_ALL = "گسترش بلوکها";
Blockly.Msg.EXPAND_BLOCK = "گسترش بلوک";
Blockly.Msg.EXTERNAL_INPUTS = "ورودیهای خارجی";
Blockly.Msg.HELP = "کومک";
Blockly.Msg.INLINE_INPUTS = "ورودیهای درون خطی";
Blockly.Msg.IOS_CANCEL = "Cancel"; // untranslated
Blockly.Msg.IOS_ERROR = "Error"; // untranslated
Blockly.Msg.IOS_OK = "OK"; // untranslated
Blockly.Msg.IOS_PROCEDURES_ADD_INPUT = "+ Add Input"; // untranslated
Blockly.Msg.IOS_PROCEDURES_ALLOW_STATEMENTS = "Allow statements"; // untranslated
Blockly.Msg.IOS_PROCEDURES_DUPLICATE_INPUTS_ERROR = "This function has duplicate inputs."; // untranslated
Blockly.Msg.IOS_PROCEDURES_INPUTS = "INPUTS"; // untranslated
Blockly.Msg.IOS_VARIABLES_ADD_BUTTON = "Add"; // untranslated
Blockly.Msg.IOS_VARIABLES_ADD_VARIABLE = "+ Add Variable"; // untranslated
Blockly.Msg.IOS_VARIABLES_DELETE_BUTTON = "Delete"; // untranslated
Blockly.Msg.IOS_VARIABLES_EMPTY_NAME_ERROR = "You can't use an empty variable name."; // untranslated
Blockly.Msg.IOS_VARIABLES_RENAME_BUTTON = "Rename"; // untranslated
Blockly.Msg.IOS_VARIABLES_VARIABLE_NAME = "Variable name"; // untranslated
Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-empty-list"; // untranslated
Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "ایجاد فهرست خالی";
Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "فهرستی با طول صفر شامل هیچ رکورد دادهای بر میگرداند.";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "فهرست";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "اضافهکردن، حذفکردن یا ترتیبسازی مجدد بخشها این بلوک فهرستی.";
Blockly.Msg.LISTS_CREATE_WITH_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated
Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "ایجاد فهرست با";
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "اضافهکردن یک مورد به فهرست.";
Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "فهرستی از هر عددی از موارد میسازد.";
Blockly.Msg.LISTS_GET_INDEX_FIRST = "اولین";
Blockly.Msg.LISTS_GET_INDEX_FROM_END = "# از انتها";
Blockly.Msg.LISTS_GET_INDEX_FROM_START = "#"; // untranslated
Blockly.Msg.LISTS_GET_INDEX_GET = "گرفتن";
Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "گرفتن و حذفکردن";
Blockly.Msg.LISTS_GET_INDEX_LAST = "اهرین";
Blockly.Msg.LISTS_GET_INDEX_RANDOM = "تصادفی";
Blockly.Msg.LISTS_GET_INDEX_REMOVE = "حذفکردن";
Blockly.Msg.LISTS_GET_INDEX_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "اولین مورد یک فهرست را بر میگرداند.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM = "موردی در محل مشخصشده بر میگرداند.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "آخرین مورد در یک فهرست را بر میگرداند.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "یک مورد تصادفی در یک فهرست بر میگرداند.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "اولین مورد مشخصشده در فهرست را حذف و بر میگرداند.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM = "مورد در محل مشخصشده در فهرست را حذف و بر میگرداند.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "آخرین مورد مشخصشده در فهرست را حذف و بر میگرداند.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "مورد تصادفیای را در فهرست حذف و بر میگرداند.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "اولین مورد را در یک فهرست حذف میکند.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM = "مورد مشخصشده در موقعیت مشخص در یک فهرست را حذف و بر میگرداند.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "آخرین مورد را در یک فهرست حذف میکند.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "یک مورد تصادفی را یک فهرست حذف میکند.";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "به # از انتها";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "به #";
Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "به آخرین";
Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "گرفتن زیرمجموعهای از ابتدا";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "گرفتن زیرمجموعهای از # از انتها";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "گرفتن زیرمجموعهای از #";
Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "کپی از قسمت مشخصشدهٔ لیست درست میکند.";
Blockly.Msg.LISTS_INDEX_FROM_END_TOOLTIP = "%1 آخرین مورد است.";
Blockly.Msg.LISTS_INDEX_FROM_START_TOOLTIP = "%1 اولین مورد است.";
Blockly.Msg.LISTS_INDEX_OF_FIRST = "آخرین رخداد متن را بیاب";
Blockly.Msg.LISTS_INDEX_OF_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list"; // untranslated
Blockly.Msg.LISTS_INDEX_OF_LAST = "یافتن آخرین رخداد مورد";
Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "شاخصی از اولین/آخرین رخداد مورد در فهرست را بر میگرداند. %1 بر میگرداند اگر متن موجود نبود.";
Blockly.Msg.LISTS_INLIST = "در فهرست";
Blockly.Msg.LISTS_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#is-empty"; // untranslated
Blockly.Msg.LISTS_ISEMPTY_TITLE = "%1 خالی است";
Blockly.Msg.LISTS_ISEMPTY_TOOLTIP = "اگر فهرست خالی است مقدار صجیج بر میگرداند.";
Blockly.Msg.LISTS_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Lists#length-of"; // untranslated
Blockly.Msg.LISTS_LENGTH_TITLE = "طول %1";
Blockly.Msg.LISTS_LENGTH_TOOLTIP = "طول یک فهرست را برمیگرداند.";
Blockly.Msg.LISTS_REPEAT_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated
Blockly.Msg.LISTS_REPEAT_TITLE = "فهرستی با %1 تکرارشده به اندازهٔ %2 میسازد";
Blockly.Msg.LISTS_REPEAT_TOOLTIP = "فهرستی شامل مقادیر دادهشدهٔ تکرار شده عدد مشخصشده میسازد.";
Blockly.Msg.LISTS_REVERSE_HELPURL = "https://github.com/google/blockly/wiki/Lists#reversing-a-list"; // untranslated
Blockly.Msg.LISTS_REVERSE_MESSAGE0 = "reverse %1"; // untranslated
Blockly.Msg.LISTS_REVERSE_TOOLTIP = "Reverse a copy of a list."; // untranslated
Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://github.com/google/blockly/wiki/Lists#in-list--set"; // untranslated
Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "بهعنوان";
Blockly.Msg.LISTS_SET_INDEX_INSERT = "درج در";
Blockly.Msg.LISTS_SET_INDEX_SET = "مجموعه";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "موردی به ته فهرست اضافه میکند.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM = "موردی در موقعیت مشخصشده در یک فهرست اضافه میکند.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "موردی به ته فهرست الحاق میکند.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "مورد را به صورت تصادفی در یک فهرست میافزاید.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "اولین مورد در یک فهرست را تعیین میکند.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM = "مورد مشخصشده در یک فهرست را قرار میدهد.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "آخرین مورد در یک فهرست را تعیین میکند.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "یک مورد تصادفی در یک فهرست را تعیین میکند.";
Blockly.Msg.LISTS_SORT_HELPURL = "https://github.com/google/blockly/wiki/Lists#sorting-a-list"; // untranslated
Blockly.Msg.LISTS_SORT_ORDER_ASCENDING = "ascending"; // untranslated
Blockly.Msg.LISTS_SORT_ORDER_DESCENDING = "descending"; // untranslated
Blockly.Msg.LISTS_SORT_TITLE = "sort %1 %2 %3"; // untranslated
Blockly.Msg.LISTS_SORT_TOOLTIP = "Sort a copy of a list."; // untranslated
Blockly.Msg.LISTS_SORT_TYPE_IGNORECASE = "alphabetic, ignore case"; // untranslated
Blockly.Msg.LISTS_SORT_TYPE_NUMERIC = "numeric"; // untranslated
Blockly.Msg.LISTS_SORT_TYPE_TEXT = "alphabetic"; // untranslated
Blockly.Msg.LISTS_SPLIT_HELPURL = "https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists"; // untranslated
Blockly.Msg.LISTS_SPLIT_LIST_FROM_TEXT = "make list from text"; // untranslated
Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST = "make text from list"; // untranslated
Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN = "Join a list of texts into one text, separated by a delimiter."; // untranslated
Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT = "Split text into a list of texts, breaking at each delimiter."; // untranslated
Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER = "with delimiter"; // untranslated
Blockly.Msg.LOGIC_BOOLEAN_FALSE = "ناصحیح";
Blockly.Msg.LOGIC_BOOLEAN_HELPURL = "https://github.com/google/blockly/wiki/Logic#values"; // untranslated
Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "بازگرداندن یکی از صحیح یا ناصحیح.";
Blockly.Msg.LOGIC_BOOLEAN_TRUE = "صحیح";
Blockly.Msg.LOGIC_COMPARE_HELPURL = "https://fa.wikipedia.org/wiki/%D9%86%D8%A7%D8%A8%D8%B1%D8%A7%D8%A8%D8%B1%DB%8C";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "بازگشت صحیح اگر هر دو ورودی با یکدیگر برابر باشد.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "بازگرداندن صحیح اگر ورودی اول بزرگتر از ورودی دوم باشد.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "بازگرداندن صحیح اگر ورودی اول بزرگتر یا مساوی یا ورودی دوم باشد.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "بازگرداندن صحیح اگر ورودی اول کوچکتر از ورودی دوم باشد.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "بازگرداندن صحیح اگر ورودی اول کوچکتر یا مساوی با ورودی دوم باشد.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "برگرداندن صحیح اگر هر دو ورودی با یکدیگر برابر نباشند.";
Blockly.Msg.LOGIC_NEGATE_HELPURL = "https://github.com/google/blockly/wiki/Logic#not"; // untranslated
Blockly.Msg.LOGIC_NEGATE_TITLE = "نه %1";
Blockly.Msg.LOGIC_NEGATE_TOOLTIP = "صجیج باز میگرداند اگر ورودی نا صحیح باشند. ناصحیح بازمیگرداند اگر ورودی صحیح باشد.";
Blockly.Msg.LOGIC_NULL = "تهی";
Blockly.Msg.LOGIC_NULL_HELPURL = "https://en.wikipedia.org/wiki/Nullable_type"; // untranslated
Blockly.Msg.LOGIC_NULL_TOOLTIP = "تهی بازمیگرداند.";
Blockly.Msg.LOGIC_OPERATION_AND = "و";
Blockly.Msg.LOGIC_OPERATION_HELPURL = "https://github.com/google/blockly/wiki/Logic#logical-operations"; // untranslated
Blockly.Msg.LOGIC_OPERATION_OR = "یا";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "بازگرداندن صحیح اگر هر دو ورودی صحیح باشد.";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "بازگرداندن صحیح اگر یکی از دو ورودی صحیح باشد.";
Blockly.Msg.LOGIC_TERNARY_CONDITION = "آزمایش";
Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:"; // untranslated
Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "اگر ناصحیح";
Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "اگر صحیح";
Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "بررسی وضعیت در «آزمایش». اگر وضعیت صحیح باشد، مقدار «اگر صحیح» را بر میگرداند در غیر اینصورت مقدار «اگر ناصحیح» را.";
Blockly.Msg.MATH_ADDITION_SYMBOL = "+"; // untranslated
Blockly.Msg.MATH_ARITHMETIC_HELPURL = "https://fa.wikipedia.org/wiki/%D8%AD%D8%B3%D8%A7%D8%A8";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "بازگرداندن مقدار جمع دو عدد.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "بازگرداندن باقیماندهٔ دو عدد.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "بازگرداندن تفاوت دو عدد.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "بازگرداندن حاصلضرب دو عدد.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "بازگرداندن اولین عددی که از توان عدد دوم حاصل شده باشد.";
Blockly.Msg.MATH_CHANGE_HELPURL = "https://fa.wikipedia.org/wiki/%D8%A7%D8%B5%D8%B7%D9%84%D8%A7%D8%AD_%D8%A8%D8%B1%D9%86%D8%A7%D9%85%D9%87%E2%80%8C%D9%86%D9%88%DB%8C%D8%B3%DB%8C#.D8.A7.D9.81.D8.B2.D8.A7.DB.8C.D8.B4_.D8.B4.D9.85.D8.A7.D8.B1.D9.86.D8.AF.D9.87";
Blockly.Msg.MATH_CHANGE_TITLE = "تغییر %1 با %2";
Blockly.Msg.MATH_CHANGE_TOOLTIP = "افزودن یک عدد به متغیر '%1'.";
Blockly.Msg.MATH_CONSTANT_HELPURL = "https://fa.wikipedia.org/wiki/%D8%AB%D8%A7%D8%A8%D8%AA_%D8%B1%DB%8C%D8%A7%D8%B6%DB%8C";
Blockly.Msg.MATH_CONSTANT_TOOLTIP = "یکی از مقادیر مشترک را برمیگرداند: π (۳٫۱۴۱…)، e (۲٫۷۱۸...)، φ (۱٫۶۱۸)، sqrt(۲) (۱٫۴۱۴)، sqrt(۱/۲) (۰٫۷۰۷...) و یا ∞ (بینهایت).";
Blockly.Msg.MATH_CONSTRAIN_HELPURL = "https://en.wikipedia.org/wiki/Clamping_(graphics)"; // untranslated
Blockly.Msg.MATH_CONSTRAIN_TITLE = "محدودکردن %1 پایین %2 بالا %3";
Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "محدودکردن یک عدد بین محدودیتهای مشخصشده (بسته).";
Blockly.Msg.MATH_DIVISION_SYMBOL = "÷"; // untranslated
Blockly.Msg.MATH_IS_DIVISIBLE_BY = "تقسیم شده بر";
Blockly.Msg.MATH_IS_EVEN = "زوج است";
Blockly.Msg.MATH_IS_NEGATIVE = "منفی است";
Blockly.Msg.MATH_IS_ODD = "فرد است";
Blockly.Msg.MATH_IS_POSITIVE = "مثبت است";
Blockly.Msg.MATH_IS_PRIME = "عدد اول است";
Blockly.Msg.MATH_IS_TOOLTIP = "بررسی میکند که آیا یک عدد زوج، فرد، اول، کامل، مثبت، منفی یا بخشپذیر عدد خاصی باشد را بررسی میکند. درست یا نادرست باز میگرداند.";
Blockly.Msg.MATH_IS_WHOLE = "کامل است";
Blockly.Msg.MATH_MODULO_HELPURL = "https://fa.wikipedia.org/wiki/%D8%B9%D9%85%D9%84%DB%8C%D8%A7%D8%AA_%D9%BE%DB%8C%D9%85%D8%A7%D9%86%D9%87";
Blockly.Msg.MATH_MODULO_TITLE = "باقیماندهٔ %1 + %2";
Blockly.Msg.MATH_MODULO_TOOLTIP = "باقیماندهٔ تقسیم دو عدد را بر میگرداند.";
Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "×"; // untranslated
Blockly.Msg.MATH_NUMBER_HELPURL = "https://fa.wikipedia.org/wiki/%D8%B9%D8%AF%D8%AF";
Blockly.Msg.MATH_NUMBER_TOOLTIP = "یک عدد.";
Blockly.Msg.MATH_ONLIST_HELPURL = ""; // untranslated
Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "میانگین فهرست";
Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "بزرگترین فهرست";
Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "میانهٔ فهرست";
Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "کوچکترین فهرست";
Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "مد فهرست";
Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "مورد تصادفی از فهرست";
Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "انحراف معیار فهرست";
Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "جمع فهرست";
Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "میانگین (میانگین ریاضی) مقادیر عددی فهرست را بر میگرداند.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "بزرگترین عدد در فهرست را باز میگرداند.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "میانهٔ عدد در فهرست را بر میگرداند.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "کوچکترین عدد در فهرست را باز میگرداند.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "شایعترین قلم(های) در فهرست را بر میگرداند.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "موردی تصادفی از فهرست را بر میگرداند.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "انحراف معیار فهرست را بر میگرداند.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "جمع همهٔ عددهای فهرست را باز میگرداند.";
Blockly.Msg.MATH_POWER_SYMBOL = "^"; // untranslated
Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://fa.wikipedia.org/wiki/%D8%AA%D9%88%D9%84%DB%8C%D8%AF_%D8%A7%D8%B9%D8%AF%D8%A7%D8%AF_%D8%AA%D8%B5%D8%A7%D8%AF%D9%81%DB%8C";
Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "کسر تصادفی";
Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "بازگرداندن کسری تصادفی بین ۰٫۰ (بسته) تا ۱٫۰ (باز).";
Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://fa.wikipedia.org/wiki/%D8%AA%D9%88%D9%84%DB%8C%D8%AF_%D8%A7%D8%B9%D8%AF%D8%A7%D8%AF_%D8%AA%D8%B5%D8%A7%D8%AF%D9%81%DB%8C";
Blockly.Msg.MATH_RANDOM_INT_TITLE = "عدد صحیح تصادفی بین %1 تا %2";
Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "یک عدد تصادفی بین دو مقدار مشخصشده به صورت بسته باز میگرداند.";
Blockly.Msg.MATH_ROUND_HELPURL = "https://fa.wikipedia.org/wiki/%D8%B1%D9%88%DB%8C%D9%87_%28%D8%B9%D9%84%D9%88%D9%85_%D8%B1%D8%A7%DB%8C%D8%A7%D9%86%D9%87%29";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "گردکردن";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "گرد به پایین";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "گرد به بالا";
Blockly.Msg.MATH_ROUND_TOOLTIP = "گردکردن یک عدد به بالا یا پایین.";
Blockly.Msg.MATH_SINGLE_HELPURL = "https://fa.wikipedia.org/wiki/%D8%B1%DB%8C%D8%B4%D9%87_%D8%AF%D9%88%D9%85";
Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "مطلق";
Blockly.Msg.MATH_SINGLE_OP_ROOT = "ریشهٔ دوم";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "قدر مطلق یک عدد را بازمیگرداند.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "بازگرداندن توان e یک عدد.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "لوگاریتم طبیعی یک عدد را باز میگرداند.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "بازگرداندن لگاریتم بر پایهٔ ۱۰ یک عدد.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "منفیشدهٔ یک عدد را باز میگرداند.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "بازگرداندن توان ۱۰ یک عدد.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "ریشهٔ دوم یک عدد را باز میگرداند.";
Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "-"; // untranslated
Blockly.Msg.MATH_TRIG_ACOS = "acos"; // untranslated
Blockly.Msg.MATH_TRIG_ASIN = "asin"; // untranslated
Blockly.Msg.MATH_TRIG_ATAN = "atan"; // untranslated
Blockly.Msg.MATH_TRIG_COS = "cos"; // untranslated
Blockly.Msg.MATH_TRIG_HELPURL = "https://fa.wikipedia.org/wiki/%D8%AA%D8%A7%D8%A8%D8%B9%E2%80%8C%D9%87%D8%A7%DB%8C_%D9%85%D8%AB%D9%84%D8%AB%D8%A7%D8%AA%DB%8C";
Blockly.Msg.MATH_TRIG_SIN = "sin"; // untranslated
Blockly.Msg.MATH_TRIG_TAN = "tan"; // untranslated
Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "بازگرداندن آرککسینوس درجه (نه رادیان).";
Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = "بازگرداندن آرکسینوس درجه (نه رادیان).";
Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "بازگرداندن آرکتانژانت درجه (نه رادیان).";
Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "بازگرداندن کسینوس درجه (نه رادیان).";
Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "بازگرداندن سینوس درجه (نه رادیان).";
Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "بازگرداندن تانژانت یک درجه (نه رادیان).";
Blockly.Msg.NEW_VARIABLE = "متغیر تازه...";
Blockly.Msg.NEW_VARIABLE_TITLE = "نام متغیر تازه:";
Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ""; // untranslated
Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS = "اجازه اظهارات";
Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "با:";
Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "https://fa.wikipedia.org/wiki/%D8%B1%D9%88%DB%8C%D9%87_%28%D8%B9%D9%84%D9%88%D9%85_%D8%B1%D8%A7%DB%8C%D8%A7%D9%86%D9%87%29";
Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "اجرای تابع تعریفشده توسط کاربر «%1».";
Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://fa.wikipedia.org/wiki/%D8%B1%D9%88%DB%8C%D9%87_%28%D8%B9%D9%84%D9%88%D9%85_%D8%B1%D8%A7%DB%8C%D8%A7%D9%86%D9%87%29";
Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "اجرای تابع تعریفشده توسط کاربر «%1» و استفاده از خروجی آن.";
Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS = "با:";
Blockly.Msg.PROCEDURES_CREATE_DO = "ساختن «%1»";
Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT = "Describe this function..."; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_DO = ""; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "انجام چیزی";
Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "به";
Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "تابعی میسازد بدون هیچ خروجی.";
Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated
Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "بازگشت";
Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "تابعی با یک خروجی میسازد.";
Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "اخطار: این تابعی پارامتر تکراری دارد.";
Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "برجستهسازی تعریف تابع";
Blockly.Msg.PROCEDURES_IFRETURN_HELPURL = "http://c2.com/cgi/wiki?GuardClause"; // untranslated
Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "اگر یک مقدار صحیح است، مقدار دوم را برگردان.";
Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "اخطار: این بلوک احتمالاً فقط داخل یک تابع استفاده میشود.";
Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "نام ورودی:";
Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP = "اضافه کردن ورودی به تابع.";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "ورودیها";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP = "افزودن، حذف یا دوباره مرتبکردن ورودی این تابع.";
Blockly.Msg.PROCEDURE_ALREADY_EXISTS = "A procedure named '%1' already exists."; // untranslated
Blockly.Msg.REDO = "Redo"; // untranslated
Blockly.Msg.REMOVE_COMMENT = "حذف نظر";
Blockly.Msg.RENAME_VARIABLE = "تغییر نام متغیر...";
Blockly.Msg.RENAME_VARIABLE_TITLE = "تغییر نام همهٔ متغیرهای «%1» به:";
Blockly.Msg.TEXT_APPEND_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg.TEXT_APPEND_TITLE = "to %1 append text %2"; // untranslated
Blockly.Msg.TEXT_APPEND_TOOLTIP = "الحاق متنی به متغیر «%1».";
Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; // untranslated
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "به حروف کوچک";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "به حروف بزرگ عنوان";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "به حروف بزرگ";
Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "بازگرداندن کپی متن در حالتی متفاوت.";
Blockly.Msg.TEXT_CHARAT_FIRST = "گرفتن اولین حرف";
Blockly.Msg.TEXT_CHARAT_FROM_END = "گرفتن حرف # از آخر";
Blockly.Msg.TEXT_CHARAT_FROM_START = "گرفتن حرف #";
Blockly.Msg.TEXT_CHARAT_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-text"; // untranslated
Blockly.Msg.TEXT_CHARAT_LAST = "گرفتن آخرین حرف";
Blockly.Msg.TEXT_CHARAT_RANDOM = "گرفتن حرف تصادفی";
Blockly.Msg.TEXT_CHARAT_TAIL = ""; // untranslated
Blockly.Msg.TEXT_CHARAT_TITLE = "in text %1 %2"; // untranslated
Blockly.Msg.TEXT_CHARAT_TOOLTIP = "حرفی در موقعیت مشخصشده بر میگرداند.";
Blockly.Msg.TEXT_COUNT_HELPURL = "https://github.com/google/blockly/wiki/Text#counting-substrings"; // untranslated
Blockly.Msg.TEXT_COUNT_MESSAGE0 = "count %1 in %2"; // untranslated
Blockly.Msg.TEXT_COUNT_TOOLTIP = "Count how many times some text occurs within some other text."; // untranslated
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "افزودن یک مورد به متن.";
Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "عضویت";
Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "اضافه، حذف یا ترتیبسازی قسمتها برای تنظیم مجدد این بلوک اگر مسدود است.";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "به حرف # از انتها";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "به حرف #";
Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "گرفتن آخرین حرف";
Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text"; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = "در متن";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "گرفتن زیرمتن از اولین حرف";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "گرفتن زیرمتن از حرف # به انتها";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "گرفتن زیرمتن از حرف #";
Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ""; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "قسمت مشخصیشدهای از متن را بر میگرداند.";
Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://github.com/google/blockly/wiki/Text#finding-text"; // untranslated
Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "اولین رخداد متن را بیاب";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "آخرین رخداد متن را بیاب";
Blockly.Msg.TEXT_INDEXOF_TITLE = "in text %1 %2 %3"; // untranslated
Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "شاخصی از اولین آخرین رخداد متن اول در متن دوم بر میگرداند. اگر متن یافت نشد %1 باز میگرداند.";
Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; // untranslated
Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 خالی است";
Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "اضافهکردن صحیح اگر متن فراهمشده خالی است.";
Blockly.Msg.TEXT_JOIN_HELPURL = "https://github.com/google/blockly/wiki/Text#text-creation"; // untranslated
Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "ایجاد متن با";
Blockly.Msg.TEXT_JOIN_TOOLTIP = "یک تکهای از متن را با چسپاندن همهٔ تعداد از موارد ایجاد میکند.";
Blockly.Msg.TEXT_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg.TEXT_LENGTH_TITLE = "طول %1";
Blockly.Msg.TEXT_LENGTH_TOOLTIP = "بازگرداندن عددی از حروف (شامل فاصلهها) در متن فراهمشده.";
Blockly.Msg.TEXT_PRINT_HELPURL = "https://github.com/google/blockly/wiki/Text#printing-text"; // untranslated
Blockly.Msg.TEXT_PRINT_TITLE = "چاپ %1";
Blockly.Msg.TEXT_PRINT_TOOLTIP = "چاپ متن، عدد یا هر مقدار دیگر مشخصشده.";
Blockly.Msg.TEXT_PROMPT_HELPURL = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; // untranslated
Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "اعلان برای کاربر با یک عدد.";
Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "اعلان برای کاربر برای یک متن.";
Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "اعلان برای عدد با پیام";
Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "اعلان برای متن با پیام";
Blockly.Msg.TEXT_REPLACE_HELPURL = "https://github.com/google/blockly/wiki/Text#replacing-substrings"; // untranslated
Blockly.Msg.TEXT_REPLACE_MESSAGE0 = "replace %1 with %2 in %3"; // untranslated
Blockly.Msg.TEXT_REPLACE_TOOLTIP = "Replace all occurances of some text within some other text."; // untranslated
Blockly.Msg.TEXT_REVERSE_HELPURL = "https://github.com/google/blockly/wiki/Text#reversing-text"; // untranslated
Blockly.Msg.TEXT_REVERSE_MESSAGE0 = "reverse %1"; // untranslated
Blockly.Msg.TEXT_REVERSE_TOOLTIP = "Reverses the order of the characters in the text."; // untranslated
Blockly.Msg.TEXT_TEXT_HELPURL = "https://fa.wikipedia.org/wiki/%D8%B1%D8%B4%D8%AA%D9%87_%28%D8%B9%D9%84%D9%88%D9%85_%D8%B1%D8%A7%DB%8C%D8%A7%D9%86%D9%87%29";
Blockly.Msg.TEXT_TEXT_TOOLTIP = "یک حرف، کلمه یا خطی از متن.";
Blockly.Msg.TEXT_TRIM_HELPURL = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; // untranslated
Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "تراشیدن فاصلهها از هر دو طرف";
Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "تراشیدن فاصلهها از طرف چپ";
Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "تراشیدن فاصلهها از طرف چپ";
Blockly.Msg.TEXT_TRIM_TOOLTIP = "کپی از متن با فاصلههای حذفشده از یک یا هر دو پایان باز میگرداند.";
Blockly.Msg.TODAY = "Today"; // untranslated
Blockly.Msg.UNDO = "Undo"; // untranslated
Blockly.Msg.VARIABLES_DEFAULT_NAME = "مورد";
Blockly.Msg.VARIABLES_GET_CREATE_SET = "درستکردن «تنظیم %1»";
Blockly.Msg.VARIABLES_GET_HELPURL = "https://github.com/google/blockly/wiki/Variables#get"; // untranslated
Blockly.Msg.VARIABLES_GET_TOOLTIP = "مقدار این متغیر را بر میگرداند.";
Blockly.Msg.VARIABLES_SET = "مجموعه %1 به %2";
Blockly.Msg.VARIABLES_SET_CREATE_GET = "درستکردن «تنظیم %1»";
Blockly.Msg.VARIABLES_SET_HELPURL = "https://github.com/google/blockly/wiki/Variables#set"; // untranslated
Blockly.Msg.VARIABLES_SET_TOOLTIP = "متغیر برابر با خروجی را مشخص میکند.";
Blockly.Msg.VARIABLE_ALREADY_EXISTS = "A variable named '%1' already exists."; // untranslated
Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE;
Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF;
Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE;
Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE;
Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO;
Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF;
Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL;
Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT = Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT;
Blockly.Msg.MATH_HUE = "230";
Blockly.Msg.LOOPS_HUE = "120";
Blockly.Msg.LISTS_HUE = "260";
Blockly.Msg.LOGIC_HUE = "210";
Blockly.Msg.VARIABLES_HUE = "330";
Blockly.Msg.TEXTS_HUE = "160";
Blockly.Msg.PROCEDURES_HUE = "290";
Blockly.Msg.COLOUR_HUE = "20"; | gpl-3.0 |
joansmith/graylog2-server | graylog2-server/src/main/java/org/graylog2/cluster/NodeService.java | 1481 | /**
* This file is part of Graylog.
*
* Graylog is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Graylog is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Graylog. If not, see <http://www.gnu.org/licenses/>.
*/
package org.graylog2.cluster;
import org.graylog2.plugin.database.PersistedService;
import org.graylog2.plugin.system.NodeId;
import java.net.URI;
import java.util.Map;
public interface NodeService extends PersistedService {
String registerServer(String nodeId, boolean isMaster, URI restTransportUri, String hostname);
Node byNodeId(String nodeId) throws NodeNotFoundException;
Node byNodeId(NodeId nodeId) throws NodeNotFoundException;
Map<String, Node> allActive(Node.Type type);
Map<String, Node> allActive();
void dropOutdated();
void markAsAlive(Node node, boolean isMaster, String restTransportAddress);
void markAsAlive(Node node, boolean isMaster, URI restTransportAddress);
boolean isOnlyMaster(NodeId nodeIde);
boolean isAnyMasterPresent();
}
| gpl-3.0 |
Morerice/piwik | core/Updater/Migration/Db/BoundSql.php | 1126 | <?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Updater\Migration\Db;
use Piwik\Db;
/**
* @see Factory::boundSql()
* @ignore
*/
class BoundSql extends Sql
{
/**
* @var array
*/
private $bind;
/**
* BoundSql constructor.
* @param string $sql
* @param array $bind
* @param int|int[] $errorCodesToIgnore
*/
public function __construct($sql, $bind, $errorCodesToIgnore)
{
parent::__construct($sql, $errorCodesToIgnore);
$this->bind = (array) $bind;
}
public function __toString()
{
$sql = parent::__toString();
foreach ($this->bind as $value) {
if (!is_int($value) && !is_float($value)) {
$value = "'" . addcslashes($value, "\000\n\r\\'\"\032") . "'";
}
$sql = substr_replace($sql, $value, $pos = strpos($sql, '?'), $len = 1);
}
return $sql;
}
public function exec()
{
Db::query($this->sql, $this->bind);
}
}
| gpl-3.0 |
18098924759/ecommon | src/Extensions/ECommon.Autofac/Properties/AssemblyInfo.cs | 1314 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("ECommon.Autofac")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ECommon.Autofac")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("ce549f5b-0236-452b-8704-ad5287ac4281")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.2")]
[assembly: AssemblyFileVersion("1.4.2")]
| gpl-3.0 |
lahwaacz/qutebrowser | tests/unit/misc/test_autoupdate.py | 2905 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2017 Alexander Cogneau (acogneau) <alexander.cogneau@gmail.com>:
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""Tests for qutebrowser.misc.autoupdate."""
import pytest
from PyQt5.QtCore import QUrl
from qutebrowser.misc import autoupdate, httpclient
INVALID_JSON = ['{"invalid": { "json"}', '{"wrong": "keys"}']
class HTTPGetStub(httpclient.HTTPClient):
"""A stub class for HTTPClient.
Attributes:
url: the last url used by get()
_success: Whether get() will emit a success signal.
"""
def __init__(self, success=True, json=None):
super().__init__()
self.url = None
self._success = success
if json:
self._json = json
else:
self._json = '{"info": {"version": "test"}}'
def get(self, url):
self.url = url
if self._success:
self.success.emit(self._json)
else:
self.error.emit("error")
def test_constructor(qapp):
client = autoupdate.PyPIVersionClient()
assert isinstance(client._client, httpclient.HTTPClient)
def test_get_version_success(qtbot):
"""Test get_version() when success is emitted."""
http_stub = HTTPGetStub(success=True)
client = autoupdate.PyPIVersionClient(client=http_stub)
with qtbot.assertNotEmitted(client.error):
with qtbot.waitSignal(client.success):
client.get_version('test')
assert http_stub.url == QUrl('https://pypi.python.org/pypi/test/json')
def test_get_version_error(qtbot):
"""Test get_version() when error is emitted."""
http_stub = HTTPGetStub(success=False)
client = autoupdate.PyPIVersionClient(client=http_stub)
with qtbot.assertNotEmitted(client.success):
with qtbot.waitSignal(client.error):
client.get_version('test')
@pytest.mark.parametrize('json', INVALID_JSON)
def test_invalid_json(qtbot, json):
"""Test on_client_success() with invalid JSON."""
http_stub = HTTPGetStub(json=json)
client = autoupdate.PyPIVersionClient(client=http_stub)
client.get_version('test')
with qtbot.assertNotEmitted(client.success):
with qtbot.waitSignal(client.error):
client.get_version('test')
| gpl-3.0 |
luisvt/xuggle-xuggler | test/src/com/xuggle/xuggler/ContainerFormatTest.java | 9769 | /*******************************************************************************
* Copyright (c) 2008, 2010 Xuggle Inc. All rights reserved.
*
* This file is part of Xuggle-Xuggler-Main.
*
* Xuggle-Xuggler-Main is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Xuggle-Xuggler-Main is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Xuggle-Xuggler-Main. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
package com.xuggle.xuggler;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.*;
import com.xuggle.ferry.JNIMemoryManager;
import com.xuggle.xuggler.IContainerFormat;
import com.xuggle.xuggler.ICodec.ID;
import junit.framework.TestCase;
public class ContainerFormatTest extends TestCase
{
private final String sampleFile = "fixtures/testfile.flv";
@Test
public void testSetOutputFmt()
{
IContainerFormat fmt = IContainerFormat.make();
fmt.setOutputFormat("flv", null, null);
fmt.setOutputFormat("flv", sampleFile, null);
fmt.setOutputFormat("flv", "file:"+sampleFile, null);
fmt.setOutputFormat("NotAShortName", null, null);
fmt.setOutputFormat("NotAShortName", "NotAURL", null);
fmt.setOutputFormat("NotAShortName", "file:"+"NotAURL", null);
fmt.setOutputFormat("NotAShortName", "NotAProtocol:"+"NotAURL", null);
assertTrue("got to end of test without coredump. woo hoo", true);
}
@Test
public void testSetInputFmt()
{
IContainerFormat fmt = IContainerFormat.make();
fmt.setInputFormat("flv");
fmt.setInputFormat("mov");
fmt.setInputFormat("NotAShortName");
assertTrue("got to end of test without coredump. woo hoo", true);
}
@Test
public void testGetInputFlag()
{
IContainerFormat fmt = IContainerFormat.make();
int retval = -1;
int flags = fmt.getInputFlags();
assertEquals("should be not set", flags, 0);
retval = fmt.setInputFormat("s16be");
assertTrue("should succeed", retval >= 0);
boolean hasGenericIndex = fmt.getInputFlag(IContainerFormat.Flags.FLAG_GENERIC_INDEX);
assertTrue("should have global header", hasGenericIndex);
}
@Test
public void testGetOutputFlag()
{
IContainerFormat fmt = IContainerFormat.make();
int retval = -1;
int flags = fmt.getOutputFlags();
assertEquals("should be not set", flags, 0);
retval = fmt.setOutputFormat("mov", null, null);
assertTrue("should succeed", retval >= 0);
boolean hasGlobalHeader = fmt.getOutputFlag(IContainerFormat.Flags.FLAG_GLOBALHEADER);
assertTrue("should have global header", hasGlobalHeader);
}
@Test
public void testSetInputFlag()
{
IContainerFormat fmt = IContainerFormat.make();
int retval = -1;
int flags = fmt.getInputFlags();
assertEquals("should be not set", flags, 0);
retval = fmt.setInputFormat("s16be");
assertTrue("should succeed", retval >= 0);
boolean hasGlobalHeader = fmt.getInputFlag(IContainerFormat.Flags.FLAG_GLOBALHEADER);
assertTrue("should not have global header", !hasGlobalHeader);
fmt.setInputFlag(IContainerFormat.Flags.FLAG_GLOBALHEADER, true);
hasGlobalHeader = fmt.getInputFlag(IContainerFormat.Flags.FLAG_GLOBALHEADER);
assertTrue("should have global header", hasGlobalHeader);
fmt.setInputFlag(IContainerFormat.Flags.FLAG_GLOBALHEADER, false);
hasGlobalHeader = fmt.getInputFlag(IContainerFormat.Flags.FLAG_GLOBALHEADER);
assertTrue("should not have global header", !hasGlobalHeader);
}
@Test
public void testSetOutputFlag()
{
IContainerFormat fmt = IContainerFormat.make();
int retval = -1;
int flags = fmt.getOutputFlags();
assertEquals("should be not set", flags, 0);
retval = fmt.setOutputFormat("mov", null, null);
assertTrue("should succeed", retval >= 0);
boolean hasGlobalHeader = fmt.getOutputFlag(IContainerFormat.Flags.FLAG_GLOBALHEADER);
assertTrue("should have global header", hasGlobalHeader);
fmt.setOutputFlag(IContainerFormat.Flags.FLAG_GLOBALHEADER, false);
hasGlobalHeader = fmt.getOutputFlag(IContainerFormat.Flags.FLAG_GLOBALHEADER);
assertTrue("should not have global header", !hasGlobalHeader);
fmt.setOutputFlag(IContainerFormat.Flags.FLAG_GLOBALHEADER, true);
hasGlobalHeader = fmt.getOutputFlag(IContainerFormat.Flags.FLAG_GLOBALHEADER);
assertTrue("should have global header", hasGlobalHeader);
}
@Test
public void testGetOutputCodecsSupported()
{
IContainerFormat fmt = IContainerFormat.make();
int retval = -1;
int flags = fmt.getOutputFlags();
assertEquals("should be not set", flags, 0);
retval = fmt.setOutputFormat("mov", null, null);
assertTrue("should succeed", retval >= 0);
List<ICodec.ID> codecs = fmt.getOutputCodecsSupported();
assertNotNull(codecs);
// for(ICodec.ID id : codecs)
// System.out.println("Codec: "+id);
assertTrue("should get at least one codec", codecs.size() > 1);
assertTrue("should have MP3",
codecs.contains(ICodec.ID.CODEC_ID_MP3));
assertTrue("Should contain H263",
codecs.contains(ICodec.ID.CODEC_ID_H263));
}
@Test
public void testGetInputFormats()
{
Collection<IContainerFormat> installed =
IContainerFormat.getInstalledInputFormats();
assertTrue(installed.size() > 0);
for(IContainerFormat fmt : installed)
{
assertNotNull(fmt);
assertTrue(fmt.isInput());
assertTrue(fmt.getInputFormatShortName().length() > 0);
}
}
@Test
public void testGetOutputFormats()
{
Collection<IContainerFormat> installed =
IContainerFormat.getInstalledOutputFormats();
assertTrue(installed.size() > 0);
for(IContainerFormat fmt : installed)
{
assertNotNull(fmt);
assertTrue(fmt.isOutput());
assertTrue(fmt.getOutputFormatShortName().length() > 0);
}
}
@Test
public void testEstablishOutputCodecId()
{
JNIMemoryManager.getMgr().flush();
IContainerFormat fmt = IContainerFormat.make();
fmt.setOutputFormat("flv", null, null);
assertEquals(ICodec.ID.CODEC_ID_FLV1,
fmt.establishOutputCodecId(ICodec.Type.CODEC_TYPE_VIDEO));
assertEquals(ICodec.ID.CODEC_ID_MP3,
fmt.establishOutputCodecId(ICodec.Type.CODEC_TYPE_AUDIO));
fmt.setOutputFormat("mp4", null, null);
assertEquals(ICodec.ID.CODEC_ID_H264,
fmt.establishOutputCodecId(ICodec.Type.CODEC_TYPE_VIDEO));
assertEquals(ICodec.ID.CODEC_ID_AAC,
fmt.establishOutputCodecId(ICodec.Type.CODEC_TYPE_AUDIO));
fmt.setOutputFormat("3gp", null, null);
assertEquals(ICodec.ID.CODEC_ID_H263,
fmt.establishOutputCodecId(ICodec.Type.CODEC_TYPE_VIDEO));
assertEquals(ICodec.ID.CODEC_ID_AMR_NB,
fmt.establishOutputCodecId(ICodec.Type.CODEC_TYPE_AUDIO));
fmt.delete();
assertEquals(0, JNIMemoryManager.getMgr().getNumPinnedObjects());
}
@Test
public void testEstablishOutputCodecIdFailOnMismatchedArgs()
{
JNIMemoryManager.getMgr().flush();
IContainerFormat fmt = IContainerFormat.make();
fmt.setOutputFormat("flv", null, null);
try {
fmt.establishOutputCodecId(ICodec.Type.CODEC_TYPE_VIDEO,
ICodec.ID.CODEC_ID_MP3);
fail("should not get here");
} catch (IllegalArgumentException e) {}
fmt.delete();
assertEquals(0, JNIMemoryManager.getMgr().getNumPinnedObjects());
}
@Test
public void testEstablishOutputCodecIdFailOnInputFormat()
{
JNIMemoryManager.getMgr().flush();
IContainerFormat fmt = IContainerFormat.make();
fmt.setInputFormat("flv");
try {
fmt.establishOutputCodecId(ICodec.Type.CODEC_TYPE_VIDEO);
fail("should not get here");
} catch (IllegalArgumentException e) {}
fmt.delete();
assertEquals(0, JNIMemoryManager.getMgr().getNumPinnedObjects());
}
@Test
public void testIssue200()
{
IContainerFormat format = IContainerFormat.make();
format.setOutputFormat("flv", null, null);
List<ID> codecs = format.getOutputCodecsSupported();
// now let's make sure there are no dups
Set<ID> uniqueCodecs = new HashSet<ID>();
for(ID id : codecs) {
assertFalse("id not unique: "+id, uniqueCodecs.contains(id));
uniqueCodecs.add(id);
}
}
/**
* Make sure the first video codec returned for FLV is FLV1.
*/
@Test
public void testIssue201()
{
IContainerFormat format = IContainerFormat.make();
format.setOutputFormat("flv", null, null);
List<ID> codecs = format.getOutputCodecsSupported();
for(ID id : codecs) {
ICodec codec = ICodec.findEncodingCodec(id);
assertNotNull(codec);
if (codec.getType() == ICodec.Type.CODEC_TYPE_VIDEO) {
assertEquals(ICodec.ID.CODEC_ID_FLV1, id);
// and the test is now finished.
break;
}
}
}
/**
* This test is not really a test -- it's used to show all enums
* and how they map to codecs
*/
@Test
public void testShowEnumsWithoutNativeCode()
{
ICodec.ID ids[] = ICodec.ID.values();
for (ICodec.ID id : ids)
{
System.out.println("ID: " + id + "; Value: " + id.swigValue());
}
}
}
| gpl-3.0 |
Acquati/aulas-tesseract | es2015/babel/node_modules/caniuse-lite/data/features/queryselector.js | 849 | module.exports={A:{A:{"1":"E A B","2":"FB","8":"H D","132":"G"},B:{"1":"C p x J L N I"},C:{"1":"0 1 2 3 4 5 6 8 9 F K H D G E A B C p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y AB YB SB","8":"aB CB"},D:{"1":"0 1 2 3 4 5 6 8 9 F K H D G E A B C p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y AB MB cB GB a HB IB JB KB"},E:{"1":"F K H D G E A B C LB DB NB OB PB QB RB z TB"},F:{"1":"0 7 B C J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w VB WB XB z BB ZB","8":"E UB"},G:{"1":"G C DB bB EB dB eB fB gB hB iB jB kB lB mB"},H:{"1":"nB"},I:{"1":"CB F a oB pB qB rB EB sB tB"},J:{"1":"D A"},K:{"1":"7 A B C M z BB"},L:{"1":"a"},M:{"1":"y"},N:{"1":"A B"},O:{"1":"uB"},P:{"1":"F K vB wB"},Q:{"1":"xB"},R:{"1":"yB"}},B:1,C:"querySelector/querySelectorAll"};
| gpl-3.0 |
pfrenssen/pharborist | src/Types/TrueNode.php | 845 | <?php
namespace Pharborist\Types;
use Pharborist\FormatterFactory;
use Pharborist\Namespaces\NameNode;
/**
* Boolean TRUE.
*
* Represents the boolean TRUE constant, spelled `true` or `TRUE`. This does *not* represent
* other truthy values like 1 or `'hello'`.
*/
class TrueNode extends BooleanNode {
/**
* Create a new TrueNode.
*
* @param boolean $boolean
* Parameter is ignored.
*
* @return TrueNode
*/
public static function create($boolean = TRUE) {
$is_upper = FormatterFactory::getDefaultFormatter()->getConfig('boolean_null_upper');
$node = new TrueNode();
$node->addChild(NameNode::create($is_upper ? 'TRUE' : 'true'), 'constantName');
return $node;
}
/**
* Gets the boolean value of the node.
*
* @return boolean
*/
public function toValue() {
return TRUE;
}
}
| gpl-3.0 |
Morerice/piwik | plugins/Contents/Reports/GetContentPieces.php | 1091 | <?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\Contents\Reports;
use Piwik\Piwik;
use Piwik\Plugin\Report;
use Piwik\Plugins\Contents\Columns\ContentPiece;
use Piwik\Plugins\Contents\Columns\Metrics\InteractionRate;
use Piwik\View;
/**
* This class defines a new report.
*
* See {@link http://developer.piwik.org/api-reference/Piwik/Plugin/Report} for more information.
*/
class GetContentPieces extends Base
{
protected function init()
{
parent::init();
$this->name = Piwik::translate('Contents_ContentPiece');
$this->dimension = null;
// TODO $this->documentation = Piwik::translate('ContentsDocumentation');
$this->dimension = new ContentPiece();
$this->order = 36;
$this->actionToLoadSubTables = 'getContentPieces';
$this->metrics = array('nb_impressions', 'nb_interactions');
$this->processedMetrics = array(new InteractionRate());
}
}
| gpl-3.0 |
asika32764/php-sitemap | src/SitemapIndex.php | 932 | <?php
/**
* Part of zero project.
*
* @copyright Copyright (C) 2015 {ORGANIZATION}. All rights reserved.
* @license GNU General Public License version 2 or later;
*/
namespace Asika\Sitemap;
/**
* The SitemapIndex class.
*
* @since {DEPLOY_VERSION}
*/
class SitemapIndex extends AbstractSitemap
{
/**
* Property root.
*
* @var string
*/
protected $root = 'sitemapindex';
/**
* addItem
*
* @param string $loc
* @param string|\DateTime $lastmod
*
* @return static
*/
public function addItem($loc, $lastmod = null)
{
if ($this->autoEscape)
{
$loc = htmlspecialchars($loc);
}
$sitemap = $this->xml->addChild('sitemap');
$sitemap->addChild('loc', $loc);
if ($lastmod)
{
if (!($lastmod instanceof \DateTime))
{
$lastmod = new \DateTime($lastmod);
}
$sitemap->addChild('lastmod', $lastmod->format($this->dateFormat));
}
return $this;
}
}
| gpl-3.0 |
rajmahesh/magento2-master | vendor/magento/magento2-base/dev/tests/functional/tests/app/Magento/CatalogSearch/Test/Block/Advanced/CustomAttribute/Text.php | 1099 | <?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogSearch\Test\Block\Advanced\CustomAttribute;
use Magento\Mtf\Block\Form as BaseForm;
use Magento\Mtf\Fixture\FixtureInterface;
use Magento\Mtf\Client\Element\SimpleElement;
/**
* Advanced search form with custom Text attribute.
*/
class Text extends BaseForm
{
/**
* Selector for text input.
*
* @var string
*/
protected $inputSelector = '[name="%s"]';
/**
* Fill the root form.
*
* @param FixtureInterface $fixture
* @param SimpleElement|null $element
* @param array|null $mapping
* @return $this
*/
public function fill(FixtureInterface $fixture, SimpleElement $element = null, array $mapping = null)
{
$attribute = $fixture->getDataFieldConfig('custom_attribute')['source']->getAttribute();
$mapping['custom_attribute']['selector'] = sprintf($this->inputSelector, $attribute->getAttributeCode());
$this->_fill($mapping, $element);
return $this;
}
}
| gpl-3.0 |
yaseppochi/mailman | src/mailman/rest/queues.py | 3951 | # Copyright (C) 2015 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# GNU Mailman is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# GNU Mailman. If not, see <http://www.gnu.org/licenses/>.
"""<api>/queues."""
__all__ = [
'AQueue',
'AQueueFile',
'AllQueues',
]
from mailman.config import config
from mailman.app.inject import inject_text
from mailman.interfaces.listmanager import IListManager
from mailman.rest.helpers import (
CollectionMixin, bad_request, created, etag, no_content, not_found, okay,
paginate)
from mailman.rest.validator import Validator
from zope.component import getUtility
class _QueuesBase(CollectionMixin):
"""Shared base class for queues."""
def _resource_as_dict(self, name):
"""See `CollectionMixin`."""
switchboard = config.switchboards[name]
files = switchboard.files
return dict(
name=switchboard.name,
directory=switchboard.queue_directory,
count=len(files),
files=files,
self_link=self.path_to('queues/{}'.format(name)),
)
@paginate
def _get_collection(self, request):
"""See `CollectionMixin`."""
return sorted(config.switchboards)
class AQueue(_QueuesBase):
"""A single queue."""
def __init__(self, name):
self._name = name
def on_get(self, request, response):
"""Return a single queue resource."""
if self._name not in config.switchboards:
not_found(response)
else:
okay(response, self._resource_as_json(self._name))
def on_post(self, request, response):
"""Inject a message into the queue."""
try:
validator = Validator(list_id=str,
text=str)
values = validator(request)
except ValueError as error:
bad_request(response, str(error))
return
list_id = values['list_id']
mlist = getUtility(IListManager).get_by_list_id(list_id)
if mlist is None:
bad_request(response, 'No such list: {}'.format(list_id))
return
try:
filebase = inject_text(
mlist, values['text'], switchboard=self._name)
except Exception as error:
bad_request(response, str(error))
return
else:
location = self.path_to(
'queues/{}/{}'.format(self._name, filebase))
created(response, location)
class AQueueFile:
def __init__(self, name, filebase):
self._name = name
self._filebase = filebase
def on_delete(self, request, response):
"""Delete the queue file."""
switchboard = config.switchboards.get(self._name)
if switchboard is None:
not_found(response, 'No such queue: {}'.format(self._name))
return
try:
switchboard.dequeue(self._filebase)
except FileNotFoundError:
not_found(response,
'No such queue file: {}'.format(self._filebase))
else:
no_content(response)
class AllQueues(_QueuesBase):
"""All queues."""
def on_get(self, request, response):
"""<api>/queues"""
resource = self._make_collection(request)
resource['self_link'] = self.path_to('queues')
okay(response, etag(resource))
| gpl-3.0 |
Integreight/1Sheeld-Android-App | oneSheeld/src/main/java/com/integreight/onesheeld/utils/customviews/PluginPinsColumnContainer.java | 9916 | package com.integreight.onesheeld.utils.customviews;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.integreight.onesheeld.R;
import com.integreight.onesheeld.enums.ArduinoPin;
import com.integreight.onesheeld.shields.observer.OnChildFocusListener;
import com.integreight.onesheeld.utils.customviews.PluginConnectingPinsView.onGetPinsView;
import com.integreight.onesheeld.utils.customviews.PluginPinsColumnContainer.PinData.TYPE;
import java.util.ArrayList;
public class PluginPinsColumnContainer extends RelativeLayout {
public int currentIndex = -1;
public String currentTag = null;
private OnChildFocusListener focusListener;
private int extraHorizontalSpace = 0, extraVerticalSpace = 0;
private ArrayList<PinData> childrenRects = new ArrayList<PinData>();
ImageView cursor;
RelativeLayout.LayoutParams cursorParams;
private onGetPinsView onGetPinsListener;
private boolean isOnglobalCalled = false;
public PluginPinsColumnContainer(Context context, AttributeSet attrs) {
super(context, attrs);
extraHorizontalSpace = (int) (50 * context.getResources()
.getDisplayMetrics().density - .5f);
extraVerticalSpace = (int) (1 * context.getResources()
.getDisplayMetrics().density - .5f);
}
public void setup(OnChildFocusListener focusListener, ImageView cursor,
onGetPinsView onGetPinsListener, final int currentIndx) {
this.focusListener = focusListener;
this.cursor = cursor;
this.onGetPinsListener = onGetPinsListener;
this.currentIndex = -1;
currentTag = null;
isOnglobalCalled = false;
childrenRects = new ArrayList<PinData>();
getViewTreeObserver().addOnGlobalLayoutListener(
new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (!isOnglobalCalled
&& (childrenRects == null || childrenRects
.size() == 0)) {
childrenRects = new ArrayList<PluginPinsColumnContainer.PinData>();
loadRects(PluginPinsColumnContainer.this);
PluginPinsColumnContainer.this.onGetPinsListener
.onPinsDrawn();
if (currentIndx != -1) {
for (PinData iterable_element : childrenRects) {
if (ArduinoPin
.valueOf(iterable_element.tag).microHardwarePin == currentIndx) {
currentTag = iterable_element.tag;
PluginPinsColumnContainer.this.currentIndex = iterable_element.index;
setCursorTo(getDataOfTag(iterable_element.tag));
loadRects(PluginPinsColumnContainer.this);
break;
}
}
}
isOnglobalCalled = true;
}
}
});
}
int concatenatedLeft = 0, concatenatedTop = 0, concatenatedRight = 0;
private boolean isPinEnabled(String tag) {
return true;
}
private int getType(PinView v) {
int type = PinData.TYPE.NOT_CONNECTED_AND_ENABLED;
if (v.getTag() != null) {
String tag = v.getTag().toString().startsWith("_") ? v.getTag()
.toString().substring(1) : v.getTag().toString();
if (isPinEnabled(tag) == false)
return PinData.TYPE.DISABLED;
} else
type = TYPE.DUMMY;
return type;
}
private void loadRects(ViewGroup vg) {
concatenatedLeft = getChildAt(1).getLeft();
concatenatedTop = getChildAt(1).getTop();
concatenatedRight = getChildAt(1).getRight();
cursorParams = (LayoutParams) cursor.getLayoutParams();
for (int i = 0; i < vg.getChildCount(); i++) {
if (vg.getChildAt(i) instanceof PinView) {
PinView v = (PinView) vg.getChildAt(i);
int type = getType(v);
if (type != TYPE.DUMMY) {
if (v.getTag().toString().equals(currentTag))
v.setBackgroundResource(PinData.TYPE.CONNECTED_HERE);
else
v.setBackgroundResource(type);
childrenRects.add(new PinData(((String) v.getTag()),
new Rect(
concatenatedLeft
+ vg.getLeft()
- (extraHorizontalSpace * (!v
.getTag().toString()
.startsWith("_") ? 2 : 1))
+ v.getLeft(), concatenatedTop
+ vg.getTop() + v.getTop()
- extraVerticalSpace,
concatenatedTop
+ vg.getLeft()
+ v.getRight()
+ (extraHorizontalSpace * (v
.getTag().toString()
.startsWith("_") ? 2 : 2)),
concatenatedTop + vg.getTop()
+ v.getBottom()
+ extraVerticalSpace), i, type));
}
} else if (vg.getChildAt(i) instanceof ViewGroup) {
loadRects((ViewGroup) vg.getChildAt(i));
}
}
}
private synchronized PinData getTouhedIndex(MotionEvent event) {
for (PinData item : childrenRects) {
if (item.rect.contains((int) event.getX(), (int) event.getY())
&& item.type != PinData.TYPE.DISABLED)
return item;
}
return new PinData("", null, -1, PinData.TYPE.NOT_CONNECTED_AND_ENABLED);
}
public void setCursorTo(PinData item) {
cursor.setVisibility(View.VISIBLE);
cursorParams.topMargin = item.rect.top - (cursorParams.height / 2)
- (5 * extraVerticalSpace);
cursorParams.leftMargin = (item.tag.startsWith("_") ? (concatenatedLeft - extraHorizontalSpace / 2)
: (concatenatedRight + extraHorizontalSpace / 4));
cursor.setBackgroundResource(item.tag.startsWith("_") ? R.drawable.arduino_pins_view_left_selector
: R.drawable.arduino_pins_view_right_selector);
cursor.requestLayout();
}
public PinData getDataOfTag(String tag) {
for (PinData item : childrenRects) {
if (tag.equals(item.tag)) {
return item;
}
}
return new PinData("", null, -1, PinData.TYPE.NOT_CONNECTED_AND_ENABLED);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN
|| event.getAction() == MotionEvent.ACTION_MOVE) {
PinData item = getTouhedIndex(event);
if (item.index != currentIndex) {
currentIndex = item.index;
currentTag = item.tag;
focusListener.focusOnThisChild(currentIndex,
currentIndex == -1 ? "" : currentTag);
if (item.index != -1) {
setCursorTo(item);
} else
cursor.setVisibility(View.INVISIBLE);
return true;
}
} else if (event.getAction() == MotionEvent.ACTION_UP) {
PinData item = getTouhedIndex(event);
currentIndex = item.index;
currentTag = item.tag;
if (item.index != -1) {
setCursorTo(item);
} else
cursor.setVisibility(View.INVISIBLE);
focusListener.selectThisChild(currentIndex, currentIndex == -1 ? ""
: currentTag);
childrenRects = new ArrayList<PluginPinsColumnContainer.PinData>();
loadRects(this);
return true;
}
return true;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
return true;
}
public static class PinData {
public String tag;
public Rect rect;
public int index;
public int type;
public PinData() {
// TODO Auto-generated constructor stub
}
public PinData(String tag, Rect rect, int index, int type) {
super();
this.tag = tag;
this.rect = rect;
this.index = index;
this.type = type;
}
public static final class TYPE {
public final static int CONNECTED_HERE = R.drawable.arduino_green_temp_pin;
public final static int CONNECTED_OUT = R.drawable.arduino_orange_pin;
public final static int NOT_CONNECTED_AND_ENABLED = R.drawable.arduino_default_pin;
public final static int DISABLED = R.drawable.arduino_red_pin;
public final static int DUMMY = R.drawable.arduino_dummy_pin;
}
}
}
| gpl-3.0 |
chb/indivo_server | indivo/middlewares/paramloader.py | 1881 | """
Middleware (filters) for Indivo
Pre-processes paramaters that are passed to Indivo views,
replacing id strings with their corresponding Django models,
including records, accounts, carenets, etc...
This is helpful to view functions, accesscontrol, and auditing.
"""
from django.http import Http404
from indivo import models
ID = 'id'
EMAIL = 'email'
TOKEN = 'token'
SEPARATOR = '_'
# Contract: new param will be named the same as the
# old param, up to the first instance of SEPARATOR.
# CHANGE URLS so param name matches primary key in DB
LOAD_PARAMS = {
'account_email' : ( models.Account, EMAIL ),
'account_id' : ( models.Account, EMAIL ),
'carenet_id' : ( models.Carenet, ID ),
'pha_email' : ( models.PHA, EMAIL ),
'record_id' : ( models.Record, ID ),
'reqtoken_id' : ( models.ReqToken, TOKEN ),
}
class ParamLoader(object):
def process_view(self, request, view_func, view_args, view_kwargs):
""" substitute id-strings with models in view_kwargs:
account_email becomes account, record_id becomes record, etc."""
# Destructively modify view_kwargs for internal layers
for param in LOAD_PARAMS.keys():
if view_kwargs.has_key(param):
model_obj = self.get_object_from_param(param, view_kwargs[param])
#delete the old arg, and add the new one
new_param = param[:param.find(SEPARATOR)]
del view_kwargs[param]
view_kwargs[new_param] = model_obj
return None
def get_object_from_param(self, param, param_val):
return object_lookup_by_id(param_val, *LOAD_PARAMS[param])
def object_lookup_by_id(object_id, django_model, id_field):
if object_id is None:
return None
query_kwargs = {id_field : object_id}
try:
return django_model.objects.get(**query_kwargs)
except django_model.DoesNotExist:
raise Http404
| gpl-3.0 |
netbrain/ntorrent | plugins/ntorrent/source/ntorrent/plugins/model/PluginList.java | 964 | package ntorrent.plugins.model;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashSet;
import ntorrent.tools.Serializer;
import org.java.plugin.PluginManager;
import org.java.plugin.registry.PluginDescriptor;
public class PluginList implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private final HashSet<String> enabledPlugins = new HashSet<String>();
private final HashSet<String> disabledPlugins = new HashSet<String>();
public void saveState(PluginManager manager) throws IOException {
for(PluginDescriptor pd : manager.getRegistry().getPluginDescriptors()){
if(manager.isPluginActivated(pd)){
enabledPlugins.add(pd.getId());
}else{
disabledPlugins.add(pd.getId());
}
}
Serializer.serialize(this);
}
public HashSet<String> getDisabledPlugins() {
return disabledPlugins;
}
public HashSet<String> getEnabledPlugins() {
return enabledPlugins;
}
}
| gpl-3.0 |
matthewzhenggong/ardupilot | ArduPlane/commands.cpp | 4396 | // -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
/*
* logic for dealing with the current command in the mission and home location
*/
#include "Plane.h"
/*
* set_next_WP - sets the target location the vehicle should fly to
*/
void Plane::set_next_WP(const struct Location &loc)
{
if (auto_state.next_wp_no_crosstrack) {
// we should not try to cross-track for this waypoint
prev_WP_loc = current_loc;
// use cross-track for the next waypoint
auto_state.next_wp_no_crosstrack = false;
auto_state.no_crosstrack = true;
} else {
// copy the current WP into the OldWP slot
prev_WP_loc = next_WP_loc;
auto_state.no_crosstrack = false;
}
// Load the next_WP slot
// ---------------------
next_WP_loc = loc;
// if lat and lon is zero, then use current lat/lon
// this allows a mission to contain a "loiter on the spot"
// command
if (next_WP_loc.lat == 0 && next_WP_loc.lng == 0) {
next_WP_loc.lat = current_loc.lat;
next_WP_loc.lng = current_loc.lng;
// additionally treat zero altitude as current altitude
if (next_WP_loc.alt == 0) {
next_WP_loc.alt = current_loc.alt;
next_WP_loc.flags.relative_alt = false;
next_WP_loc.flags.terrain_alt = false;
}
}
// convert relative alt to absolute alt
if (next_WP_loc.flags.relative_alt) {
next_WP_loc.flags.relative_alt = false;
next_WP_loc.alt += home.alt;
}
// are we already past the waypoint? This happens when we jump
// waypoints, and it can cause us to skip a waypoint. If we are
// past the waypoint when we start on a leg, then use the current
// location as the previous waypoint, to prevent immediately
// considering the waypoint complete
if (location_passed_point(current_loc, prev_WP_loc, next_WP_loc)) {
gcs_send_text(MAV_SEVERITY_NOTICE, "Resetting previous waypoint");
prev_WP_loc = current_loc;
}
// used to control FBW and limit the rate of climb
// -----------------------------------------------
set_target_altitude_location(next_WP_loc);
// zero out our loiter vals to watch for missed waypoints
loiter_angle_reset();
setup_glide_slope();
setup_turn_angle();
loiter_angle_reset();
}
void Plane::set_guided_WP(void)
{
if (g.loiter_radius < 0 || guided_WP_loc.flags.loiter_ccw) {
loiter.direction = -1;
} else {
loiter.direction = 1;
}
// copy the current location into the OldWP slot
// ---------------------------------------
prev_WP_loc = current_loc;
// Load the next_WP slot
// ---------------------
next_WP_loc = guided_WP_loc;
// used to control FBW and limit the rate of climb
// -----------------------------------------------
set_target_altitude_current();
update_flight_stage();
setup_glide_slope();
setup_turn_angle();
// reset loiter start time.
loiter.start_time_ms = 0;
// start in non-VTOL mode
auto_state.vtol_loiter = false;
loiter_angle_reset();
}
// run this at setup on the ground
// -------------------------------
void Plane::init_home()
{
gcs_send_text(MAV_SEVERITY_INFO, "Init HOME");
ahrs.set_home(gps.location());
home_is_set = HOME_SET_NOT_LOCKED;
Log_Write_Home_And_Origin();
GCS_MAVLINK::send_home_all(gps.location());
gcs_send_text_fmt(MAV_SEVERITY_INFO, "GPS alt: %lu", (unsigned long)home.alt);
// Save Home to EEPROM
mission.write_home_to_storage();
// Save prev loc
// -------------
next_WP_loc = prev_WP_loc = home;
}
/*
update home location from GPS
this is called as long as we have 3D lock and the arming switch is
not pushed
*/
void Plane::update_home()
{
if (home_is_set == HOME_SET_NOT_LOCKED) {
Location loc = gps.location();
Location origin;
// if an EKF origin is available then we leave home equal to
// the height of that origin. This ensures that our relative
// height calculations are using the same origin
if (ahrs.get_origin(origin)) {
loc.alt = origin.alt;
}
ahrs.set_home(loc);
Log_Write_Home_And_Origin();
GCS_MAVLINK::send_home_all(gps.location());
}
barometer.update_calibration();
}
| gpl-3.0 |
chriskmanx/qmole | QMOLEDEV/boost_1_49_0/libs/interprocess/test/cached_adaptive_pool_test.cpp | 2414 | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2004-2011. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/list.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/cached_adaptive_pool.hpp>
#include "print_container.hpp"
#include "dummy_test_allocator.hpp"
#include "movable_int.hpp"
#include "list_test.hpp"
#include "vector_test.hpp"
using namespace boost::interprocess;
//We will work with wide characters for shared memory objects
//Alias an cached adaptive pool that allocates ints
typedef cached_adaptive_pool
<int, managed_shared_memory::segment_manager>
cached_node_allocator_t;
typedef ipcdetail::cached_adaptive_pool_v1
<int, managed_shared_memory::segment_manager>
cached_node_allocator_v1_t;
namespace boost {
namespace interprocess {
//Explicit instantiations to catch compilation errors
template class cached_adaptive_pool<int, managed_shared_memory::segment_manager>;
template class cached_adaptive_pool<void, managed_shared_memory::segment_manager>;
namespace ipcdetail {
template class ipcdetail::cached_adaptive_pool_v1<int, managed_shared_memory::segment_manager>;
template class ipcdetail::cached_adaptive_pool_v1<void, managed_shared_memory::segment_manager>;
}}}
//Alias list types
typedef list<int, cached_node_allocator_t> MyShmList;
typedef list<int, cached_node_allocator_v1_t> MyShmListV1;
//Alias vector types
typedef vector<int, cached_node_allocator_t> MyShmVector;
typedef vector<int, cached_node_allocator_v1_t> MyShmVectorV1;
int main ()
{
if(test::list_test<managed_shared_memory, MyShmList, true>())
return 1;
if(test::list_test<managed_shared_memory, MyShmListV1, true>())
return 1;
if(test::vector_test<managed_shared_memory, MyShmVector>())
return 1;
if(test::vector_test<managed_shared_memory, MyShmVectorV1>())
return 1;
return 0;
}
#include <boost/interprocess/detail/config_end.hpp>
| gpl-3.0 |
jhcepas/ete | ete3/test/test_treeview/barchart_and_piechart_faces.py | 1370 | import sys
import random
from ... import Tree, faces, TreeStyle, COLOR_SCHEMES
schema_names = COLOR_SCHEMES.keys()
def layout(node):
if node.is_leaf():
F= faces.PieChartFace([10,10,10,10,10,10,10,10,10,4,6],
colors=COLOR_SCHEMES["set3"],
width=50, height=50)
F.border.width = None
F.opacity = 0.8
faces.add_face_to_node(F,node, 0, position="branch-right")
F= faces.PieChartFace([10,20,5,5,60],
colors=COLOR_SCHEMES[random.sample(schema_names, 1)[0]],
width=100, height=40)
F.border.width = None
F.opacity = 0.8
faces.add_face_to_node(F,node, 0, position="branch-right")
else:
F= faces.BarChartFace([40,20,70,100,30,40,50,40,70,-12], min_value=-12,
colors=COLOR_SCHEMES["spectral"],
labels = "aaa,bbb,cccccc,dd,eeee,ffff,gg,HHH,II,JJJ,KK".split(","))
faces.add_face_to_node(F,node, 0, position="branch-top")
F.background.color = "#eee"
def get_example_tree():
t = Tree()
ts = TreeStyle()
ts.layout_fn = layout
ts.mode = "r"
ts.show_leaf_name = False
t.populate(10)
return t, ts
if __name__ == '__main__':
t, ts = get_example_tree()
t.show(tree_style=ts)
| gpl-3.0 |
qubist/Ultimate-Altimeter | Libraries/Bounce2/docs/files/search/functions_0.js | 229 | var searchData=
[
['attach',['attach',['../class_bounce.html#aba08e592941465d033e3eba3dde66eaf',1,'Bounce::attach(int pin, int mode)'],['../class_bounce.html#a163477dbcbaf1a3dee6cb3b62eedf09e',1,'Bounce::attach(int pin)']]]
];
| gpl-3.0 |
jmcPereira/overture | core/ast/src/main/java/org/overture/ast/intf/lex/ILexNameToken.java | 2046 | /*
* #%~
* The Overture Abstract Syntax Tree
* %%
* Copyright (C) 2008 - 2014 Overture
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #~%
*/
package org.overture.ast.intf.lex;
import java.util.List;
import org.overture.ast.types.PType;
public interface ILexNameToken extends ILexIdentifierToken
{
String getFullName();
int compareTo(ILexNameToken o);
ILexNameToken copy();
ILexNameToken getClassName();
boolean getExplicit();
ILexNameToken clone();
ILexNameToken getExplicit(boolean ex);
ILexIdentifierToken getIdentifier();
ILexNameToken getInitName(ILexLocation l);
ILexNameToken getInvName(ILexLocation l);
ILexLocation getLocation();
ILexNameToken getModifiedName(String classname);
String getModule();
String getName();
ILexNameToken getNewName();
boolean getOld();
ILexNameToken getOldName();
ILexNameToken getPerName(ILexLocation loc);
ILexNameToken getPostName(ILexLocation l);
ILexNameToken getPreName(ILexLocation l);
ILexNameToken getSelfName();
String getSimpleName();
ILexNameToken getThreadName();
ILexNameToken getThreadName(ILexLocation loc);
List<PType> getTypeQualifier();
List<PType> typeQualifier();
boolean isOld();
boolean matches(ILexNameToken other);
void setTypeQualifier(List<PType> types);
// int hashCode(IAstAssistantFactory assistantFactory);
// Try to declare it here as requested by eclipse.
// Didn't seem to work.
}
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/scroll_of_absorb-dex.lua | 481 | -----------------------------------------
-- ID: 4875
-- Scroll of Absorb-DEX
-- Teaches the black magic Absorb-DEX
-----------------------------------------
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
return target:canLearnSpell(267);
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addSpell(267);
end; | gpl-3.0 |
b3lst/Zeus-Android-Client | app/src/main/java/com/prey/activities/AgreementDialogActivity.java | 5443 | /*******************************************************************************
* Created by Carlos Yaconi
* Copyright 2012 Fork Ltd. All rights reserved.
* License: GPLv3
* Full license at "/LICENSE"
******************************************************************************/
package com.prey.activities;
import com.prey.R;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AgreementDialogActivity extends PreyActivity {
protected static final int INSTRUCTIONS_SENT = 0;
int wrongPasswordIntents = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agreement);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
TextView linkToTOS = (TextView) findViewById(R.id.linkToTosText);
linkToTOS.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String url = "http://" + getPreyConfig().getPreyDomain() + "/terms";
Intent internetIntent = new Intent(Intent.ACTION_VIEW);
internetIntent.setData(Uri.parse(url));
startActivity(internetIntent);
}
});
Button checkPasswordOkButton = (Button) findViewById(R.id.agree_tos_button);
checkPasswordOkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK);
finish();
}
});
Button checkPasswordCancelButton = (Button) findViewById(R.id.dont_agree_tos_button);
checkPasswordCancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setResult(RESULT_CANCELED);
finish();
}
});
}
}
/*
* @Override protected Dialog onCreateDialog(int id) {
*
* Dialog pass = null; switch (id) {
*
* case INSTRUCTIONS_SENT: setResult(RESULT_FIRST_USER); String email =
* PreyConfig.getPreyConfig(getApplicationContext()).getEmail(); String message
* = getString(R.string.password_dialog_forgot_sent_label, email); //
* label.setTextAppearance(getApplicationContext(),R.style.PreyTextAppearance);
* pass = new
* AlertDialog.Builder(AgreementDialogActivity.this).setIcon(R.drawable
* .info).setTitle(R.string.password_dialog_forgot_sent_title)
* .setMessage(message).setCancelable(true).setPositiveButton(R.string.ok, new
* DialogInterface.OnClickListener() {
*
* public void onClick(DialogInterface dialog, int which) {
*
* } }).create(); } return pass; }
*
* private class ReportForgotPassword extends AsyncTask<Void, Void, Void> {
*
* ProgressDialog progressDialog = null; private String error = null;
*
* @Override protected void onPreExecute() { progressDialog = new
* ProgressDialog(AgreementDialogActivity.this);
* progressDialog.setMessage(AgreementDialogActivity
* .this.getText(R.string.password_dialog_forgot_requesting).toString());
* progressDialog.setIndeterminate(true); progressDialog.setCancelable(false);
* progressDialog.show(); }
*
* @Override protected Void doInBackground(Void... passwords) { try {
* PreyWebServices.getInstance().forgotPassword(AgreementDialogActivity.this); }
* catch (PreyException e) { error = e.getMessage(); } return null; }
*
* @Override protected void onPostExecute(Void unused) {
* progressDialog.dismiss(); if (error == null) { showDialog(INSTRUCTIONS_SENT);
* } else { Toast.makeText(AgreementDialogActivity.this, error,
* Toast.LENGTH_LONG).show(); setResult(RESULT_CANCELED); }
*
* }
*
* }
*
* private class CheckPassword extends AsyncTask<String, Void, Void> {
*
* ProgressDialog progressDialog = null; boolean isPasswordOk = false; boolean
* keepAsking = true; String error = null;
*
* @Override protected void onPreExecute() {
*
* progressDialog = new ProgressDialog(AgreementDialogActivity.this);
* progressDialog.setMessage(AgreementDialogActivity.this.getText(R.string.
* password_checking_dialog).toString()); progressDialog.setIndeterminate(true);
* progressDialog.setCancelable(false); progressDialog.show(); }
*
* @Override protected Void doInBackground(String... password) { try { String
* email = PreyConfig.getPreyConfig(getBaseContext()).getEmail(); isPasswordOk =
* PreyWebServices.getInstance().checkPassword(AgreementDialogActivity.this,
* email, password[0]); if (isPasswordOk)
* PreyConfig.getPreyConfig(AgreementDialogActivity
* .this).setPassword(password[0]);
*
* } catch (PreyException e) { error = e.getMessage(); } return null; }
*
* @Override protected void onPostExecute(Void unused) {
* progressDialog.dismiss(); if (error != null)
* Toast.makeText(AgreementDialogActivity.this, error,
* Toast.LENGTH_LONG).show(); else if (!isPasswordOk) { boolean
* isAccountVerified =
* PreyConfig.getPreyConfig(AgreementDialogActivity.this).isAccountVerified();
* if (!isAccountVerified) Toast.makeText(AgreementDialogActivity.this,
* R.string.verify_your_account_first, Toast.LENGTH_LONG).show(); else {
* wrongPasswordIntents++; if (wrongPasswordIntents == 3) {
* Toast.makeText(AgreementDialogActivity.this,
* R.string.password_intents_exceed, Toast.LENGTH_LONG).show();
* setResult(RESULT_CANCELED); finish(); } else {
* Toast.makeText(AgreementDialogActivity.this, R.string.password_wrong,
* Toast.LENGTH_SHORT).show(); } } } else { setResult(RESULT_OK); finish(); } }
*
* }
*
* }
*/
| gpl-3.0 |
Franck-MOREAU/dolibarr | htdocs/product/reassort.php | 15568 | <?php
/* Copyright (C) 2001-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2004-2015 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2005-2012 Regis Houssin <regis.houssin@capnetworks.com>
* Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
* Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/product/reassort.php
* \ingroup produit
* \brief Page to list stocks
*/
require '../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
$langs->load("products");
$langs->load("stocks");
// Security check
if ($user->societe_id) $socid=$user->societe_id;
$result=restrictedArea($user,'produit|service');
$action=GETPOST('action','alpha');
$sref=GETPOST("sref");
$snom=GETPOST("snom");
$sall=GETPOST("sall");
$type=GETPOST("type","int");
$sbarcode=GETPOST("sbarcode");
$catid=GETPOST('catid','int');
$toolowstock=GETPOST('toolowstock');
$tosell = GETPOST("tosell");
$tobuy = GETPOST("tobuy");
$fourn_id = GETPOST("fourn_id",'int');
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
$page = GETPOST("page",'int');
if (! $sortfield) $sortfield="p.ref";
if (! $sortorder) $sortorder="ASC";
$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
$offset = $limit * $page ;
// Load sale and categ filters
$search_sale = GETPOST("search_sale");
$search_categ = GETPOST("search_categ");
// Get object canvas (By default, this is not defined, so standard usage of dolibarr)
$canvas=GETPOST("canvas");
$objcanvas=null;
if (! empty($canvas))
{
require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php';
$objcanvas = new Canvas($db,$action);
$objcanvas->getCanvas('product','list',$canvas);
}
// Define virtualdiffersfromphysical
$virtualdiffersfromphysical=0;
if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER))
{
$virtualdiffersfromphysical=1; // According to increase/decrease stock options, virtual and physical stock may differs.
}
/*
* Actions
*/
if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All test are required to be compatible with all browsers
{
$sref="";
$snom="";
$sall="";
$search_sale="";
$search_categ="";
$type="";
$catid='';
$toolowstock='';
}
/*
* View
*/
$helpurl='EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks';
$form=new Form($db);
$htmlother=new FormOther($db);
$title=$langs->trans("ProductsAndServices");
$sql = 'SELECT p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,';
$sql.= ' p.fk_product_type, p.tms as datem,';
$sql.= ' p.duration, p.tosell as statut, p.tobuy, p.seuil_stock_alerte, p.desiredstock,';
$sql.= ' SUM(s.reel) as stock_physique';
$sql.= ' FROM '.MAIN_DB_PREFIX.'product as p';
$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as s on p.rowid = s.fk_product';
// We'll need this table joined to the select in order to filter by categ
if ($search_categ) $sql.= ", ".MAIN_DB_PREFIX."categorie_product as cp";
$sql.= " WHERE p.entity IN (".getEntity('product', 1).")";
if ($search_categ) $sql.= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ
if ($sall)
{
$sql.= " AND (p.ref LIKE '%".$db->escape($sall)."%' OR p.label LIKE '%".$db->escape($sall)."%' OR p.description LIKE '%".$db->escape($sall)."%' OR p.note LIKE '%".$db->escape($sall)."%')";
}
// if the type is not 1, we show all products (type = 0,2,3)
if (dol_strlen($type))
{
if ($type==1)
{
$sql.= " AND p.fk_product_type = '1'";
}
else
{
$sql.= " AND p.fk_product_type <> '1'";
}
}
if ($sref) $sql.= " AND p.ref LIKE '%".$sref."%'";
if ($sbarcode) $sql.= " AND p.barcode LIKE '%".$sbarcode."%'";
if ($snom) $sql.= " AND p.label LIKE '%".$db->escape($snom)."%'";
if (! empty($tosell))
{
$sql.= " AND p.tosell = ".$tosell;
}
if (! empty($tobuy))
{
$sql.= " AND p.tobuy = ".$tobuy;
}
if (! empty($canvas))
{
$sql.= " AND p.canvas = '".$db->escape($canvas)."'";
}
if($catid)
{
$sql.= " AND cp.fk_categorie = ".$catid;
}
if ($fourn_id > 0)
{
$sql.= " AND p.rowid = pf.fk_product AND pf.fk_soc = ".$fourn_id;
}
// Insert categ filter
if ($search_categ)
{
$sql .= " AND cp.fk_categorie = ".$db->escape($search_categ);
}
$sql.= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,";
$sql.= " p.fk_product_type, p.tms, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock";
if ($toolowstock) $sql.= " HAVING SUM(".$db->ifsql('s.reel IS NULL', '0', 's.reel').") < p.seuil_stock_alerte"; // Not used yet
$sql.= $db->order($sortfield,$sortorder);
$sql.= $db->plimit($limit + 1, $offset);
$resql = $db->query($sql);
if ($resql)
{
$num = $db->num_rows($resql);
$i = 0;
if ($num == 1 && GETPOST('autojumpifoneonly') && ($sall || $snom || $sref))
{
$objp = $db->fetch_object($resql);
header("Location: card.php?id=$objp->rowid");
exit;
}
if (isset($type))
{
if ($type==1) { $texte = $langs->trans("Services"); }
else { $texte = $langs->trans("Products"); }
} else {
$texte = $langs->trans("ProductsAndServices");
}
$texte.=' ('.$langs->trans("Stocks").')';
llxHeader("", $texte, $helpurl);
if ($sref || $snom || $sall || GETPOST('search'))
{
print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], "&sref=".$sref."&snom=".$snom."&sall=".$sall."&tosell=".$tosell."&tobuy=".$tobuy.(!empty($search_categ) ? '&search_categ='.$search_categ : '').(!empty($toolowstock) ? '&toolowstock='.$toolowstock : ''), $sortfield, $sortorder,'',$num, 0, 'title_products');
}
else
{
print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], "&sref=$sref&snom=$snom&fourn_id=$fourn_id".(isset($type)?"&type=$type":"").(!empty($search_categ) ? '&search_categ='.$search_categ : '').(!empty($toolowstock) ? '&toolowstock='.$toolowstock : ''), $sortfield, $sortorder,'',$num, 0, 'title_products');
}
if (! empty($catid))
{
print "<div id='ways'>";
$c = new Categorie($db);
$c->fetch($catid);
$ways = $c->print_all_ways(' > ','product/reassort.php');
print " > ".$ways[0]."<br>\n";
print "</div><br>";
}
print '<form action="'. $_SERVER["PHP_SELF"] .'" method="post" name="formulaire">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
print '<input type="hidden" name="type" value="'.$type.'">';
// Filter on categories
$moreforfilter='';
if (! empty($conf->categorie->enabled))
{
$moreforfilter.='<div class="divsearchfield">';
$moreforfilter.=$langs->trans('Categories'). ': ';
$moreforfilter.=$htmlother->select_categories(Categorie::TYPE_PRODUCT,$search_categ,'search_categ');
$moreforfilter.='</div>';
}
$moreforfilter.='<div class="divsearchfield">';
$moreforfilter.=$langs->trans("StockTooLow").' <input type="checkbox" name="toolowstock" value="1"'.($toolowstock?' checked':'').'>';
$moreforfilter.='</div>';
if (! empty($moreforfilter))
{
print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter;
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
print '</div>';
}
$param='';
if ($tosell) $param.="&tosell=".$tosell;
if ($tobuy) $param.="&tobuy=".$tobuy;
if ($type) $param.="&type=".$type;
if ($fourn_id) $param.="&fourn_id=".$fourn_id;
if ($snom) $param.="&snom=".$snom;
if ($sref) $param.="&sref=".$sref;
$formProduct = new FormProduct($db);
$formProduct->loadWarehouses();
$warehouses_list = $formProduct->cache_warehouses;
$nb_warehouse = count($warehouses_list);
$colspan_warehouse = 1;
if (! empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) { $colspan_warehouse = $nb_warehouse > 1 ? $nb_warehouse+1 : 1; }
print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">';
// Lignes des titres
print "<tr class=\"liste_titre\">";
print_liste_field_titre($langs->trans("Ref"), $_SERVER["PHP_SELF"], "p.ref",$param,"","",$sortfield,$sortorder);
print_liste_field_titre($langs->trans("Label"), $_SERVER["PHP_SELF"], "p.label",$param,"","",$sortfield,$sortorder);
if (! empty($conf->service->enabled) && $type == 1) print_liste_field_titre($langs->trans("Duration"), $_SERVER["PHP_SELF"], "p.duration",$param,"",'align="center"',$sortfield,$sortorder);
print_liste_field_titre($langs->trans("StockLimit"), $_SERVER["PHP_SELF"], "p.seuil_stock_alerte",$param,"",'align="right"',$sortfield,$sortorder);
print_liste_field_titre($langs->trans("DesiredStock"), $_SERVER["PHP_SELF"], "p.desiredstock",$param,"",'align="right"',$sortfield,$sortorder);
print_liste_field_titre($langs->trans("PhysicalStock"), $_SERVER["PHP_SELF"], "stock_physique",$param,"",'align="right"',$sortfield,$sortorder);
// Details per warehouse
if (! empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) // TODO This should be moved into the selection of fields on page product/list (page product/stock will be removed and replaced with product/list with its own context)
{
if ($nb_warehouse>1) {
foreach($warehouses_list as &$wh) {
print_liste_field_titre($wh['label'], '', '','','','align="right"');
}
}
}
if ($virtualdiffersfromphysical) print_liste_field_titre($langs->trans("VirtualStock"),$_SERVER["PHP_SELF"], "",$param,"",'align="right"',$sortfield,$sortorder);
print_liste_field_titre('');
print_liste_field_titre($langs->trans("Status").' ('.$langs->trans("Sell").')',$_SERVER["PHP_SELF"], "p.tosell",$param,"",'align="right"',$sortfield,$sortorder);
print_liste_field_titre($langs->trans("Status").' ('.$langs->trans("Buy").')',$_SERVER["PHP_SELF"], "p.tobuy",$param,"",'align="right"',$sortfield,$sortorder);
print "</tr>\n";
// Lignes des champs de filtre
print '<tr class="liste_titre">';
print '<td class="liste_titre">';
print '<input class="flat" type="text" name="sref" size="6" value="'.$sref.'">';
print '</td>';
print '<td class="liste_titre">';
print '<input class="flat" type="text" name="snom" size="8" value="'.$snom.'">';
print '</td>';
// Duration
if (! empty($conf->service->enabled) && $type == 1)
{
print '<td class="liste_titre">';
print ' ';
print '</td>';
}
// Stock limit
print '<td class="liste_titre"> </td>';
print '<td class="liste_titre" align="right"> </td>';
print '<td class="liste_titre"> </td>';
if ($virtualdiffersfromphysical) print '<td class="liste_titre"> </td>';
print '<td class="liste_titre"> </td>';
print '<td class="liste_titre" colspan="'.$colspan_warehouse.'"> </td>';
print '<td class="liste_titre" align="right">';
$searchpitco=$form->showFilterAndCheckAddButtons(0);
print $searchpitco;
print '</td>';
print '</tr>';
$var=True;
while ($i < min($num,$limit))
{
$objp = $db->fetch_object($resql);
$var=!$var;
print '<tr '.$bc[$var].'><td class="nowrap">';
$product=new Product($db);
$product->fetch($objp->rowid);
$product->load_stock();
print $product->getNomUrl(1,'',16);
//if ($objp->stock_theorique < $objp->seuil_stock_alerte) print ' '.img_warning($langs->trans("StockTooLow"));
print '</td>';
print '<td>'.$product->label.'</td>';
if (! empty($conf->service->enabled) && $type == 1)
{
print '<td align="center">';
if (preg_match('/([0-9]+)y/i',$objp->duration,$regs)) print $regs[1].' '.$langs->trans("DurationYear");
elseif (preg_match('/([0-9]+)m/i',$objp->duration,$regs)) print $regs[1].' '.$langs->trans("DurationMonth");
elseif (preg_match('/([0-9]+)d/i',$objp->duration,$regs)) print $regs[1].' '.$langs->trans("DurationDay");
else print $objp->duration;
print '</td>';
}
//print '<td align="right">'.$objp->stock_theorique.'</td>';
print '<td align="right">'.$objp->seuil_stock_alerte.'</td>';
print '<td align="right">'.$objp->desiredstock.'</td>';
// Real stock
print '<td align="right">';
if ($objp->seuil_stock_alerte != '' && ($objp->stock_physique < $objp->seuil_stock_alerte)) print img_warning($langs->trans("StockTooLow")).' ';
print $objp->stock_physique;
print '</td>';
// Details per warehouse
if (! empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) // TODO This should be moved into the selection of fields on page product/list (page product/stock will be removed and replaced with product/list with its own context)
{
if($nb_warehouse>1) {
foreach($warehouses_list as &$wh) {
print '<td align="right">';
print empty($product->stock_warehouse[$wh['id']]->real) ? '0' : $product->stock_warehouse[$wh['id']]->real;
print '</td>';
}
}
}
// Virtual stock
if ($virtualdiffersfromphysical)
{
print '<td align="right">';
if ($objp->seuil_stock_alerte != '' && ($product->stock_theorique < $objp->seuil_stock_alerte)) print img_warning($langs->trans("StockTooLow")).' ';
print $product->stock_theorique;
print '</td>';
}
print '<td align="right"><a href="'.DOL_URL_ROOT.'/product/stock/mouvement.php?idproduct='.$product->id.'">'.$langs->trans("Movements").'</a></td>';
print '<td align="right" class="nowrap">'.$product->LibStatut($objp->statut,5,0).'</td>';
print '<td align="right" class="nowrap">'.$product->LibStatut($objp->tobuy,5,1).'</td>';
print "</tr>\n";
$i++;
}
print "</table>";
print '</form>';
if ($num > $conf->liste_limit)
{
if ($sref || $snom || $sall || GETPOST('search'))
{
print_barre_liste('', $page, "reassort.php", "&sref=".$sref."&snom=".$snom."&sall=".$sall."&tosell=".$tosell."&tobuy=".$tobuy.(!empty($search_categ) ? '&search_categ='.$search_categ : '').(!empty($toolowstock) ? '&toolowstock='.$toolowstock : ''), $sortfield, $sortorder,'',$num, 0, '');
}
else
{
print_barre_liste('', $page, "reassort.php", "&sref=$sref&snom=$snom&fourn_id=$fourn_id".(isset($type)?"&type=$type":"")."&tosell=".$tosell."&tobuy=".$tobuy.(!empty($search_categ) ? '&search_categ='.$search_categ : '').(!empty($toolowstock) ? '&toolowstock='.$toolowstock : ''), $sortfield, $sortorder,'',$num, 0, '');
}
}
$db->free($resql);
}
else
{
dol_print_error($db);
}
llxFooter();
$db->close();
| gpl-3.0 |
azarkevich/gitextensions | GitUI/CommandsDialogs/FormDeleteRemoteBranch.Designer.cs | 8786 | namespace GitUI.CommandsDialogs
{
partial class FormDeleteRemoteBranch
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormDeleteRemoteBranch));
this.Delete = new System.Windows.Forms.Button();
this.labelSelectBranches = new System.Windows.Forms.Label();
this.labelDeleteBranchWarning = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.DeleteRemote = new System.Windows.Forms.CheckBox();
this.Branches = new GitUI.BranchComboBox();
this.gotoUserManualControl1 = new GitUI.UserControls.GotoUserManualControl();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// Delete
//
this.Delete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.Delete.Enabled = false;
this.Delete.ForeColor = System.Drawing.Color.Black;
this.Delete.Image = global::GitUI.Properties.Resources.IconBranchDelete;
this.Delete.Location = new System.Drawing.Point(553, 80);
this.Delete.Margin = new System.Windows.Forms.Padding(4);
this.Delete.Name = "Delete";
this.Delete.Size = new System.Drawing.Size(150, 31);
this.Delete.TabIndex = 4;
this.Delete.Text = "Delete";
this.Delete.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.Delete.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.Delete.UseVisualStyleBackColor = true;
this.Delete.Click += new System.EventHandler(this.OkClick);
//
// labelSelectBranches
//
this.labelSelectBranches.AutoSize = true;
this.labelSelectBranches.ForeColor = System.Drawing.Color.Black;
this.labelSelectBranches.Location = new System.Drawing.Point(11, 11);
this.labelSelectBranches.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.labelSelectBranches.Name = "labelSelectBranches";
this.labelSelectBranches.Size = new System.Drawing.Size(104, 17);
this.labelSelectBranches.TabIndex = 1;
this.labelSelectBranches.Text = "Select branches";
//
// labelDeleteBranchWarning
//
this.labelDeleteBranchWarning.AutoSize = true;
this.labelDeleteBranchWarning.ForeColor = System.Drawing.Color.Black;
this.labelDeleteBranchWarning.Location = new System.Drawing.Point(49, 145);
this.labelDeleteBranchWarning.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.labelDeleteBranchWarning.MaximumSize = new System.Drawing.Size(625, 0);
this.labelDeleteBranchWarning.Name = "labelDeleteBranchWarning";
this.labelDeleteBranchWarning.Size = new System.Drawing.Size(612, 68);
this.labelDeleteBranchWarning.TabIndex = 5;
this.labelDeleteBranchWarning.Text = resources.GetString("labelDeleteBranchWarning.Text");
//
// pictureBox1
//
this.pictureBox1.Image = global::GitUI.Properties.Resources.IconWarning;
this.pictureBox1.InitialImage = global::GitUI.Properties.Resources.IconWarning;
this.pictureBox1.Location = new System.Drawing.Point(15, 178);
this.pictureBox1.Margin = new System.Windows.Forms.Padding(4);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(26, 25);
this.pictureBox1.TabIndex = 7;
this.pictureBox1.TabStop = false;
//
// DeleteRemote
//
this.DeleteRemote.AutoSize = true;
this.DeleteRemote.Location = new System.Drawing.Point(15, 86);
this.DeleteRemote.Margin = new System.Windows.Forms.Padding(4);
this.DeleteRemote.Name = "DeleteRemote";
this.DeleteRemote.Size = new System.Drawing.Size(176, 21);
this.DeleteRemote.TabIndex = 3;
this.DeleteRemote.Text = "Delete branche(s) from remote repository";
this.DeleteRemote.UseVisualStyleBackColor = true;
this.DeleteRemote.CheckedChanged += new System.EventHandler(this.DeleteRemote_CheckedChanged);
//
// Branches
//
this.Branches.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.Branches.BranchesToSelect = null;
this.Branches.Location = new System.Drawing.Point(15, 44);
this.Branches.Margin = new System.Windows.Forms.Padding(0);
this.Branches.Name = "Branches";
this.Branches.Size = new System.Drawing.Size(688, 26);
this.Branches.TabIndex = 2;
//
// gotoUserManualControl1
//
this.gotoUserManualControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.gotoUserManualControl1.AutoSize = true;
this.gotoUserManualControl1.Location = new System.Drawing.Point(12, 264);
this.gotoUserManualControl1.ManualSectionAnchorName = "delete-branch";
this.gotoUserManualControl1.ManualSectionSubfolder = "branches";
this.gotoUserManualControl1.Margin = new System.Windows.Forms.Padding(4);
this.gotoUserManualControl1.MinimumSize = new System.Drawing.Size(88, 25);
this.gotoUserManualControl1.Name = "gotoUserManualControl1";
this.gotoUserManualControl1.Size = new System.Drawing.Size(88, 25);
this.gotoUserManualControl1.TabIndex = 8;
//
// FormDeleteRemoteBranch
//
this.AcceptButton = this.Delete;
this.AutoScaleDimensions = new System.Drawing.SizeF(120F, 120F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.ClientSize = new System.Drawing.Size(724, 295);
this.Controls.Add(this.gotoUserManualControl1);
this.Controls.Add(this.Branches);
this.Controls.Add(this.DeleteRemote);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.labelDeleteBranchWarning);
this.Controls.Add(this.Delete);
this.Controls.Add(this.labelSelectBranches);
this.Margin = new System.Windows.Forms.Padding(4);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(652, 326);
this.Name = "FormDeleteRemoteBranch";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Delete branch";
this.Load += new System.EventHandler(this.FormDeleteRemoteBranchLoad);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button Delete;
private System.Windows.Forms.Label labelSelectBranches;
private System.Windows.Forms.Label labelDeleteBranchWarning;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.CheckBox DeleteRemote;
private BranchComboBox Branches;
private UserControls.GotoUserManualControl gotoUserManualControl1;
}
} | gpl-3.0 |
arael120/App-Beicor | node_modules/@ionic/app-scripts/dist/build.js | 13685 | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Constants = require("./util/constants");
var interfaces_1 = require("./util/interfaces");
var errors_1 = require("./util/errors");
var events_1 = require("./util/events");
var helpers_1 = require("./util/helpers");
var bundle_1 = require("./bundle");
var clean_1 = require("./clean");
var copy_1 = require("./copy");
var lint_1 = require("./lint");
var logger_1 = require("./logger/logger");
var minify_1 = require("./minify");
var ngc_1 = require("./ngc");
var postprocess_1 = require("./postprocess");
var preprocess_1 = require("./preprocess");
var sass_1 = require("./sass");
var template_1 = require("./template");
var transpile_1 = require("./transpile");
function build(context) {
helpers_1.setContext(context);
var logger = new logger_1.Logger("build " + (context.isProd ? 'prod' : 'dev'));
return buildWorker(context)
.then(function () {
// congrats, we did it! (•_•) / ( •_•)>⌐■-■ / (⌐■_■)
logger.finish();
})
.catch(function (err) {
if (err.isFatal) {
throw err;
}
throw logger.fail(err);
});
}
exports.build = build;
function buildWorker(context) {
return Promise.resolve().then(function () {
// load any 100% required files to ensure they exist
return validateRequiredFilesExist();
})
.then(function (_a) {
var _ = _a[0], tsConfigContents = _a[1];
return validateTsConfigSettings(tsConfigContents);
})
.then(function () {
return buildProject(context);
});
}
function validateRequiredFilesExist() {
return Promise.all([
helpers_1.readFileAsync(process.env[Constants.ENV_APP_ENTRY_POINT]),
helpers_1.readFileAsync(process.env[Constants.ENV_TS_CONFIG])
]).catch(function (error) {
if (error.code === 'ENOENT' && error.path === process.env[Constants.ENV_APP_ENTRY_POINT]) {
error = new errors_1.BuildError(error.path + " was not found. The \"main.dev.ts\" and \"main.prod.ts\" files have been deprecated. Please create a new file \"main.ts\" containing the content of \"main.dev.ts\", and then delete the deprecated files.\n For more information, please see the default Ionic project main.ts file here:\n https://github.com/driftyco/ionic2-app-base/tree/master/src/app/main.ts");
error.isFatal = true;
throw error;
}
if (error.code === 'ENOENT' && error.path === process.env[Constants.ENV_TS_CONFIG]) {
error = new errors_1.BuildError([error.path + " was not found. The \"tsconfig.json\" file is missing. This file is required.",
'For more information please see the default Ionic project tsconfig.json file here:',
'https://github.com/driftyco/ionic2-app-base/blob/master/tsconfig.json'].join('\n'));
error.isFatal = true;
throw error;
}
error.isFatal = true;
throw error;
});
}
function validateTsConfigSettings(tsConfigFileContents) {
return new Promise(function (resolve, reject) {
try {
var tsConfigJson = JSON.parse(tsConfigFileContents);
var isValid = tsConfigJson.hasOwnProperty('compilerOptions') &&
tsConfigJson.compilerOptions.hasOwnProperty('sourceMap') &&
tsConfigJson.compilerOptions.sourceMap === true;
if (!isValid) {
var error = new errors_1.BuildError(['The "tsconfig.json" file must have compilerOptions.sourceMap set to true.',
'For more information please see the default Ionic project tsconfig.json file here:',
'https://github.com/driftyco/ionic2-app-base/blob/master/tsconfig.json'].join('\n'));
error.isFatal = true;
return reject(error);
}
resolve();
}
catch (e) {
var error = new errors_1.BuildError('The "tsconfig.json" file contains malformed JSON.');
error.isFatal = true;
return reject(error);
}
});
}
function buildProject(context) {
// sync empty the www/build directory
clean_1.clean(context);
buildId++;
var copyPromise = copy_1.copy(context);
var compilePromise = (context.runAot) ? ngc_1.ngc(context) : transpile_1.transpile(context);
return compilePromise
.then(function () {
return preprocess_1.preprocess(context);
})
.then(function () {
return bundle_1.bundle(context);
})
.then(function () {
var minPromise = (context.runMinifyJs) ? minify_1.minifyJs(context) : Promise.resolve();
var sassPromise = sass_1.sass(context)
.then(function () {
return (context.runMinifyCss) ? minify_1.minifyCss(context) : Promise.resolve();
});
return Promise.all([
minPromise,
sassPromise,
copyPromise
]);
})
.then(function () {
return postprocess_1.postprocess(context);
})
.then(function () {
if (helpers_1.getBooleanPropertyValue(Constants.ENV_ENABLE_LINT)) {
// kick off the tslint after everything else
// nothing needs to wait on its completion unless bailing on lint error is enabled
var result = lint_1.lint(context);
if (helpers_1.getBooleanPropertyValue(Constants.ENV_BAIL_ON_LINT_ERROR)) {
return result;
}
}
})
.catch(function (err) {
throw new errors_1.BuildError(err);
});
}
function buildUpdate(changedFiles, context) {
return new Promise(function (resolve) {
var logger = new logger_1.Logger('build');
buildId++;
var buildUpdateMsg = {
buildId: buildId,
reloadApp: false
};
events_1.emit(events_1.EventType.BuildUpdateStarted, buildUpdateMsg);
function buildTasksDone(resolveValue) {
// all build tasks have been resolved or one of them
// bailed early, stopping all others to not run
parallelTasksPromise.then(function () {
// all parallel tasks are also done
// so now we're done done
var buildUpdateMsg = {
buildId: buildId,
reloadApp: resolveValue.requiresAppReload
};
events_1.emit(events_1.EventType.BuildUpdateCompleted, buildUpdateMsg);
if (!resolveValue.requiresAppReload) {
// just emit that only a certain file changed
// this one is useful when only a sass changed happened
// and the webpack only needs to livereload the css
// but does not need to do a full page refresh
events_1.emit(events_1.EventType.FileChange, resolveValue.changedFiles);
}
var requiresLintUpdate = false;
for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) {
var changedFile = changedFiles_1[_i];
if (changedFile.ext === '.ts') {
if (changedFile.event === 'change' || changedFile.event === 'add') {
requiresLintUpdate = true;
break;
}
}
}
if (requiresLintUpdate) {
// a ts file changed, so let's lint it too, however
// this task should run as an after thought
if (helpers_1.getBooleanPropertyValue(Constants.ENV_ENABLE_LINT)) {
lint_1.lintUpdate(changedFiles, context);
}
}
logger.finish('green', true);
logger_1.Logger.newLine();
// we did it!
resolve();
});
}
// kick off all the build tasks
// and the tasks that can run parallel to all the build tasks
var buildTasksPromise = buildUpdateTasks(changedFiles, context);
var parallelTasksPromise = buildUpdateParallelTasks(changedFiles, context);
// whether it was resolved or rejected, we need to do the same thing
buildTasksPromise
.then(buildTasksDone)
.catch(function () {
buildTasksDone({
requiresAppReload: false,
changedFiles: changedFiles
});
});
});
}
exports.buildUpdate = buildUpdate;
/**
* Collection of all the build tasks than need to run
* Each task will only run if it's set with eacn BuildState.
*/
function buildUpdateTasks(changedFiles, context) {
var resolveValue = {
requiresAppReload: false,
changedFiles: []
};
return loadFiles(changedFiles, context)
.then(function () {
// TEMPLATE
if (context.templateState === interfaces_1.BuildState.RequiresUpdate) {
resolveValue.requiresAppReload = true;
return template_1.templateUpdate(changedFiles, context);
}
// no template updates required
return Promise.resolve();
})
.then(function () {
// TRANSPILE
if (context.transpileState === interfaces_1.BuildState.RequiresUpdate) {
resolveValue.requiresAppReload = true;
// we've already had a successful transpile once, only do an update
// not that we've also already started a transpile diagnostics only
// build that only needs to be completed by the end of buildUpdate
return transpile_1.transpileUpdate(changedFiles, context);
}
else if (context.transpileState === interfaces_1.BuildState.RequiresBuild) {
// run the whole transpile
resolveValue.requiresAppReload = true;
return transpile_1.transpile(context);
}
// no transpiling required
return Promise.resolve();
})
.then(function () {
// PREPROCESS
return preprocess_1.preprocessUpdate(changedFiles, context);
})
.then(function () {
// BUNDLE
if (context.bundleState === interfaces_1.BuildState.RequiresUpdate) {
// we need to do a bundle update
resolveValue.requiresAppReload = true;
return bundle_1.bundleUpdate(changedFiles, context);
}
else if (context.bundleState === interfaces_1.BuildState.RequiresBuild) {
// we need to do a full bundle build
resolveValue.requiresAppReload = true;
return bundle_1.bundle(context);
}
// no bundling required
return Promise.resolve();
})
.then(function () {
// SASS
if (context.sassState === interfaces_1.BuildState.RequiresUpdate) {
// we need to do a sass update
return sass_1.sassUpdate(changedFiles, context).then(function (outputCssFile) {
var changedFile = {
event: Constants.FILE_CHANGE_EVENT,
ext: '.css',
filePath: outputCssFile
};
context.fileCache.set(outputCssFile, { path: outputCssFile, content: outputCssFile });
resolveValue.changedFiles.push(changedFile);
});
}
else if (context.sassState === interfaces_1.BuildState.RequiresBuild) {
// we need to do a full sass build
return sass_1.sass(context).then(function (outputCssFile) {
var changedFile = {
event: Constants.FILE_CHANGE_EVENT,
ext: '.css',
filePath: outputCssFile
};
context.fileCache.set(outputCssFile, { path: outputCssFile, content: outputCssFile });
resolveValue.changedFiles.push(changedFile);
});
}
// no sass build required
return Promise.resolve();
})
.then(function () {
return resolveValue;
});
}
function loadFiles(changedFiles, context) {
// UPDATE IN-MEMORY FILE CACHE
var promises = [];
var _loop_1 = function (changedFile) {
if (changedFile.event === Constants.FILE_DELETE_EVENT) {
// remove from the cache on delete
context.fileCache.remove(changedFile.filePath);
}
else {
// load the latest since the file changed
var promise = helpers_1.readFileAsync(changedFile.filePath);
promises.push(promise);
promise.then(function (content) {
context.fileCache.set(changedFile.filePath, { path: changedFile.filePath, content: content });
});
}
};
for (var _i = 0, changedFiles_2 = changedFiles; _i < changedFiles_2.length; _i++) {
var changedFile = changedFiles_2[_i];
_loop_1(changedFile);
}
return Promise.all(promises);
}
/**
* parallelTasks are for any tasks that can run parallel to the entire
* build, but we still need to make sure they've completed before we're
* all done, it's also possible there are no parallelTasks at all
*/
function buildUpdateParallelTasks(changedFiles, context) {
var parallelTasks = [];
if (context.transpileState === interfaces_1.BuildState.RequiresUpdate) {
parallelTasks.push(transpile_1.transpileDiagnosticsOnly(context));
}
return Promise.all(parallelTasks);
}
var buildId = 0;
| gpl-3.0 |
firelab/OpenFOAM-2.2.x | src/OpenFOAM/matrices/lduMatrix/lduAddressing/lduInterfaceFields/processorLduInterfaceField/processorLduInterfaceField.H | 3619 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2012 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::processorLduInterfaceField
Description
Abstract base class for processor coupled interfaces.
SourceFiles
processorLduInterfaceField.C
\*---------------------------------------------------------------------------*/
#ifndef processorLduInterfaceField_H
#define processorLduInterfaceField_H
#include "primitiveFieldsFwd.H"
#include "typeInfo.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class processorLduInterfaceField Declaration
\*---------------------------------------------------------------------------*/
class processorLduInterfaceField
{
public:
//- Runtime type information
TypeName("processorLduInterfaceField");
// Constructors
//- Construct given coupled patch
processorLduInterfaceField()
{}
//- Destructor
virtual ~processorLduInterfaceField();
// Member Functions
// Access
//- Return processor number
virtual int myProcNo() const = 0;
//- Return neigbour processor number
virtual int neighbProcNo() const = 0;
//- Is the transform required
virtual bool doTransform() const = 0;
//- Return face transformation tensor
virtual const tensorField& forwardT() const = 0;
//- Return rank of component for transform
virtual int rank() const = 0;
//- Transform given patch field
template<class Type>
void transformCoupleField(Field<Type>& f) const;
//- Transform given patch component field
void transformCoupleField
(
scalarField& f,
const direction cmpt
) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#include "tensorField.H"
template<class Type>
void Foam::processorLduInterfaceField::transformCoupleField
(
Field<Type>& f
) const
{
if (doTransform())
{
if (forwardT().size() == 1)
{
transform(f, forwardT()[0], f);
}
else
{
transform(f, forwardT(), f);
}
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| gpl-3.0 |
CLAMP-IT/moodle | admin/tool/cohortroles/version.php | 1206 | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Plugin version info
*
* @package tool_cohortroles
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2021051700; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2021051100; // Requires this Moodle version.
$plugin->component = 'tool_cohortroles'; // Full name of the plugin (used for diagnostics).
$plugin->dependencies = array(
'tool_lp' => ANY_VERSION
);
| gpl-3.0 |
FernandoIsaac/Kunena-Forum | components/com_kunena/site/template/crypsisb3/layouts/topic/edit/editor/default.php | 14253 | <?php
/**
* Kunena Component
*
* @package Kunena.Template.Crypsis
* @subpackage Topic
*
* @copyright (C) 2008 - 2015 Kunena Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @link http://www.kunena.org
**/
defined('_JEXEC') or die ();
$this->getBBcodesEnabled();
// Kunena bbcode editor
?>
<div class="form-group">
<label class="control-label col-md-4"><?php echo (JText::_('COM_KUNENA_MESSAGE')) ; ?></label>
<div class="controls">
<ul id="tabs_kunena_editor" class="nav nav-tabs">
<li class="active"><a href="#write" data-toggle="tab"><?php echo JText::_('COM_KUNENA_EDITOR_TAB_WRITE_LABEL') ?></a></li>
<li><a href="#preview" data-toggle="tab"><?php echo JText::_('COM_KUNENA_PREVIEW') ?></a></li>
</ul>
<textarea class="col-md-12 form-control" name="message" id="kbbcode-message" rows="12" tabindex="7" required="required"><?php echo $this->escape($this->message->message); ?></textarea>
</div>
<!-- Hidden preview placeholder -->
<div class="controls" id="kbbcode-preview" style="display: none;"></div>
</div>
<!-- Bootstrap modal to be used with bbcode editor -->
<div id="modal-map" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_TITLE_MAP_SETTINGS') ?></h3>
</div>
<div class="modal-body">
<p><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_MAP_SETTINGS_TYPE') ?>: <select id="modal-map-type" class="form-control"><option type="HYBRID"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_MAP_SETTINGS_HYBRID') ?></option><option type="ROADMAP"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_MAP_SETTINGS_ROADMAP') ?></option><option type="TERRAIN"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_MAP_SETTINGS_TERRAIN') ?></option><option type="SATELLITE"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_MAP_SETTINGS_SATELLITE') ?></option></select><br />
<?php echo JText::_('COM_KUNENA_EDITOR_MODAL_MAP_SETTINGS_ZOOM_LEVEL') ?>: <select id="modal-map-zoomlevel" class="form-control"><option type="2">2</option><option type="4">4</option><option type="6">6</option><option type="8">8</option><option type="10">10</option><option type="12">12</option><option type="14">14</option><option type="16">16</option><option type="18">18</option></select><br />
<?php echo JText::_('COM_KUNENA_EDITOR_MODAL_MAP_SETTINGS_CITY') ?>: <input name="modal-map-city" id="modal-map-city" type="text" value="" class="form-control" /></p>
</div>
<div class="modal-footer">
<button id="map-modal-submit" class="btn btn-primary"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_ADD_LABEL') ?></button>
<button class="btn btn-default" data-dismiss="modal" aria-hidden="true"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_CLOSE_LABEL') ?></button>
</div>
</div>
</div>
</div>
<?php $codeTypes = $this->getCodeTypes(); if (!empty($codeTypes)) : ?>
<div id="modal-code" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_TITLE_CODE_SETTINGS') ?></h3>
</div>
<div class="modal-body">
<p>
<?php echo $codeTypes; ?>
</p>
</div>
<div class="modal-footer">
<button id="code-modal-submit" class="btn btn-primary"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_ADD_LABEL') ?></button>
<button class="btn btn-default" data-dismiss="modal" aria-hidden="true"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_CLOSE_LABEL') ?></button>
</div>
</div>
</div>
</div>
<?php endif; ?>
<div id="modal-picture" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_TITLE_PICTURE_SETTINGS') ?></h3>
</div>
<div class="modal-body">
<p><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_TITLE_PICTURE_SETTINGS_SIZE') ?>: <input class="form-control" name="modal-picture-size" id="modal-picture-size" type="text" value="" />
<?php echo JText::_('COM_KUNENA_EDITOR_MODAL_TITLE_PICTURE_SETTINGS_URL') ?>: <input class="form-control" name="modal-picture-url" id="modal-picture-url" type="text" value="" /></p>
</div>
<div class="modal-footer">
<button id="picture-modal-submit" class="btn btn-primary"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_ADD_LABEL') ?></button>
<button class="btn btn-default" data-dismiss="modal" aria-hidden="true"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_CLOSE_LABEL') ?></button>
</div>
</div>
</div>
</div>
<div id="modal-link" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_TITLE_LINK_SETTINGS') ?></h3>
</div>
<div class="modal-body">
<p><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_TITLE_LINK_SETTINGS_URL') ?>: <input class="form-control" name="modal-link-url" id="modal-link-url" type="text" value="" />
<?php echo JText::_('COM_KUNENA_EDITOR_MODAL_TITLE_LINK_SETTINGS_TEXT') ?>: <input class="form-control" name="modal-link-text" id="modal-link-text" type="text" value="" /></p>
</div>
<div class="modal-footer">
<button id="link-modal-submit" class="btn btn-primary"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_ADD_LABEL') ?></button>
<button class="btn btn-default" data-dismiss="modal" aria-hidden="true"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_CLOSE_LABEL') ?></button>
</div>
</div>
</div>
</div>
<div id="modal-video-settings" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_TITLE_VIDEO_SETTINGS') ?></h3>
</div>
<div class="modal-body">
<p><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_TITLE_LINK_SETTINGS_SIZE') ?>: <input class="form-control" name="modal-video-size" id="modal-video-size" type="text" maxlength="5" size="5" value="" />
<?php echo JText::_('COM_KUNENA_EDITOR_MODAL_TITLE_LINK_SETTINGS_WIDTH') ?>: <input class="form-control" name="modal-video-width" id="modal-video-width" type="text" maxlength="5" size="5" value="" />
<?php echo JText::_('COM_KUNENA_EDITOR_MODAL_TITLE_LINK_SETTINGS_HEIGHT') ?>: <input class="form-control" name="modal-video-height" id="modal-video-height" type="text" maxlength="5" size="5" value="" />
<?php
echo JText::_('COM_KUNENA_EDITOR_VIDEO_PROVIDER');
?>
<select id="kvideoprovider-list-modal"
name="provider" class="kbutton form-control">
<?php
$vid_provider = array ('', 'Bofunk', 'Break', 'Clipfish', 'DivX,divx]http://', 'Flash,flash]http://', 'FlashVars,flashvars param=]http://', 'MediaPlayer,mediaplayer]http://', 'Metacafe', 'MySpace', 'QuickTime,quicktime]http://', 'RealPlayer,realplayer]http://', 'RuTube', 'Sapo', 'Streetfire', 'Veoh', 'Videojug', 'Vimeo', 'Wideo.fr', 'YouTube' );
foreach ( $vid_provider as $vid_type ) {
$vid_type = explode ( ',', $vid_type );
echo '<option value = "' . (! empty ( $vid_type [1] ) ? $this->escape($vid_type [1]) : Joomla\String\String::strtolower ( $this->escape($vid_type [0]) ) . '') . '">' . $this->escape($vid_type [0]) . '</option>';
}
?>
</select>
<?php echo JText::_('COM_KUNENA_EDITOR_MODAL_TITLE_LINK_SETTINGS_ID') ?>: <input class="form-control" name="modal-video-id" id="modal-video-id" type="text" maxlength="30" size="11" value="" /></p>
</div>
<div class="modal-footer">
<button id="videosettings-modal-submit" class="btn btn-primary"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_ADD_LABEL') ?></button>
<button class="btn btn-default" data-dismiss="modal" aria-hidden="true"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_CLOSE_LABEL') ?></button>
</div>
</div>
</div>
</div>
<div id="modal-video-urlprovider" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_TITLE_VIDEO_URL_PROVIDER') ?></h3>
</div>
<div class="modal-body">
<p><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_TITLE_VIDEO_URL_PROVIDER_URL') ?>: <input class="form-control" name="modal-video-urlprovider-input" id="modal-video-urlprovider-input" type="text" value="" /></p>
</div>
<div class="modal-footer">
<button id="videourlprovider-modal-submit" class="btn btn-primary modal-submit"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_ADD_LABEL') ?></button>
<button class="btn btn-default" data-dismiss="modal" aria-hidden="true"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_CLOSE_LABEL') ?></button>
</div>
</div>
</div>
</div>
<?php if (!$this->message->parent && isset($this->poll)) : ?>
<div id="modal-poll-settings" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_TITLE_POLL_SETTINGS') ?></h3>
</div>
<div class="modal-body">
<div id="kbbcode-poll-options">
<?php JHtml::_('behavior.calendar'); ?>
<label class="kpoll-title-lbl" for="kpoll-title"><?php echo JText::_('COM_KUNENA_POLL_TITLE'); ?></label>
<input type="text" class="inputbox form-control" name="poll_title" id="kpoll-title"
maxlength="100" size="40"
value="<?php echo $this->escape( $this->poll->title ) ?>"
/>
<i id="kbutton-poll-add" class="glyphicon glyphicon-plus btn btn-xs btn-default"
alt="<?php echo JText::_('COM_KUNENA_POLL_ADD_POLL_OPTION'); ?>"> </i>
<i id="kbutton-poll-rem" class="glyphicon glyphicon-minus btn btn-xs btn-default"
alt="<?php echo JText::_('COM_KUNENA_POLL_REMOVE_POLL_OPTION'); ?>"> </i>
<br>
<label class="kpoll-term-lbl" for="kpoll-time-to-live"><?php echo JText::_('COM_KUNENA_POLL_TIME_TO_LIVE'); ?></label>
<?php echo JHtml::_('calendar', isset($this->poll->polltimetolive) ? $this->escape($this->poll->polltimetolive) : '0000-00-00', 'poll_time_to_live', 'kpoll-time-to-live', '%Y-%m-%d', 'class="form-control"'); ?>
<br>
<div id="kpoll-alert-error" class="alert alert-notice" style="display:none;">
<button type="button" class="close" data-dismiss="alert">×</button>
<?php echo JText::sprintf('COM_KUNENA_ALERT_WARNING_X', JText::_('COM_KUNENA_POLL_NUMBER_OPTIONS_MAX_NOW')) ?>
</div>
<?php
if($this->poll->exists()) {
$x = 1;
foreach ($this->poll->getOptions() as $poll_option) {
echo '<div class="polloption">Option '.$x.' <input type="text" class="form-control" size="100" id="field_option'.$x.' '.'" name="polloptionsID['.$poll_option->id.']" value="'.$poll_option->text.'")" /></div>';
$x++;
}
}
?>
<input type="hidden" name="nb_options_allowed" id="nb_options_allowed" value="<?php echo $this->config->pollnboptions; ?>" />
<input type="hidden" name="number_total_options" id="numbertotal"
value="<?php echo !empty ($this->polloptionstotal) ? $this->escape($this->polloptionstotal) : '' ?>" />
</div>
</div>
<div class="modal-footer">
<button id="poll-settings-modal-submit" class="btn btn-primary"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_ADD_LABEL') ?></button>
<button class="btn btn-default" data-dismiss="modal" aria-hidden="true"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_CLOSE_LABEL') ?></button>
</div>
</div>
</div>
</div>
<?php endif; ?>
<div id="modal-emoticons" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Emoticons</h3>
</div>
<div class="modal-body">
<div id="smilie"><?php
$emoticons = KunenaHtmlParser::getEmoticons(0, 1);
foreach ( $emoticons as $emo_code=>$emo_url ) {
echo '<img class="smileyimage" src="' . $emo_url . '" border="0" alt="' . $emo_code . ' " title="' . $emo_code . ' " style="cursor:pointer"/> ';
}
?>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default" data-dismiss="modal" aria-hidden="true"><?php echo JText::_('COM_KUNENA_EDITOR_MODAL_CLOSE_LABEL') ?></button>
</div>
</div>
</div>
</div>
<!-- end of Bootstrap modal to be used with bbcode editor -->
<div class="control-group">
<div class="controls">
<input type="hidden" id="kurl_emojis" name="kurl_emojis" value="<?php echo KunenaRoute::_('index.php?option=com_kunena&view=topic&layout=listemoji&format=raw') ?>" />
<input type="hidden" id="kemojis_allowed" name="kemojis_allowed" value="<?php echo $this->config->disemoticons ?>" />
</div>
</div>
| gpl-3.0 |
pfschwartz/openelisglobal-core | app/src/us/mn/state/health/lims/common/security/PageIdentityUtil.java | 3402 | /**
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations under
* the License.
*
* The Original Code is OpenELIS code.
*
* Copyright (C) The Minnesota Department of Health. All Rights Reserved.
*
* Contributor(s): CIRG, University of Washington, Seattle WA.
*/
package us.mn.state.health.lims.common.security;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.validator.GenericValidator;
import org.owasp.encoder.Encode;
import us.mn.state.health.lims.common.action.IActionConstants;
import us.mn.state.health.lims.common.exception.LIMSRuntimeException;
import us.mn.state.health.lims.common.util.StringUtil;
public class PageIdentityUtil {
private static final String REPORT_PARAMETER = "report";
private static final String TYPE_PARAMETER = "type";
public static boolean isMainPage(HttpServletRequest request) {
String actionName = (String) request.getAttribute(IActionConstants.ACTION_KEY);
return (IActionConstants.MAIN_PAGE.equals(actionName));
}
/*
* This is ripped and simplified from UserModuleDAOImp. In it's most basic form it gets the ACTION_KEY
*/
public static String getActionName(HttpServletRequest request, boolean useParameterExtention) throws LIMSRuntimeException {
String actionName = null;
actionName = (String) request.getAttribute(IActionConstants.ACTION_KEY);
String localizedName = StringUtil.getContextualMessageForKey("dictionary.result.Positif_VIH_2");
System.out.println("gnrTest: " + localizedName);
if (actionName == null) {
System.out.println("actionName is null");
actionName = "dummy";
} else {
System.out.println("actionName is " + Encode.forJava(actionName));
}
if (actionName.equals("QuickEntryAddTestPopup")) {
actionName = "QuickEntry";
} else if (actionName.equals("TestManagementAddTestPopup")) {
actionName = "TestManagement";
} else if (actionName.equals("TestAnalyteTestResultAddDictionaryRGPopup")
|| actionName.equals("TestAnalyteTestResultAddNonDictionaryRGPopup")
|| actionName.equals("TestAnalyteTestResultAddRGPopup")
|| actionName.equals("TestAnalyteTestResultAssignRGPopup")
|| actionName.equals("TestAnalyteTestResultEditDictionaryRGPopup")
|| actionName.equals("TestAnalyteTestResultEditDictionaryRGPopup")
|| actionName.equals("TestAnalyteTestResultEditNonDictionaryRGPopup")) {
actionName = "TestAnalyteTestResult";
} else if (actionName.equals("QaEventsEntryAddQaEventsToTestsPopup")
|| actionName.equals("QaEventsEntryAddActionsToQaEventsPopup")) {
actionName = "QaEventsEntry";
}
actionName = actionName.endsWith("Menu") ? actionName.substring(0, actionName.length() - 4) : actionName;
if(useParameterExtention){
String parameter = request.getParameter(TYPE_PARAMETER);
if( GenericValidator.isBlankOrNull(parameter)){
parameter = request.getParameter(REPORT_PARAMETER);
}
if( !GenericValidator.isBlankOrNull(parameter)){
actionName += ":" + parameter;
}
}
return actionName;
}
}
| mpl-2.0 |
mainakibui/dkobo | jsapp/build_configs/dkobo_xlform.js | 200 | // tells the r.js loader to include these modules
require(['cs!xlform/_xlform.init']);
(function(){
if ( !this.dkobo_xlform ) {
this.dkobo_xlform = require('cs!xlform/_xlform.init');
}
})();
| agpl-3.0 |
sbriseid/GoTools | compositemodel/src/RegularizeUtils.C | 113931 | /*
* Copyright (C) 1998, 2000-2007, 2010, 2011, 2012, 2013 SINTEF ICT,
* Applied Mathematics, Norway.
*
* Contact information: E-mail: tor.dokken@sintef.no
* SINTEF ICT, Department of Applied Mathematics,
* P.O. Box 124 Blindern,
* 0314 Oslo, Norway.
*
* This file is part of GoTools.
*
* GoTools is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* GoTools is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with GoTools. If not, see
* <http://www.gnu.org/licenses/>.
*
* In accordance with Section 7(b) of the GNU Affero General Public
* License, a covered work must retain the producer line in every data
* file that is created or manipulated using GoTools.
*
* Other Usage
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial activities involving the GoTools library without
* disclosing the source code of your own applications.
*
* This file may be used in accordance with the terms contained in a
* written agreement between you and SINTEF ICT.
*/
//#define DEBUG_REG
#include "GoTools/compositemodel/RegularizeUtils.h"
#include "GoTools/compositemodel/Body.h"
#include "GoTools/geometry/BoundedUtils.h"
#include "GoTools/geometry/HermiteInterpolator.h"
#include "GoTools/geometry/ElementaryCurve.h"
#include "GoTools/geometry/Circle.h"
#include "GoTools/geometry/SplineCurve.h"
#include "GoTools/creators/CoonsPatchGen.h"
#include "sislP.h"
#include "GoTools/geometry/SISLconversion.h"
#include <fstream>
using namespace Go;
using std::vector;
using std::pair;
using std::make_pair;
//==========================================================================
vector<shared_ptr<ftSurface> >
RegularizeUtils::divideVertex(shared_ptr<ftSurface> face,
shared_ptr<Vertex> vx,
vector<shared_ptr<Vertex> >& cand_vx,
ftEdge* cand_edge,
vector<shared_ptr<Vertex> >& prio_vx,
double epsge, double tol2, double angtol,
double bend,
vector<shared_ptr<Vertex> >& non_corner,
const Point& centre, const Point& axis,
bool strong)
//==========================================================================
{
// Perform splitting
vector<shared_ptr<CurveOnSurface> > trim_segments;
shared_ptr<BoundedSurface> bd_sf;
trim_segments = findVertexSplit(face, vx, cand_vx, cand_edge,
prio_vx, epsge, tol2, angtol, bend,
non_corner, centre, axis, bd_sf,
strong);
// Define faces
vector<shared_ptr<ftSurface> > faces;
if (trim_segments.size() > 0)
{
vector<shared_ptr<BoundedSurface> > sub_sfs =
BoundedUtils::splitWithTrimSegments(bd_sf, trim_segments, epsge);
#ifdef DEBUG_REG
std::ofstream of("split_surf.g2");
for (size_t kr=0; kr<sub_sfs.size(); ++kr)
{
sub_sfs[kr]->writeStandardHeader(of);
sub_sfs[kr]->write(of);
}
#endif
// Create faces
faces = createFaces(sub_sfs, face,
epsge, tol2, angtol,
non_corner);
}
return faces;
}
//==========================================================================
vector<shared_ptr<CurveOnSurface> >
RegularizeUtils::findVertexSplit(shared_ptr<ftSurface> face,
shared_ptr<Vertex> vx,
vector<shared_ptr<Vertex> >& cand_vx,
ftEdge* cand_edge,
vector<shared_ptr<Vertex> >& prio_vx,
double epsge, double tol2, double angtol,
double bend,
vector<shared_ptr<Vertex> >& non_corner,
const Point& centre, const Point& axis,
shared_ptr<BoundedSurface>& bd_sf,
bool strong)
//==========================================================================
{
#ifdef DEBUG_REG
if (cand_vx.size() > 0)
{
std::ofstream ofvx("cand_vx2.g2");
ofvx << "400 1 0 4 155 100 0 255" << std::endl;
ofvx << cand_vx.size() << std::endl;
for (size_t kj=0; kj<cand_vx.size(); ++kj)
ofvx << cand_vx[kj]->getVertexPoint() << std::endl;
ofvx << "400 1 0 4 0 100 155 255" << std::endl;
ofvx << prio_vx.size() << std::endl;
for (size_t kj=0; kj<prio_vx.size(); ++kj)
ofvx << prio_vx[kj]->getVertexPoint() << std::endl;
}
#endif
shared_ptr<ParamSurface> surf = face->surface();
RectDomain dom = surf->containingDomain();
Point vx_point = vx->getVertexPoint();
Point vx_par = vx->getFacePar(face.get());
// Vertex positions may be inaccurate due to gaps in the model,
// adjust with surface information
adjustVertexPosition(surf, vx_point, vx_par, tol2);
double level_ang = M_PI/3; // M_PI/2.0; // M_PI/4.0; //M_PI/6.0;
Point axis2 = axis;
Point centre2 = centre;
if (centre.dimension() == 3 && axis2.dimension() == 3)
centre2 = centre - ((centre-vx_point)*axis)*axis;
// Fetch adjacent vertices
vector<shared_ptr<Vertex> > next_vxs = vx->getNextVertex(face.get());
// Get the plane with which to divide the current face to get subdivision
// information
Point pnt;
Point normal;
if (centre.dimension() > 0)
{
pnt = centre;
normal = (vx_point - centre).cross(axis);
}
else if (axis.dimension() > 0)
{
pnt = vx_point;
normal = axis;
}
else
getDivisionPlane(face, vx, epsge, pnt, normal);
// Fetch a vector in the given vertex pointing into the surface
Point in_vec = getInVec(vx, face);
in_vec.normalize();
// A patch with 5 sides requires a special treatment to avoid
// a degenerate solution. Check the number of corners
// The same applies to a patch with 4 corners where the given vertex
// is not one of the corners
vector<shared_ptr<Vertex> > corners = face->getCornerVertices(bend);
checkCornerConfig(corners, face, 2.0*bend);
ftEdge* opposite=NULL; // Pointer to edge with opposite point if set
double opposite_dist;
double opposite_par;
Point opposite_point;
if (corners.size() == 4 || corners.size() == 5)
opposite = getOppositeBoundaryPar(face, vx, corners, epsge, tol2,
opposite_point, opposite_par,
opposite_dist);
if (opposite)
{
#ifdef DEBUG_REG
std::ofstream ofvx2("opposite_vx2.g2");
ofvx2 << "400 1 0 4 0 100 155 255" << std::endl;
ofvx2 << "1" << std::endl;
ofvx2 << opposite_point << std::endl;
#endif
}
// Compute tolerance for split curve checking
size_t kr, kh;
double tol3 = tol2;
for (kr=0; kr<corners.size(); ++kr)
{
if (corners[kr].get() == vx.get())
continue;
double dist = corners[kr]->getDist(vx);
tol3 = std::min(tol3, 0.9*dist);
}
// Fetch boundary curve information
vector<shared_ptr<ftEdge> > all_edg = face->getAllEdges();
vector<shared_ptr<ParamCurve> > all_cvs;
getSourceCvs(all_edg, all_cvs);
// Fetch boundary curve information related to selected split vertex
vector<ftEdge*> vx_edg = vx->getFaceEdges(face.get());
vector<shared_ptr<ParamCurve> > vx_cvs;
for (kr=0; kr<vx_edg.size(); ++kr)
{
shared_ptr<ParamCurve> tmp = vx_edg[kr]->geomCurve();
for (kh=0; kh<vx_cvs.size(); ++kh)
if (vx_cvs[kh].get() == tmp.get())
break;
if (kh == vx_cvs.size())
vx_cvs.push_back(tmp);
}
if (centre.dimension() == 0)
{
// Check for circular behaviour
size_t ka;
for (ka=0; ka<all_cvs.size(); ++ka)
{
if (!all_cvs[ka].get())
continue;
if (all_cvs[ka]->instanceType() == Class_Circle)
{
// Check that the circle is not directly connected to
// the split vertex
size_t kb;
for (kb=0; kb<vx_edg.size(); ++kb)
if (all_edg[ka].get() == vx_edg[kb])
break;
// @@@ VSK. There is a risk that the curve is the same, but
// the edge is different so the test above is probably too simple
if (kb == vx_edg.size())
break;
}
}
if (ka < all_cvs.size())
{
shared_ptr<Circle> circ =
dynamic_pointer_cast<Circle,ParamCurve>(all_cvs[ka]);
centre2 = circ->getCentre();
axis2 = circ->getNormal();
double axis_ang = axis2.angle(normal);
double level_ang = 0.25*M_PI;
if (std::min(axis_ang, fabs(M_PI-axis_ang)) < level_ang)
{
centre2.resize(0);
axis2.resize(0);
}
}
}
int close_idx;
double close_dist;
Point close_par, close_pt;
getClosestBoundaryPar(face, vx, vx_cvs, vx_point, in_vec,
epsge, angtol, close_idx, close_dist,
close_par, strong ? 0 : -1);
if (close_idx < 0 && cand_edge)
{
double par;
cand_edge->closestPoint(vx_point, par, close_pt, close_dist);
for (close_idx=0; close_idx<(int)all_edg.size(); ++close_idx)
if (all_edg[close_idx].get() == cand_edge)
break;
if (close_idx == (int)all_edg.size())
close_idx = -1;
else
close_par = cand_edge->faceParameter(par);
}
else if (close_idx >= 0)
close_pt = face->point(close_par[0], close_par[1]);
// Turn off closest point index if the edge doesn't correspond
// to the candidate split edge
// if (close_idx >= 0 && cand_edge && all_edg[close_idx].get() != cand_edge)
// close_idx = -1;
#ifdef DEBUG_REG
std::ofstream ofvx3("closest_vx2.g2");
ofvx3 << "400 1 0 4 0 100 155 255" << std::endl;
ofvx3 << "1" << std::endl;
ofvx3 << face->point(close_par[0],close_par[1]) << std::endl;
if (cand_edge)
{
std::ofstream ofvx4("edge_vx2.g2");
ofvx4 << "400 1 0 4 155 0 100 255" << std::endl;
ofvx4 << "1" << std::endl;
ofvx4 << cand_edge->point(0.5*(cand_edge->tMin()+cand_edge->tMax())) << std::endl;
}
#endif
// Traverse all candidate vertices and check if any is feasible for
// division
// Compute distance between vertices and found plane
// Select vertex with minimum distance
vector<shared_ptr<CurveOnSurface> > trim_segments;
while (prio_vx.size() > 0)
{
size_t nmb_cand = prio_vx.size();
double cyl_rad = -1.0;
int min_idx = selectCandVx(face, vx, in_vec, prio_vx, dom, epsge,
angtol /*bend*/, centre2, normal, vx_cvs, close_dist,
close_pt, cyl_rad, strong ? 2 : 1);
if (min_idx < 0)
{
if (prio_vx.size() < nmb_cand)
continue; // No vertex is choosen, look for a new
else
break; // No legal candidate vertex
}
#ifdef DEBUG_REG
if (min_idx >= 0)
{
std::ofstream ofcurr0("curr_prio_vx.g2");
ofcurr0 << "400 1 0 4 155 0 100 255" << std::endl;
ofcurr0 << 1 << std::endl;
ofcurr0 << prio_vx[min_idx]->getVertexPoint() << std::endl;
}
#endif
if (min_idx >= 0 && cyl_rad > 0.0)
{
// Perform cylinder intersection
trim_segments = BoundedUtils::getCylinderIntersections(surf, centre2,
axis2, cyl_rad,
epsge, bd_sf);
// Remove intersections not connected with the initial point
// Remove also segments going through an adjacent vertex
Point dummy;
checkTrimSeg(trim_segments, next_vxs, vx_point, dummy, tol3 /*epsge*/);
}
if (trim_segments.size() == 0 && min_idx >= 0)
{
// Check the feasability of a stright curve in the
// parameter domain
Point pos2 = prio_vx[min_idx]->getVertexPoint();
Point parval2 = prio_vx[min_idx]->getFacePar(face.get());
adjustVertexPosition(surf, pos2, parval2, tol3);
shared_ptr<ParamCurve> pcurve = checkStrightParCv(face, vx, prio_vx[min_idx],
epsge, bend);
if (pcurve.get())
{
trim_segments = BoundedUtils::getTrimCrvsPcrv(surf, pcurve, epsge,
bd_sf);
}
else
{
// Find division curve between vertices
trim_segments = BoundedUtils::getTrimCrvsParam(surf, vx_par,
parval2, epsge,
bd_sf);
}
#ifdef DEBUG_REG
std::ofstream ofcv("trim_seg0.g2");
for (size_t kj=0; kj<trim_segments.size(); ++kj)
{
shared_ptr<ParamCurve> cv = trim_segments[kj]->spaceCurve();
cv->writeStandardHeader(ofcv);
cv->write(ofcv);
}
#endif
// Check output
checkTrimSeg2(trim_segments, vx_par, parval2, tol3 /*epsge*/);
// Remove intersections not connected with the initial point
// Remove also segments going through an adjacent vertex
if (trim_segments.size() > 0)
{
//Point other_pt = prio_vx[min_idx]->getVertexPoint();
checkTrimSeg(trim_segments, next_vxs, vx_point,
pos2, tol3 /*epsge*/);
}
// Make another try if a non-linear curve failed
if (trim_segments.size() != 1 && pcurve.get())
{
// Find division curve between vertices
trim_segments = BoundedUtils::getTrimCrvsParam(surf, vx_par,
parval2, epsge,
bd_sf);
}
#ifdef DEBUG_REG
std::ofstream ofcv_2("trim_seg0_2.g2");
for (size_t kj=0; kj<trim_segments.size(); ++kj)
{
shared_ptr<ParamCurve> cv = trim_segments[kj]->spaceCurve();
cv->writeStandardHeader(ofcv_2);
cv->write(ofcv_2);
}
#endif
// Check output
checkTrimSeg2(trim_segments, vx_par, parval2, tol3 /*epsge*/);
// Remove intersections not connected with the initial point
// Remove also segments going through an adjacent vertex
if (trim_segments.size() > 0)
{
//Point other_pt = prio_vx[min_idx]->getVertexPoint();
checkTrimSeg(trim_segments, next_vxs, vx_point,
pos2, tol3 /*epsge*/);
}
}
if (trim_segments.size() == 0)
{
// The choosen vertex did not work. Remove it from the pool and try again
prio_vx.erase(prio_vx.begin()+min_idx);
}
else
break;
}
if (trim_segments.size() == 0)
{
while (cand_vx.size() > 0)
{
size_t nmb_cand = cand_vx.size();
double cyl_rad = -1.0;
int min_idx = selectCandVx(face, vx, in_vec, cand_vx, dom, epsge,
bend, centre2, normal, vx_cvs, close_dist,
close_pt, cyl_rad, /*strong ? 1 :*/ 0);
if (min_idx < 0)
{
if (cand_vx.size() < nmb_cand)
continue; // No vertex is choosen, look for a new
else
break; // No legal candidate vertex
}
#ifdef DEBUG_REG
if (min_idx >= 0)
{
std::ofstream ofcurr("curr_cand_vx.g2");
ofcurr << "400 1 0 4 155 0 100 255" << std::endl;
ofcurr << 1 << std::endl;
ofcurr << cand_vx[min_idx]->getVertexPoint() << std::endl;
}
#endif
if (min_idx >= 0 && cyl_rad > 0.0)
{
// Perform cylinder intersection
trim_segments = BoundedUtils::getCylinderIntersections(surf, centre2,
axis2, cyl_rad,
epsge, bd_sf);
// Remove intersections not connected with the initial point
// Remove also segments going through an adjacent vertex
Point dummy;
checkTrimSeg(trim_segments, next_vxs, vx_point, dummy, tol3 /*epsge*/);
}
else if (min_idx >= 0)
{
// Check opening angles of candidate new surfaces
bool OK = checkCandVx(face, vx, cand_vx[min_idx], bend);
if (!OK)
{
cand_vx.erase(cand_vx.begin()+min_idx);
min_idx = -1;
}
}
if (trim_segments.size() == 0 && min_idx >= 0)
{
// Check the feasability of a stright curve in the
// parameter domain
Point pos2 = cand_vx[min_idx]->getVertexPoint();
Point parval2 = cand_vx[min_idx]->getFacePar(face.get());
adjustVertexPosition(surf, pos2, parval2, tol3);
shared_ptr<ParamCurve> pcurve = checkStrightParCv(face, vx, cand_vx[min_idx],
epsge, bend);
if (pcurve.get())
{
trim_segments = BoundedUtils::getTrimCrvsPcrv(surf, pcurve, epsge,
bd_sf);
}
else
{
// Find division curve between vertices
trim_segments = BoundedUtils::getTrimCrvsParam(surf, vx_par,
parval2, epsge,
bd_sf);
}
// Check output
checkTrimSeg2(trim_segments, vx_par, parval2, tol3 /*epsge*/);
// Remove intersections not connected with the initial point
// Remove also segments going through an adjacent vertex
if (trim_segments.size() > 0)
{
//Point other_pt = cand_vx[min_idx]->getVertexPoint();
checkTrimSeg(trim_segments, next_vxs, vx_point,
pos2, tol3 /*epsge*/);
}
}
if (trim_segments.size() == 0 && min_idx >= 0)
{
// The choosen vertex did not work. Remove it from the pool and try again
cand_vx.erase(cand_vx.begin()+min_idx);
}
else
break;
}
}
// if (false /*trim_segments.size() == 0 && cand_edge*/)
// {
// // Let the division curve end at a point of the given edge
// double tmid = 0.5*(cand_edge->tMin() + cand_edge->tMax());
// double clo_par, clo_dist;
// Point clo_pt;
// Point parval2;
// cand_edge->closestPoint(pnt, clo_par, clo_pt, clo_dist, &tmid);
// double p_len = cand_edge->tMax() - cand_edge->tMin();
// double lenfac = 0.1;
// if (clo_par - cand_edge->tMin() < lenfac*p_len ||
// cand_edge->tMax() - clo_par < lenfac*p_len)
// parval2 = cand_edge->faceParameter(tmid);
// else
// {
// Point face_seed = cand_edge->faceParameter(tmid);
// parval2 = cand_edge->faceParameter(clo_par, face_seed.begin());
// }
// trim_segments = BoundedUtils::getTrimCrvsParam(surf, vx_par,
// parval2, epsge,
// bd_sf);
// // Check output
// Point par1, par2;
// for (kr=0; kr<trim_segments.size(); ++kr)
// {
// par1 =
// trim_segments[kr]->parameterCurve()->point(trim_segments[kr]->startparam());
// par2 =
// trim_segments[kr]->parameterCurve()->point(trim_segments[kr]->endparam());
// if (par1.dist(parval2) < epsge || par2.dist(parval2) < epsge)
// break;
// }
// if (kr == trim_segments.size() ||
// (trim_segments.size()>1 &&
// par1.dist(vx_par)>epsge && par2.dist(vx_par)>epsge))
// trim_segments.clear();
// }
// if (trim_segments.size() == 0 && min_frac < fac*max_frac &&
// edge_par.dimension() == 2)
// {
// // Let the division curve end at an edge closest point
// trim_segments = BoundedUtils::getTrimCrvsParam(surf, vx_par,
// edge_par, epsge,
// bd_sf);
// // Check output
// Point par1, par2;
// for (kr=0; kr<trim_segments.size(); ++kr)
// {
// par1 =
// trim_segments[kr]->parameterCurve()->point(trim_segments[kr]->startparam());
// par2 =
// trim_segments[kr]->parameterCurve()->point(trim_segments[kr]->endparam());
// if (par1.dist(edge_par) < epsge || par2.dist(edge_par) < epsge)
// break;
// }
// if (kr == trim_segments.size() ||
// (trim_segments.size()>1 &&
// par1.dist(vx_par)>epsge && par2.dist(vx_par)>epsge))
// trim_segments.clear();
// }
if (trim_segments.size() == 0)
{
// Check if a constant parameter curve is a feasible
// split curve. First evaluate constant parameter tangents
vector<Point> pts(3);
surf->point(pts, vx_par[0], vx_par[1], 1);
double ang1 = pts[1].angle(normal);
double ang2 = pts[2].angle(normal);
ang1 = fabs(0.5*M_PI - ang1);
ang2 = fabs(0.5*M_PI - ang2);
double d1 = 0.0, d2 = 0.0;
double dfac = 0.05;
double frac = 1.0;
if (close_idx >= 0)
{
d1 = fabs(vx_par[1] - close_par[1]);
d2 = fabs(vx_par[0] - close_par[0]);
frac = (dom.umax()-dom.umin())/(dom.vmax()-dom.vmin());
}
if (((ang1 < 0.25*ang2 && close_idx < 0) ||
(close_idx>=0 && (d1 < std::max(frac*dfac*d2,0.01*d2)
|| d1 < epsge || ang1 < 0.1*ang2)))
&& ang1 < level_ang/*std::min(level_ang, 0.75*ang2)*/)
{
Point parval1(2), parval2(2);
parval1[1] = parval2[1] = vx_par[1];
parval1[0] = dom.umin();
parval2[0] = dom.umax();
trim_segments = BoundedUtils::getTrimCrvsParam(surf, parval1,
parval2, epsge,
bd_sf);
// Adjust curves ending very close to a non-significant vertex
adjustTrimSeg(trim_segments, NULL, NULL, face, bd_sf, non_corner,
tol3, epsge);
// Remove intersections not connected with the initial point
// Remove also segments going through an adjacent vertex
Point dummy;
vector<shared_ptr<Vertex> > adj_vxs;
adj_vxs.insert(adj_vxs.end(), next_vxs.begin(), next_vxs.end());
if (close_idx >= 0 && cand_edge)
{
adj_vxs.push_back(cand_edge->getVertex(true));
adj_vxs.push_back(cand_edge->getVertex(false));
}
checkTrimSeg(trim_segments, adj_vxs, vx_point, dummy, tol3 /*epsge*/);
// Check configuration to avoid 3-sided surfaces
checkTrimConfig(face, trim_segments, vx, corners, tol3 /*epsge*/);
}
if (trim_segments.size() == 0 &&
((ang2 < 0.25*ang1 && close_idx < 0) ||
(close_idx>=0 && (d2 < std::max(dfac*d1/frac, 0.01*d1) ||
d2 < epsge || ang2 < 0.1*ang1)))
&& ang2 < level_ang /*std::min(level_ang, 0.75*ang1)*/)
{
Point parval1(2), parval2(2);
parval1[0] = parval2[0] = vx_par[0];
parval1[1] = dom.vmin();
parval2[1] = dom.vmax();
trim_segments = BoundedUtils::getTrimCrvsParam(surf, parval1,
parval2, epsge,
bd_sf);
// Adjust curves ending very close to a non-significant vertex
adjustTrimSeg(trim_segments, NULL, NULL, face, bd_sf, non_corner,
tol3, epsge);
// Remove intersections not connected with the initial point
// Remove also segments going through an adjacent vertex
Point dummy;
vector<shared_ptr<Vertex> > adj_vxs;
adj_vxs.insert(adj_vxs.end(), next_vxs.begin(), next_vxs.end());
if (close_idx >= 0 && cand_edge)
{
adj_vxs.push_back(cand_edge->getVertex(true));
adj_vxs.push_back(cand_edge->getVertex(false));
}
checkTrimSeg(trim_segments, adj_vxs, vx_point, dummy, tol3 /*epsge*/);
// Check configuration to avoid 3-sided surfaces
checkTrimConfig(face, trim_segments, vx, corners, tol3 /*epsge*/);
}
}
if (opposite && trim_segments.size() == 0)
{
// Split to opposite edge. First fetch face parameter
// Make sure to split in the inner of the edge
double ta = opposite->tMin();
double tb = opposite->tMax();
if (cand_edge)
{
opposite_par = std::max(opposite_par, ta+0.2*(tb-ta));
opposite_par = std::min(opposite_par, tb-0.2*(tb-ta));
}
Point face_par = opposite->faceParameter(opposite_par);
opposite_point = opposite->point(opposite_par);
trim_segments = BoundedUtils::getTrimCrvsParam(surf, vx_par,
face_par, epsge,
bd_sf);
// Adjust curves ending very close to a non-significant vertex
adjustTrimSeg(trim_segments, &vx_par, &face_par, face, bd_sf, non_corner,
tol3, epsge);
// Remove intersections not connected with the initial point
// Remove also segments going through an adjacent vertex
checkTrimSeg(trim_segments, next_vxs, vx_point,
opposite_point, tol3 /*epsge*/);
}
if (trim_segments.size() == 0 && close_pt.dimension() > 0)
{
// Connect to closest point
// Check the feasability of a stright curve in the
// parameter domain
adjustVertexPosition(surf, close_pt, close_par, tol3);
shared_ptr<ParamCurve> pcurve = checkStrightParCv(face, vx,
close_pt,
epsge, bend);
if (pcurve.get())
{
trim_segments = BoundedUtils::getTrimCrvsPcrv(surf, pcurve, epsge,
bd_sf);
}
else
{
trim_segments = BoundedUtils::getTrimCrvsParam(surf, vx_par,
close_par, epsge,
bd_sf);
}
#ifdef DEBUG_REG
std::ofstream ofcv("trim_seg0.g2");
for (size_t kj=0; kj<trim_segments.size(); ++kj)
{
shared_ptr<ParamCurve> cv = trim_segments[kj]->spaceCurve();
cv->writeStandardHeader(ofcv);
cv->write(ofcv);
}
#endif
// Adjust curves ending very close to a non-significant vertex
adjustTrimSeg(trim_segments, &vx_par, &close_par, face, bd_sf, non_corner,
tol3, epsge);
// Remove intersections not connected with the initial point
// Remove also segments going through an adjacent vertex
checkTrimSeg(trim_segments, next_vxs, vx_point, close_pt, tol3 /*epsge*/);
}
if (trim_segments.size() == 0)
{
// Find intersections between the face and this plane
trim_segments = BoundedUtils::getPlaneIntersections(surf, vx_point,
normal, epsge,
bd_sf);
// Adjust curves ending very close to a non-significant vertex
adjustTrimSeg(trim_segments, NULL, NULL, face, bd_sf, non_corner,
tol3, epsge);
// Remove intersections not connected with the initial point
// Remove also segments going through an adjacent vertex
Point dummy;
checkTrimSeg(trim_segments, next_vxs, vx_point, dummy, tol3 /*epsge*/);
}
if (trim_segments.size() == 0)
{
// No split.
return trim_segments;
}
#ifdef DEBUG_REG
std::ofstream out_file("split_segments.g2");
for (size_t kj=0; kj<trim_segments.size(); ++kj)
{
shared_ptr<ParamCurve> cv = trim_segments[kj]->spaceCurve();
cv->writeStandardHeader(out_file);
cv->write(out_file);
}
#endif
return trim_segments;
}
//==========================================================================
vector<shared_ptr<ftSurface> >
RegularizeUtils::createFaces(vector<shared_ptr<BoundedSurface> >& sub_sfs,
shared_ptr<ftSurface> face,
double epsge, double tol2, double angtol,
vector<shared_ptr<Vertex> > non_corner)
//==========================================================================
{
// Sort surfaces according to the number of loops
for (size_t ki=0; ki<sub_sfs.size(); ++ki)
{
int nmb1 = sub_sfs[ki]->numberOfLoops();
for (size_t kj=ki+1; kj<sub_sfs.size(); ++kj)
{
int nmb2 = sub_sfs[kj]->numberOfLoops();
if (nmb2 > nmb1)
{
std::swap(sub_sfs[ki], sub_sfs[kj]);
std::swap(nmb1, nmb2);
}
}
}
// Create faces
vector<shared_ptr<ftSurface> > faces;
faces.reserve(sub_sfs.size());
for (size_t kj=0; kj<sub_sfs.size(); ++kj)
{
shared_ptr<ftSurface> curr =
shared_ptr<ftSurface>(new ftSurface(sub_sfs[kj], -1));
curr->setBody(face->getBody());
//(void)curr->createInitialEdges(epsge, angtol/*, true*/);
(void)curr->createInitialEdges(tol2, angtol/*, true*/);
// Transfer boundary conditions
if (face->hasBoundaryConditions())
{
int bd_type, bd;
face->getBoundaryConditions(bd_type, bd);
curr->setBoundaryConditions(bd_type, bd);
}
// Check if any non-corner vertices belongs to the new face
double frac = 0.001;
vector<shared_ptr<ftEdge> > edges = curr->getAllEdges();
for (size_t kr=0; kr<non_corner.size(); kr++)
{
Point vx_pt = non_corner[kr]->getVertexPoint();
for (size_t kh=0; kh<edges.size(); ++kh)
{
shared_ptr<Vertex> v1 = edges[kh]->getVertex(true);
shared_ptr<Vertex> v2 = edges[kh]->getVertex(false);
if (vx_pt.dist(v1->getVertexPoint()) < epsge ||
vx_pt.dist(v2->getVertexPoint()) < epsge)
continue; // Non-corner vertex not transferred
double t1 = edges[kh]->tMin();
double t2 = edges[kh]->tMax();
double par, dist;
Point close;
edges[kh]->closestPoint(vx_pt, par, close, dist);
double len1 =
edges[kh]->estimatedCurveLength(edges[kh]->tMin(), par);
double len2 =
edges[kh]->estimatedCurveLength(par, edges[kh]->tMax());
if (dist < tol2 &&
(par-t1 > frac*(t2-t1) && t2-par > frac*(t2-t1)) &&
len1 > epsge && len2 > epsge)
{
shared_ptr<ftEdgeBase> new_edge = edges[kh]->split2(par);
shared_ptr<ftEdge> curr_edge =
dynamic_pointer_cast<ftEdge,ftEdgeBase>(new_edge);
if (curr_edge.get())
{
shared_ptr<Vertex> vx = curr_edge->getVertex(true);
// if (vx.get())
// vx->joinVertex(non_corner[kr]);
edges.push_back(curr_edge);
}
//curr->updateBoundaryLoops(new_edge);
break;
}
}
}
faces.push_back(curr);
}
return faces;
}
//==========================================================================
void RegularizeUtils::getDivisionPlane(shared_ptr<ftSurface> face,
shared_ptr<Vertex> vx,
double epsge,
Point& pnt,
Point& normal)
//==========================================================================
{
// Get parameter corresponding to the vertex in the given face
Point param = vx->getFacePar(face.get());
// Get the edges corresponding to this face meeting in the vertex
vector<ftEdge*> edges = vx->getFaceEdges(face.get());
// Theoretically a face can have an equal number of edges meeting in
// a given vertex. Assume two, and use the two first edges
if (edges.size() < 2)
THROW("getDivisionPlane: edges.size() < 2");
// Define plane
pnt = face->point(param[0], param[1]);
Point norm = face->normal(param[0], param[1]);
norm.normalize();
double t1 = edges[0]->parAtVertex(vx.get());
double t2 = edges[1]->parAtVertex(vx.get());
Point tan1 = edges[0]->tangent(t1);
Point tan2 = edges[1]->tangent(t2);
tan1.normalize();
tan2.normalize();
Point vec = 0.5*(tan1 + tan2);
if (vec.length() < epsge)
vec = tan1;
// Project the vector into the tangent plane of the face
// normal = vec - (vec*norm)*norm;
// if (normal.length() < epsge)
// normal = vec%norm;
normal = vec;
normal.normalize();
}
//==========================================================================
void
RegularizeUtils::getClosestBoundaryPar(shared_ptr<ftSurface> face,
shared_ptr<Vertex> vx,
vector<shared_ptr<ParamCurve> >& vx_cvs,
const Point& pnt, const Point& in_vec,
double epsge, double angtol,
int& close_idx, double& close_dist,
Point& close_par, int loop_idx)
//==========================================================================
{
close_idx = -1;
close_dist = 1.0e8;
// Fetch information about boundary curves
size_t kr, kh;
vector<shared_ptr<ftEdge> > all_edg = (loop_idx < 0) ?
face->getAllEdges() : face->getAllEdges(loop_idx);
vector<shared_ptr<ParamCurve> > cvs;
vector<Point> adj_pnt; // Vertex points adjacent to the split vertex.
// Can not serve as vertices to connect to and is thus not feasible as
// a closest point to compare with
for (kr=0; kr<all_edg.size(); ++kr)
{
shared_ptr<Vertex> next_vx = all_edg[kr]->getOtherVertex(vx.get());
if (next_vx.get())
{
shared_ptr<Vertex> next_vx2;
if (!next_vx->isCornerInFace(face.get(), angtol))
{
if (next_vx->nmbUniqueEdges() == 2)
{
// Bypass this vertex
vector<ftEdge*> edgs = next_vx->getFaceEdges(face.get());
ftEdge* curr_edg = (edgs[0] == all_edg[kr].get()) ?
edgs[1] : edgs[0];
next_vx2 = curr_edg->getOtherVertex(next_vx.get());
}
}
adj_pnt.push_back(next_vx2.get() ? next_vx2->getVertexPoint() :
next_vx->getVertexPoint());
}
shared_ptr<ParamCurve> tmp = all_edg[kr]->geomCurve();
for (kh=0; kh<cvs.size(); ++kh)
if (cvs[kh].get() == tmp.get())
break;
if (kh == cvs.size())
cvs.push_back(tmp);
}
// Make a copy
vector<shared_ptr<ParamCurve> > cvs2(cvs.begin(), cvs.end());
int idx1 = -1, idx2 = -1;
for (kr=0; kr<cvs.size(); ++kr)
{
for (kh=0; kh<vx_cvs.size(); ++kh)
if (vx_cvs[kh].get() == cvs[kr].get())
{
if (idx1 < 0)
idx1 = (int)kr;
else
idx2 = (int)kr;
}
}
if (idx2 < 0)
{
if (idx1 == 0)
{
cvs.erase(cvs.begin(),
cvs.begin()+std::min((int)(cvs.size()),2));
if (cvs.size() > 0)
cvs.erase(cvs.end()-1);
}
else if (idx1 >= (int)cvs.size()-1)
{
cvs.erase(cvs.begin()+idx1-1, cvs.begin()+idx1+1);
if (cvs.size() > 0)
cvs.erase(cvs.begin());
}
else
cvs.erase(cvs.begin()+idx1-1, cvs.begin()+idx1+2);
}
else
{
cvs.erase(cvs.begin()+idx2);
cvs.erase(cvs.begin()+idx1);
}
Point close_pnt;
double close_t;
double close_ang = 2*M_PI;
double close_frac = 0.0;
double fac = 2.0;
shared_ptr<ParamSurface> surf = face->surface();
if (cvs.size() == 0)
cvs.insert(cvs.begin(), cvs2.begin(), cvs2.end());
for (kr=0; kr<cvs.size(); ++kr)
{
double dist, upar, vpar;
Point close_pnt2;
double t1 = cvs[kr]->startparam();
double t2 = cvs[kr]->endparam();
cvs[kr]->closestPoint(pnt, t1, t2, close_t, close_pnt, dist);
// Check feasability of closest point
for (kh=0; kh<adj_pnt.size(); ++kh)
if (adj_pnt[kh].dist(close_pnt) < epsge)
break;
if (kh < adj_pnt.size())
continue;
Point vec = close_pnt - pnt;
double in_ang = vec.angle(in_vec);
double frac = std::min(close_t-t1, t2-close_t)/(t2 - t1);
if ((dist < close_dist && in_ang < fac*close_ang ||
fac*in_ang < close_ang && dist < fac*close_dist))
{
close_dist = dist;
close_idx = (int)kr;
close_ang = in_ang;
close_frac = frac;
surf->closestPoint(close_pnt, upar, vpar, close_pnt2, dist,
epsge);
close_par = Point(upar,vpar);
}
}
if (close_idx < 0)
{
if (cvs2.size() == 0)
return;
#ifdef DEBUG_REG
std::cout << "RegularizeUtils: Arbitrary closest boundary point" << std::endl;
#endif
// No closest point selected. Choose a point
close_idx = (int)cvs2.size()/2;
close_t = 0.5*(cvs2[close_idx]->startparam() +
cvs2[close_idx]->endparam());
close_pnt = cvs2[close_idx]->point(close_t);
double upar, vpar, dist;
Point close_pnt2;
surf->closestPoint(close_pnt, upar, vpar, close_pnt2, dist,
epsge);
close_par = Point(upar,vpar);
}
// Let the index reflect the face edges
for (kr=0; kr<all_edg.size(); ++kr)
{
if (all_edg[kr]->geomCurve().get() == cvs[close_idx].get())
{
close_idx = (int)kr;
break;
}
}
}
//==========================================================================
ftEdge*
RegularizeUtils::getClosestOpposite(ftSurface* face, ftEdgeBase* edge,
Point pnt, Point& close, double& par,
double& dist)
//==========================================================================
{
// Fetch candidate edges
vector<shared_ptr<ftEdge> > all_edges = face->getAllEdges();
// Remove input edge and the adjacent edges
for (size_t ki=0; ki<all_edges.size(); )
{
if (all_edges[ki].get() == edge ||
all_edges[ki].get() == edge->next() ||
all_edges[ki].get() == edge->prev())
all_edges.erase(all_edges.begin()+ki);
else
++ki;
}
// Perform closest point computation
ftEdge *result = NULL;
dist = std::numeric_limits<double>::max();
for (size_t ki=0; ki<all_edges.size(); ++ki)
{
double local_par, local_dist;
Point local_close;
all_edges[ki]->closestPoint(pnt, local_par, local_close, local_dist);
if (local_dist < dist)
{
dist = local_dist;
par = local_par;
close = local_close;
result = all_edges[ki].get();
}
}
return result;
}
//==========================================================================
bool
RegularizeUtils::checkPath(shared_ptr<Vertex> vx1, shared_ptr<Vertex> vx2,
shared_ptr<Vertex> vx, shared_ptr<ftSurface> face,
double angtol)
//==========================================================================
{
// Find the path between vx1 and vx
ftEdge *edg = vx1->getCommonEdge(vx2.get());
vector<ftEdge*> path;
bool found = getPath(edg, vx2, vx, face, path);
if (!found)
return true; //false; // Should be a path, if not it is probably not a good split
// Fetch corners
vector<shared_ptr<Vertex> > vx_corners;
size_t kj;
vx_corners.push_back(vx);
for (kj=path.size()-1; kj>0; --kj)
{
shared_ptr<Vertex> common_vx =
path[kj-1]->getCommonVertex(path[kj]);
double t1 = path[kj-1]->parAtVertex(common_vx.get());
double t2 = path[kj]->parAtVertex(common_vx.get());
Point tan1 = path[kj-1]->tangent(t1);
Point tan2 = path[kj]->tangent(t2);
double ang = tan1.angle(tan2);
if (ang > angtol)
vx_corners.push_back(common_vx);
}
vx_corners.push_back(vx1);
if (vx_corners.size() > 4)
return true; // Does not lead to a regular face, not necessary to
// test quality
/*bool OK =*/ checkRegularity(vx_corners, face, false);
//return OK;
return true;
}
//==========================================================================
bool
RegularizeUtils::cornerInShortestPath(shared_ptr<Vertex> vx1,
shared_ptr<Vertex> vx2,
shared_ptr<ftSurface> face,
double angtol)
//==========================================================================
{
// Find shortest path
vector<ftEdge*> edg1 = vx1->getFaceEdges(face.get());
vector<ftEdge*> shortest_path;
int min_nmb_corners = 200; // A large and unlikely number
size_t ki, kj;
for (ki=0; ki<edg1.size(); ++ki)
{
shared_ptr<Vertex> other_vx = edg1[ki]->getOtherVertex(vx1.get());
vector<ftEdge*> path;
bool found = getPath(edg1[ki], other_vx, vx2, face, path);
if (found)
{
// Count corners
int nmb_corners = 0;
for (kj=1; kj<path.size(); ++kj)
{
shared_ptr<Vertex> common_vx =
path[kj-1]->getCommonVertex(path[kj]);
double t1 = path[kj-1]->parAtVertex(common_vx.get());
double t2 = path[kj]->parAtVertex(common_vx.get());
Point tan1 = path[kj-1]->tangent(t1);
Point tan2 = path[kj]->tangent(t2);
double ang = tan1.angle(tan2);
if (ang > angtol)
nmb_corners++;
}
if (ki == 0 || nmb_corners < min_nmb_corners)
min_nmb_corners = nmb_corners;
}
}
if (min_nmb_corners >= 2)
return true;
else
return false;
}
//==========================================================================
bool
RegularizeUtils::getPath(ftEdge* edg, shared_ptr<Vertex> vx,
shared_ptr<Vertex> last, shared_ptr<ftSurface> face,
vector<ftEdge*>& path)
//==========================================================================
{
path.push_back(edg);
if (vx.get() == last.get())
return true;
vector<ftEdge*> edges = vx->getFaceEdges(face.get());
vector<ftEdge*> shortest_path;
for (size_t ki=0; ki<edges.size(); ++ki)
{
if (edges[ki] == edg)
continue;
size_t kj;
for (kj=0; kj<path.size(); ++kj)
if (path[kj] == edges[ki])
break;
if (kj < path.size())
continue;
shared_ptr<Vertex> other = edges[ki]->getOtherVertex(vx.get());
vector<ftEdge*> curr_path = path;
bool found = getPath(edges[ki], other, last, face, curr_path);
if (found && (shortest_path.size() == 0 || curr_path.size() < shortest_path.size()))
shortest_path = curr_path;
}
if (shortest_path.size() > 0)
{
path = shortest_path;
return true;
}
else
return false;
}
//==========================================================================
int
RegularizeUtils::noExtension(shared_ptr<Vertex> vx, ftSurface* face,
shared_ptr<Vertex>& vx2, pair<Point, Point>& co_par1,
pair<Point, Point>& co_par2, int& dir1, int& dir2,
double& val1, double& val2, double angtol,
bool check_constant_curve)
//==========================================================================
{
double ptol = 1.0e-8;
size_t ki, kj, kr;
int idx = -1;
shared_ptr<Vertex> last_vx;
// Fetch faces and remove faces from other bodies
vector<ftSurface*> vx_faces = vx->faces();
Body *bd0 = face->getBody();
for (kj=0; kj<vx_faces.size();)
{
Body *bd1 = vx_faces[kj]->getBody();
if (/*bd0 != NULL && bd1 != NULL &&*/ bd1 != bd0)
vx_faces.erase(vx_faces.begin()+kj);
else
{
// if (bd1 != NULL)
// bd0 = vx_faces[kj]->getBody();
kj++;
}
}
// Check number of faces
if (vx_faces.size() == 2)
return 1; // Not a significant vertex in this body
if (vx_faces.size() != 3)
return 0;
// Get edges
vector<ftEdge*> edges = vx->uniqueEdges();
// Look for an edge connecting two T-vertices where 3 edges meet
for (ki=0; ki<edges.size(); ++ki)
{
// Check the continuity between the faces meeting in the
// identified edge
if (!edges[ki]->twin())
continue;
if (!edges[ki]->hasConnectivityInfo())
continue; // No continuity info
shared_ptr<FaceConnectivity<ftEdgeBase> > info =
edges[ki]->getConnectivityInfo();
int status = info->WorstStatus();
if (status > 1)
continue; // Not G1 or almost G1
// Dismiss edges going along the initial face
if (edges[ki]->face() == face ||
edges[ki]->twin()->geomEdge()->face() == face)
continue;
// Check configuration
vx2 = edges[ki]->getOtherVertex(vx.get());
if (!vx2.get())
continue;
vector<ftSurface*> vx_faces2 = vx2->faces();
// Remove faces from other bodies
for (kj=0; kj<vx_faces2.size();)
{
if (vx_faces2[kj]->getBody() != bd0)
vx_faces2.erase(vx_faces2.begin()+kj);
else
kj++;
}
if (vx_faces2.size() < 3)
{
// Traverse along the edge until a T-joint is found
#ifdef DEBUG_REG
std::ofstream of("traverse_vx.g2");
of << "400 1 0 4 255 0 0 255" << std::endl;
of << "1" << std::endl;
of << vx->getVertexPoint() << std::endl;
of << "400 1 0 4 0 255 0 255" << std::endl;
of << "1" << std::endl;
of << vx2->getVertexPoint() << std::endl;
#endif
int status0 = traverseUntilTJoint(vx_faces, vx, vx2, vx_faces2);
if (status0 > 1)
continue; // Not a smooth transition
}
bool continued_merge = false;
if (vx_faces2.size() == 4)
{
// Check the continuation of this edge to see if there are
// several merge situations in a row
continued_merge = mergeSituationContinuation(face, vx, edges[ki],
angtol,
check_constant_curve);
}
if (vx_faces2.size() != 3 && !continued_merge)
continue;
// Remove the face(s) which are adjacent to the initial vertex
for (kj=0; kj<vx_faces2.size();)
{
for (kr=0; kr<vx_faces.size(); ++kr)
if (vx_faces[kr] == vx_faces2[kj])
break;
if (kr < vx_faces.size())
{
// vx_faces2.erase(vx_faces2.begin()+kj); Something wrong with this!!
std::swap(vx_faces2[kj], vx_faces2[vx_faces2.size()-1]);
vx_faces2.pop_back();
}
else
kj++;
}
if ( vx_faces2.size() == 0 || vx_faces2.size() > 2)
continue; // Not a legal configuration
// Fetch edges in this vertex
vector<ftEdge*> edges2 = vx2->uniqueEdges();
// Remove the edges that do not follow the remaining faces only once
for (kj=0; kj<edges2.size(); )
{
int nmb = 0;
for (kr=0; kr<vx_faces2.size(); ++kr)
{
if (edges2[kj]->face() == vx_faces2[kr] ||
(edges2[kj]->twin() &&
edges2[kj]->twin()->geomEdge()->face() == vx_faces2[kr]))
nmb++;
}
if (nmb == 1)
kj++;
else
edges2.erase(edges2.begin()+kj);
}
if (edges2.size() != 2)
continue;
// Check angle
double t1 = edges2[0]->parAtVertex(vx2.get());
double t2 = edges2[1]->parAtVertex(vx2.get());
Point tan1 = edges2[0]->tangent(t1);
Point tan2 = edges2[1]->tangent(t2);
double ang = tan1.angle(tan2);
ang = std::min(ang, fabs(M_PI-ang));
if (ang > angtol)
continue; // The faces meet in a corner
idx = ki;
last_vx = vx2;
}
if (idx < 0)
return 0;
vx2 = last_vx;
ftSurface *f1 = edges[idx]->face()->asFtSurface();
ftSurface *f2 = edges[idx]->twin()->geomEdge()->face()->asFtSurface();
Point par1_1 = vx->getFacePar(f1);
Point par1_2 = vx->getFacePar(f2);
Point par2_1 = vx2->getFacePar(f1);
Point par2_2 = vx2->getFacePar(f2);
co_par1 = make_pair(par1_1, par1_2);
co_par2 = make_pair(par2_1, par2_2);
// Update output
vx2 = edges[idx]->getOtherVertex(vx.get());
shared_ptr<ParamCurve> cv1 = edges[idx]->geomCurve();
shared_ptr<ParamCurve> cv2 = edges[idx]->twin()->geomEdge()->geomCurve();
shared_ptr<CurveOnSurface> sf_cv1 =
dynamic_pointer_cast<CurveOnSurface,ParamCurve>(cv1);
shared_ptr<CurveOnSurface> sf_cv2 =
dynamic_pointer_cast<CurveOnSurface,ParamCurve>(cv2);
// Point pt1 = cv1->point(edges[idx]->tMin());
// Point pt2 = cv2->point(edges[idx]->twin()->tMin());
// Point pt3 = cv2->point(edges[idx]->twin()->tMax());
// if (pt1.dist(pt2) < pt1.dist(pt3))
// {
// co_par1 = make_pair(sf_cv1->parameterCurve()->point(edges[idx]->tMin()),
// sf_cv2->parameterCurve()->point(edges[idx]->twin()->tMin()));
// co_par2 = make_pair(sf_cv1->parameterCurve()->point(edges[idx]->tMax()),
// sf_cv2->parameterCurve()->point(edges[idx]->twin()->tMax()));
// }
// else
// {
// co_par1 = make_pair(sf_cv1->parameterCurve()->point(edges[idx]->tMin()),
// sf_cv2->parameterCurve()->point(edges[idx]->twin()->tMax()));
// co_par2 = make_pair(sf_cv1->parameterCurve()->point(edges[idx]->tMax()),
// sf_cv2->parameterCurve()->point(edges[idx]->twin()->tMin()));
// }
if (check_constant_curve)
{
// Check if the boundary between the
// faces are constant parameter curves in both parameter directions
if (!sf_cv1.get() ||
!sf_cv1->isConstantCurve(ptol, dir1, val1))
return 1;
if (!sf_cv2.get() ||
!sf_cv2->isConstantCurve(ptol, dir2, val2))
return 1;
dir1--;
dir2--;
return 2; // A possible insignificant splitting curve is found
}
// if (false)
// {
// // Check if the next or previous edge follow the same constant boundary
// int dir;
// double val;
// shared_ptr<ParamCurve> tmp_crv = edges[idx]->next()->geomEdge()->geomCurve();
// shared_ptr<CurveOnSurface> sf_crv =
// dynamic_pointer_cast<CurveOnSurface,ParamCurve>(tmp_crv);
// if (sf_crv.get())
// sf_crv->isConstantCurve(ptol, dir, val);
// else
// dir = -1;
// if (dir == dir1)
// continue;
// tmp_crv = edges[idx]->prev()->geomEdge()->geomCurve();
// sf_crv = dynamic_pointer_cast<CurveOnSurface,ParamCurve>(tmp_crv);
// if (sf_crv.get())
// sf_crv->isConstantCurve(ptol, dir, val);
// else
// dir = -1;
// if (dir == dir1)
// continue;
// tmp_crv = edges[idx]->twin()->next()->geomEdge()->geomCurve();
// sf_crv = dynamic_pointer_cast<CurveOnSurface,ParamCurve>(tmp_crv);
// if (sf_crv.get())
// sf_crv->isConstantCurve(ptol, dir, val);
// else
// dir = -1;
// if (dir == dir2)
// continue;
// tmp_crv = edges[idx]->twin()->prev()->geomEdge()->geomCurve();
// sf_crv = dynamic_pointer_cast<CurveOnSurface,ParamCurve>(tmp_crv);
// if (sf_crv.get())
// sf_crv->isConstantCurve(ptol, dir, val);
// else
// dir = -1;
// if (dir == dir2)
// continue;
// }
return 1;
}
//==========================================================================
bool
RegularizeUtils::mergeSituationContinuation(ftSurface* init_face, shared_ptr<Vertex> vx,
ftEdge* edge, double angtol,
bool check_constant_curve)
//==========================================================================
{
ftSurface *face1, *face2;
// Fetch faces adjacent to edge
face1 = edge->face()->asFtSurface();
if (!edge->twin())
return false;
face2 = edge->twin()->geomEdge()->face()->asFtSurface();
shared_ptr<Vertex> vx1 = vx;
ftEdge* edge1 = edge;
size_t ki;
while (true)
{
// Check continuity
if (!edge1->hasConnectivityInfo())
return false; // No continuity info
shared_ptr<FaceConnectivity<ftEdgeBase> > info =
edge1->getConnectivityInfo();
int status = info->WorstStatus();
if (status > 1)
return false; // Not G1 or almost G1
// Fetch next vertex
shared_ptr<Vertex> vx2 = edge1->getOtherVertex(vx1.get());
// Fetch faces surrounding the vertex
vector<ftSurface*> vx_faces2 = vx2->faces();
// Get edges
vector<ftEdge*> edges = vx2->uniqueEdges();
if (vx_faces2.size() == 3 ||
(vx_faces2.size() >= 3 && check_constant_curve))
{
// Check continuity at end of edge sequence
// Remove the edges that do not follow the recent faces only once
for (ki=0; ki<edges.size(); )
{
int nmb = 0;
if (edges[ki]->face() == face1 ||
(edges[ki]->twin() &&
edges[ki]->twin()->geomEdge()->face() == face1))
nmb++;
if (edges[ki]->face() == face2 ||
(edges[ki]->twin() &&
edges[ki]->twin()->geomEdge()->face() == face2))
nmb++;
if (nmb == 1)
ki++;
else
edges.erase(edges.begin()+ki);
}
if (edges.size() != 2)
return false;
// Check angle
double t1 = edges[0]->parAtVertex(vx2.get());
double t2 = edges[1]->parAtVertex(vx2.get());
Point tan1 = edges[0]->tangent(t1);
Point tan2 = edges[1]->tangent(t2);
double ang = tan1.angle(tan2);
ang = std::min(ang, fabs(M_PI-ang));
if (ang > angtol)
return false; // The faces meet in a corner
// Check if the initial face is found
int kj;
for (kj=0; kj<vx_faces2.size(); ++kj)
if (vx_faces2[kj] == init_face)
return false;
if (vx_faces2.size() == 3)
return true; // The end of the edge sequence is found
}
// Remove edges that cannot be a part of a continuation
if (vx_faces2.size() == 2)
{
for (ki=0; ki<edges.size(); )
{
if (edges[ki] == edge1 || edges[ki]->twin() == edge1)
edges.erase(edges.begin()+ki);
else
ki++;
}
}
else
{
for (ki=0; ki<edges.size(); )
{
if (edges[ki]->face() == face1 || edges[ki]->face() == face2 ||
(!edges[ki]->twin()))
edges.erase(edges.begin()+ki);
else
{
ftFaceBase *tmp_face = edges[ki]->twin()->geomEdge()->face();
if (tmp_face == face1 || tmp_face == face2)
edges.erase(edges.begin()+ki);
else
ki++;
}
}
}
if (edges.size() != 1)
return false;
edge1 = edges[0];
if (edge1 == edge)
return false; // A loop is found
// Fetch faces adjacent to edge
face1 = edge1->face()->asFtSurface();
if (!edge1->twin())
return false;
face2 = edge1->twin()->geomEdge()->face()->asFtSurface();
vx1 = vx2;
}
return true; // Should not get here
}
//==========================================================================
double
RegularizeUtils::getMaxParFrac(shared_ptr<ftSurface> face)
//==========================================================================
{
// Fetch all edges
vector<shared_ptr<ftEdge> > edges = face->getAllEdges();
double maxparfrac = 0.0;
double accpar1=0.0, accpar2=0.0;
for (size_t ki=0; ki<edges.size(); ++ki)
{
Point par1 = edges[ki]->faceParameter(edges[ki]->tMin());
Point par2 = edges[ki]->faceParameter(edges[ki]->tMax());
accpar1 += (fabs(par1[0]-par2[0]));
accpar2 += (fabs(par1[1]-par2[1]));
// double parfrac = std::min(fabs(par1[0]-par2[0]),fabs(par1[1]-par2[1]))/
// std::max(fabs(par1[0]-par2[0]),fabs(par1[1]-par2[1]));
// maxparfrac = std::max(maxparfrac, parfrac);
}
maxparfrac = std::min(accpar1, accpar2)/std::max(accpar1, accpar2);
return maxparfrac;
}
//==========================================================================
int
RegularizeUtils::selectCandVx(shared_ptr<ftSurface> face,
shared_ptr<Vertex> vx, const Point& in_vec,
vector<shared_ptr<Vertex> >& cand_vx,
RectDomain& dom,
double epsge, double angtol,
const Point& centre, const Point& normal,
vector<shared_ptr<ParamCurve> >& vx_cvs,
double close_dist, const Point& close_pt,
double& cyl_rad, int strong)
//==========================================================================
{
// Statistics
double parfrac = getMaxParFrac(face);
double level_frac = std::max(std::min(0.5, 100.0*parfrac), 0.1);
Point edge_par;
//double level_ang = M_PI/3; // M_PI/2.0; // M_PI/4.0; //M_PI/6.0;
double level_ang = (centre.dimension() > 0) ? M_PI/3 : M_PI/2.0;
double fac = 0.5; // 0.2;
double fac2 = 2.0;
double fac3 = 0.05;
double tol = 1.0e-4;
Point vx_point = vx->getVertexPoint();
Point vx_par = vx->getFacePar(face.get());
Point close_vec = close_pt - vx_point;
Point curr_vx_par, curr_vx_par1;
Point min_deriv;
int min_idx = -1;
double min_frac = MAXDOUBLE;
double max_frac = 0.0;
double min_ang = 1.0e8;
double min_close_ang = 1.0e8;
double min_dist = MAXDOUBLE;
double curr_rad_dist = MAXDOUBLE;
double min_close_dist = MAXDOUBLE;
double d1=-1.0, d2=-1.0;
bool prev_tri = false;
if (centre.dimension() > 0)
d1 = vx_point.dist(centre);
// Fetch adjacent vertices
vector<shared_ptr<Vertex> > next_vxs = vx->getNextVertex(face.get());
// Tangent info
shared_ptr<ParamSurface> surf = face->surface();
DirectionCone cone1 = surf->tangentCone(true);
DirectionCone cone2 = surf->tangentCone(false);
// Traverse all candidate vertices and check if any is feasible for
// division
// Compute distance between vertices and found plane
// Select vertex with minimum distance
for (int ki=0; ki<(int)cand_vx.size(); ++ki)
{
size_t kr, kh;
int tri = false;
Point curr_vx_par2 = cand_vx[ki]->getFacePar(face.get());
if (curr_vx_par2.dimension() != 2)
continue; // Not a candidate
vector<Point> der(3);
surf->point(der, curr_vx_par2[0], curr_vx_par2[1], 1);
Point cand_vx_pt = cand_vx[ki]->getVertexPoint();
Point vec = cand_vx_pt - vx_point;
double dist = vec.length();
if (dist > epsge)
vec.normalize();
double dist1 = fabs(vx_par[0]-curr_vx_par2[0]);
double dist2 = fabs(vx_par[1]-curr_vx_par2[1]);
dist1 /= (dom.umax() - dom.umin());
dist2 /= (dom.vmax() - dom.vmin());
double frac = std::min(dist1, dist2);
double ang = vec.angle(normal);
ang = fabs(0.5*M_PI - ang);
double close_dist = close_pt.dist(cand_vx_pt);
double rad_dist;
min_close_ang = std::min(min_close_ang, close_vec.angle(vec));
if (centre.dimension() > 0)
{
d2 = cand_vx[ki]->getVertexPoint().dist(centre);
rad_dist = fabs(d1 - d2);
}
else
rad_dist = MAXDOUBLE;
// Skip vertices lying in the wrong direction compared to the material
// of the surface
if (vec*in_vec < -fac2*angtol /*-tol*/)
{
if (strong && cand_vx.size() == 1) // Restrictive start
{
bool modified = updateVertexPos(face, vx, cand_vx[ki],
epsge, 10.0*epsge, angtol);
if (!modified)
continue;
}
else
continue; // The tolerances is arbitrary here, but do not want
}
// to rule out orthogonal cases when the face is curved. The
// test should be made more precise by taking the shape of the
// face into consideration
// Check if the vertex is associated the same underlying curve
// as the initial vertex. In that case, it is not a candidate
// for split
vector<ftEdge*> vx_edg2 = cand_vx[ki]->getFaceEdges(face.get());
for (kr=0; kr<vx_edg2.size(); ++kr)
{
shared_ptr<ParamCurve> cv = vx_edg2[kr]->geomCurve();
for (kh=0; kh<vx_cvs.size(); ++kh)
if (cv.get() == vx_cvs[kh].get())
break;
if (kh < vx_cvs.size())
break;
}
if (kr < vx_edg2.size())
{
curr_vx_par = curr_vx_par1 = curr_vx_par2;
continue; // Vertex not allowed for split
}
// Check for corners between the current and the candidate vertex
bool has_corner = cornerInShortestPath(vx, cand_vx[ki], face, angtol);
if (strong == 1 && (!has_corner))
tri = true;
else if (strong == 0 && (!has_corner))
continue;
// Avoid vertices which is inline with the neighbouring vertices
// to the split vertex
Point vec3 = cand_vx[ki]->getVertexPoint() - vx_point;
for (kr=0; kr<next_vxs.size(); ++kr)
{
Point vec4 = next_vxs[kr]->getVertexPoint() - vx_point;
double vx_ang = vec3.angle(vec4);
if (vx_ang < angtol)
break;
}
if (kr < next_vxs.size() && cyl_rad <= 0.0)
{
// This candidate vertex is not a good coice for splitting
continue;
}
// Check also other angles
vector<shared_ptr<Vertex> > next_vxs2 =
cand_vx[ki]->getNextVertex(face.get());
for (kr=0; kr<next_vxs2.size(); ++kr)
{
bool OK = checkPath(cand_vx[ki], next_vxs2[kr], vx,
face, angtol);
if (!OK)
break;
}
if (kr < next_vxs2.size() && cyl_rad <= 0.0)
{
// This candidate vertex is not a good coice for splitting
continue;
}
// Compute the angle between the vector from the split vertex to the
// previous choice of destination vertex and the corresponding vector
// for the current on in the parameter domain. If these vectors are almost
// parallel, the closest candidate will be choosen
Point vec1 = (curr_vx_par.dimension() == 0) ? Point(0.0, 0.0) : curr_vx_par - vx_par;
Point vec2 = curr_vx_par2 - vx_par;
double par_ang = vec1.angle(vec2);
double par_limit = 0.05*M_PI;
if (curr_rad_dist < epsge)
{
if (rad_dist < curr_rad_dist)
{
curr_rad_dist = rad_dist;
min_ang = ang;
min_dist = dist;
min_frac = frac;
min_idx = ki;
curr_vx_par = curr_vx_par2;
max_frac = std::max(dist1,dist2);
min_deriv = (dist1 > dist2) ? der[2] : der[1];
min_close_dist = close_dist;
prev_tri = tri;
}
}
else
{
/*if (cand_vx.size() > 1 && tri && (!prev_tri))
{
// Not a good candidate
}
else*/ if (((fabs(frac-min_frac) < tol && fabs(ang-min_ang) < tol &&
dist < min_dist) || (prev_tri && (!tri))) &&
!(ki>0 && tri && (!prev_tri)))
{
curr_rad_dist = rad_dist;
min_ang = ang;
min_dist = dist;
min_frac = frac;
min_idx = ki;
curr_vx_par = curr_vx_par2;
max_frac = std::max(dist1,dist2);
min_deriv = (dist1 > dist2) ? der[2] : der[1];
min_close_dist = close_dist;
prev_tri = tri;
}
else if (((frac < 0.9*min_frac && ang < level_ang &&
dist < fac2*min_dist && close_dist < fac2*min_close_dist) ||
dist < fac*min_dist) &&
!(ki>0 && tri && (!prev_tri)))
{
curr_rad_dist = rad_dist;
min_ang = ang;
min_dist = dist;
min_frac = frac;
min_idx = ki;
curr_vx_par = curr_vx_par2;
max_frac = std::max(dist1,dist2);
min_deriv = (dist1 > dist2) ? der[2] : der[1];
min_close_dist = close_dist;
prev_tri = tri;
}
else if (((par_ang < par_limit || close_dist < min_close_dist) &&
dist < min_dist) &&
!(ki>0 && tri && (!prev_tri)))
{
curr_rad_dist = rad_dist;
min_ang = ang;
min_dist = dist;
min_frac = frac;
min_idx = ki;
curr_vx_par = curr_vx_par2;
max_frac = std::max(dist1,dist2);
min_deriv = (dist1 > dist2) ? der[2] : der[1];
min_close_dist = close_dist;
prev_tri = tri;
}
}
// Check edge between vertices
ftEdge *curr_edge = NULL;
if (ki > 0)
cand_vx[ki-1]->getCommonEdgeInFace(cand_vx[ki].get(),
face.get());
if (curr_edge)
{
// Perform closest point to vertex
double seed = 0.5*(curr_edge->tMin() + curr_edge->tMax());
double clo_par, clo_dist;
Point clo_pt;
curr_edge->closestPoint(vx_point, clo_par, clo_pt, clo_dist, &seed);
Point face_seed = 0.5*(curr_vx_par1 + curr_vx_par2);
Point curr_e_par = curr_edge->faceParameter(clo_par,
face_seed.begin());
dist1 = fabs(vx_par[0]-curr_e_par[0]);
dist2 = fabs(vx_par[1]-curr_e_par[1]);
dist1 /= (dom.umax() - dom.umin());
dist2 /= (dom.vmax() - dom.vmin());
frac = std::min(dist1, dist2);
double mfac = 10.0;
if (frac < mfac*min_frac)
{
min_frac = frac;
min_idx = -1;
edge_par = curr_e_par;
}
max_frac = std::max(max_frac, std::max(dist1,dist2));
curr_vx_par = curr_vx_par1 = curr_vx_par2;
}
}
double ang = 0.0;
double ang2 = 0.0;
double ang3 = 0.0;
Point curr_vec;
if (min_idx >= 0)
{
curr_vec = cand_vx[min_idx]->getVertexPoint() - vx_point;
ang = curr_vec.angle(normal);
// Compute also the angle in the candidate end point of the split
Point pnt2, normal2;
getDivisionPlane(face, cand_vx[min_idx], epsge, pnt2, normal2);
ang2 = curr_vec.angle(normal2);
ang3 = normal.angle(normal2);
}
if (min_idx >= 0)
{
double deriv_ang1 = min_deriv.angle(normal);
deriv_ang1 = fabs(0.5*M_PI - deriv_ang1);
double deriv_ang2 = min_deriv.angle(close_vec);
double close_ang = close_vec.angle(curr_vec);
// if (min_deriv.angle(curr_vec) > level_frac*level_ang &&
// close_ang > 2.0*min_close_ang)
// min_frac = max_frac; // Not the same parameter direction
if (curr_rad_dist < epsge)
{
// A good candidate for a cylinder split
cyl_rad = d1;
}
else
{
double scp =
(vx_point - close_pt)*(vx_point - cand_vx[min_idx]->getVertexPoint());
double fac4 = (scp < 0.0) ? 0.5 : 1;
if (false
/*(fabs(ang - ang2) < epsge || fabs(M_PI-(ang+ang2)) < epsge) &&
(ang3 < epsge || fabs(M_PI-ang3) < epsge)*/)
{
if (!(vx->isCornerInFace(face.get(), angtol) &&
cand_vx[min_idx]->isCornerInFace(face.get(), angtol)))
level_frac *= 0.1;
}
if (strong)
{
// The candidate is selected already
;
}
else if ((!((fac4*fac*min_dist < close_dist ||
min_frac < fac3*max_frac) &&
(min_frac < level_frac*max_frac ||
fabs(0.5*M_PI - ang) < level_frac*level_ang))) /*||
(deriv_ang1 > level_frac*level_ang &&
deriv_ang2 > level_frac*level_ang &&
close_ang > 2.0*min_close_ang)*/)
{
// Not a good candidate. Remove it from the list if it is
// not a T-joint
if (cand_vx[min_idx]->isCornerInFace(face.get(), angtol))
{
cand_vx.erase(cand_vx.begin()+min_idx);
min_idx = -1;
}
}
else
{
int stop_break = 1;
stop_break *= 2;
}
}
}
return min_idx;
}
//==========================================================================
bool
RegularizeUtils::updateVertexPos(shared_ptr<ftSurface> face,
shared_ptr<Vertex> vx,
shared_ptr<Vertex>& cand_vx,
double epsge, double tol2, double angtol)
//==========================================================================
{
bool modified = false;
// Check if the vertex is a Tjoint in this face
vector<ftEdge*> face_edges = cand_vx->getFaceEdges(face.get());
if (face_edges.size() != 2)
return modified;
Point tan1 =
face_edges[0]->tangent(face_edges[0]->parAtVertex(cand_vx.get()));
Point tan2 =
face_edges[1]->tangent(face_edges[1]->parAtVertex(cand_vx.get()));
double ang = tan1.angle(tan2);
if (ang > angtol && ang < M_PI-angtol)
return modified;
// Fetch faces meeting in the vertex
Body *body = face->getBody();
vector<ftSurface*> adj_faces = cand_vx->faces(body);
if (adj_faces.size() != 3)
return modified;
// Check if the other two faces shared the same underlying surface
for (size_t ki=0; ki<adj_faces.size(); ++ki)
if (adj_faces[ki] == face.get())
{
adj_faces.erase(adj_faces.begin()+ki);
break;
}
if (adj_faces.size() != 2)
return modified;
shared_ptr<ParamSurface> surf1 = adj_faces[0]->surface();
shared_ptr<ParamSurface> surf2 = adj_faces[1]->surface();
shared_ptr<BoundedSurface> bd_sf1 =
dynamic_pointer_cast<BoundedSurface, ParamSurface>(surf1);
shared_ptr<BoundedSurface> bd_sf2 =
dynamic_pointer_cast<BoundedSurface, ParamSurface>(surf2);
if (bd_sf1.get() == NULL || bd_sf2.get() == NULL)
return modified;
shared_ptr<ParamSurface> under1 = bd_sf1->underlyingSurface();
shared_ptr<ParamSurface> under2 = bd_sf2->underlyingSurface();
if (under1.get() != under2.get())
return modified;
// The candidate vertex can be moved. Find new position
double fac = 0.1;
double t1 = face_edges[0]->tMin();
double t2 = face_edges[0]->tMax();
double t3 = face_edges[1]->tMin();
double t4 = face_edges[1]->tMax();
Point vx_pos = vx->getVertexPoint();
double par1, par2, dist1, dist2;
Point clo1, clo2;
face_edges[0]->closestPoint(vx_pos, par1, clo1, dist1);
face_edges[1]->closestPoint(vx_pos, par2, clo2, dist2);
shared_ptr<ftEdge> edg;
shared_ptr<Vertex> split_vx;
if (dist1 < dist2-epsge &&
par1 > t1 + fac*(t2-t1) && par1 < t2 - fac*(t2-t1))
{
edg = face_edges[0]->split2(par1);
split_vx = face_edges[0]->getCommonVertex(edg.get());
}
else if (dist2 < dist1-epsge &&
par2 > t3 + fac*(t4-t3) && par2 < t4 - fac*(t4-t3))
{
edg = face_edges[1]->split2(par2);
split_vx = face_edges[1]->getCommonVertex(edg.get());
}
else
return modified;
if (split_vx.get() == NULL)
return modified;
Point split_pos = split_vx->getVertexPoint();
// Remove current split
// Fetch opposite vertex
vector<shared_ptr<ftEdge> > common_edgs =
adj_faces[0]->getCommonEdges(adj_faces[1]);
if (common_edgs.size() != 1)
return modified;
shared_ptr<Vertex> opposite_vertex =
common_edgs[0]->getOtherVertex(cand_vx.get());
Point opposite_pos = opposite_vertex->getVertexPoint();
// Fetch shell
shared_ptr<SurfaceModel> model = body->getOuterShell();
int ix1 = model->getIndex(adj_faces[0]);
int ix2 = model->getIndex(adj_faces[1]);
if (ix1 < 0 || ix2 < 0)
return modified; // Faces not in shell
// Merge
vector<CurveLoop> loops1 = bd_sf1->allBoundaryLoops();
vector<CurveLoop> loops2 = bd_sf2->allBoundaryLoops();
vector<Point> seam_joints;
shared_ptr<ftSurface> merged_face =
model->performMergeFace(under1, loops1, loops2, body, seam_joints, 0);
if (merged_face.get() == NULL)
return modified;
// Insert modified split
double u1, u2, v1, v2, d1, d2;
Point pt1, pt2;
merged_face->closestPoint(split_pos, u1, v1, pt1, d1, epsge);
merged_face->closestPoint(opposite_pos, u2, v2, pt2, d2, epsge);
Point parval1(u1, v1);
Point parval2(u2, v2);
vector<shared_ptr<CurveOnSurface> > trim_segments;
shared_ptr<ParamSurface> merged_surf = merged_face->surface();
shared_ptr<BoundedSurface> bd_sf;
trim_segments = BoundedUtils::getTrimCrvsParam(merged_surf, parval1,
parval2, epsge, bd_sf);
// Check
checkTrimSeg2(trim_segments, parval1, parval2, tol2);
if (trim_segments.size() > 0)
{
#ifdef DEBUG_REG
std::ofstream out_file("new_split_segments.g2");
for (size_t kj=0; kj<trim_segments.size(); ++kj)
{
shared_ptr<ParamCurve> cv = trim_segments[kj]->spaceCurve();
cv->writeStandardHeader(out_file);
cv->write(out_file);
}
#endif
vector<shared_ptr<BoundedSurface> > sub_sfs =
BoundedUtils::splitWithTrimSegments(bd_sf, trim_segments, epsge);
// Create faces
vector<shared_ptr<Vertex> > non_corner; // Dummy
vector<shared_ptr<ftSurface> > subfaces = createFaces(sub_sfs, face,
epsge, tol2,
angtol,
non_corner);
if (subfaces.size() != 2)
return modified;
// Update topology structures
// Can the modified face pointers create problems here?
modified = true;
shared_ptr<ftSurface> adj1 = model->getFace(ix1);
shared_ptr<ftSurface> adj2 = model->getFace(ix2);
model->removeFace(adj1);
model->removeFace(adj2);
model->append(subfaces, false, false);
// Grab updated vertex
vector<shared_ptr<Vertex> > vxs =
face->getCommonVertices(subfaces[0].get(), subfaces[1].get());
if (vxs.size() > 0)
{
double vx_dist = vxs[0]->getDist(cand_vx);
cand_vx = vxs[0];
for (size_t ki=1; ki<vxs.size(); ++ki)
{
double dist = vxs[ki]->getVertexPoint().dist(vx_pos);
if (dist < vx_dist)
{
vx_dist = dist;
cand_vx = vxs[ki];
}
}
}
}
return modified;
}
//==========================================================================
void
RegularizeUtils::adjustTrimSeg(vector<shared_ptr<CurveOnSurface> >& trim_segments,
Point *parval1, Point *parval2,
shared_ptr<ftSurface> face,
shared_ptr<BoundedSurface>& bd_sf,
vector<shared_ptr<Vertex> >& non_corner,
double tol, double epsge)
// Avoid unstability be dividing very close to an insignificant vertex
//==========================================================================
{
shared_ptr<ParamSurface> surf = face->surface();
for (size_t kr=0; kr<trim_segments.size(); ++kr)
{
Point pos1 = trim_segments[kr]->ParamCurve::point(trim_segments[kr]->startparam());
Point pos2 = trim_segments[kr]->ParamCurve::point(trim_segments[kr]->endparam());
double min_dist1=std::numeric_limits<double>::max(), min_dist2=std::numeric_limits<double>::max();
int idx1 = -1, idx2 = -1;
for (size_t kj=0; kj<non_corner.size(); ++kj)
{
Point pos3 = non_corner[kj]->getVertexPoint();
double dist = pos1.dist(pos3);
if (dist < min_dist1)
{
min_dist1 = dist;
idx1 = (int)kj;
}
dist = pos2.dist(pos3);
if (dist < min_dist2)
{
min_dist2 = dist;
idx2 = (int)kj;
}
}
bool replace = false;
Point par1, par2;
Point dummy_vec;
if (idx1 >= 0 && min_dist1 < tol)
{
// Modify trim segment by adjusting the end points and make a
// constant parameter curve
replace = true;
par1 = non_corner[idx1]->getFacePar(face.get());
if (parval2 == NULL)
{
double upar, vpar, dist, edg_par;
Point clo_pt;
ftEdgeBase *edg = face->closestBoundaryPoint(pos2, dummy_vec, upar,
vpar, clo_pt,
dist, edg_par);
par2 = Point(upar, vpar);
}
else
par2 = (*parval2);
}
if (idx2 >= 0 && min_dist2 < tol)
{
replace = true;
if (parval1 == NULL)
{
double upar, vpar, dist, edg_par;
Point clo_pt;
ftEdgeBase *edg = face->closestBoundaryPoint(pos1, dummy_vec, upar,
vpar, clo_pt,
dist, edg_par);
par1 = Point(upar, vpar);
}
else
par1 = (*parval1);
par2 = non_corner[idx2]->getFacePar(face.get());
}
if (replace)
{
// Modified curve
vector<shared_ptr<CurveOnSurface> > mod_seg =
BoundedUtils::getTrimCrvsParam(surf, par1, par2, epsge, bd_sf);
if (mod_seg.size() == 1)
{
trim_segments[kr] = mod_seg[0];
break;
}
}
}
}
//==========================================================================
void
RegularizeUtils::checkTrimSeg(vector<shared_ptr<CurveOnSurface> >& trim_segments,
vector<shared_ptr<Vertex> >& next_vxs,
const Point& vx_point, const Point& other_pt,
double epsge)
// Remove intersections not connected with the initial point
// Remove also segments going through an adjacent vertex
//==========================================================================
{
double a_tol = std::max(1.0e-6, 0.01*epsge);
for (size_t kr=0; kr<trim_segments.size(); )
{
double t1 = trim_segments[kr]->startparam();
double t2 = trim_segments[kr]->endparam();
Point pos1 = trim_segments[kr]->ParamCurve::point(t1);
Point pos2 = trim_segments[kr]->ParamCurve::point(t2);
Point pos3, pos4;
double t3, t4, d3, d4 = std::numeric_limits<double>::max();
trim_segments[kr]->closestPoint(vx_point, t1, t2, t3, pos3, d3);
if (other_pt.dimension() == vx_point.dimension())
trim_segments[kr]->closestPoint(other_pt, t1, t2, t4, pos4, d4);
if (d3 < epsge &&
d3 < std::min(pos1.dist(vx_point), pos2.dist(vx_point))-a_tol)
{
// Reduce curve length
double ta = (t3 - t1 < t2 - t3) ? t3 : t1;
double tb = (t3 - t1 < t2 - t3) ? t2 : t3;
trim_segments[kr] =
shared_ptr<CurveOnSurface>(trim_segments[kr]->subCurve(ta, tb));
if (t3 - t1 < t2 - t3)
{
t1 = t3;
pos1 = pos3;
}
else
{
t2 = t3;
pos2 = pos3;
}
}
if (d4 < epsge &&
d4 < std::min(pos1.dist(other_pt), pos2.dist(other_pt))-a_tol)
{
// Reduce curve length
double ta = (t4 - t1 < t2 - t4) ? t4 : t1;
double tb = (t4 - t1 < t2 - t4) ? t2 : t4;
trim_segments[kr] =
shared_ptr<CurveOnSurface>(trim_segments[kr]->subCurve(ta, tb));
if (t4 - t1 < t2 - t4)
pos1 = pos3;
else
pos2 = pos3;
}
if (pos1.dist(vx_point) > epsge && pos2.dist(vx_point) > epsge)
trim_segments.erase(trim_segments.begin()+kr);
else if (other_pt.dimension() == vx_point.dimension() &&
pos1.dist(other_pt) > epsge && pos2.dist(other_pt) > epsge)
trim_segments.erase(trim_segments.begin()+kr);
else
{
double ta = trim_segments[kr]->startparam();
double tb = trim_segments[kr]->endparam();
size_t k3;
for (k3=0; k3<next_vxs.size(); ++k3)
{
Point next_pt = next_vxs[k3]->getVertexPoint();
Point next_close;
double next_par, next_dist;
trim_segments[kr]->closestPoint(next_pt, ta, tb, next_par,
next_close, next_dist);
// VSK, 0917. Test if this is OK
if (next_dist < epsge /*&& next_par > ta && next_par < tb*/)
break;
}
if (k3 < next_vxs.size())
trim_segments.erase(trim_segments.begin()+kr);
else
kr++;
}
}
}
//==========================================================================
void
RegularizeUtils::checkTrimSeg2(vector<shared_ptr<CurveOnSurface> >& trim_segments,
const Point& vx_par1, const Point& vx_par2,
double epsge)
// Remove intersections not connected with the initial points in the
// parameter domain
//==========================================================================
{
Point par1, par2;
size_t kr;
for (kr=0; kr<trim_segments.size(); ++kr)
{
par1 =
trim_segments[kr]->parameterCurve()->point(trim_segments[kr]->startparam());
par2 =
trim_segments[kr]->parameterCurve()->point(trim_segments[kr]->endparam());
if (par1.dist(vx_par2) < epsge || par2.dist(vx_par2) < epsge)
break;
}
if (kr == trim_segments.size() ||
(trim_segments.size()>1 &&
par1.dist(vx_par1)>epsge && par2.dist(vx_par1)>epsge))
trim_segments.clear();
}
//==========================================================================
void
RegularizeUtils::checkTrimSeg3(vector<shared_ptr<CurveOnSurface> >& trim_segments,
const Point& vx_par1, const Point& vx_par2,
double epsge)
// Remove intersections not connected with the initial points in the
// parameter domain
//==========================================================================
{
Point par1, par2;
size_t kr;
for (kr=0; kr<trim_segments.size();)
{
par1 =
trim_segments[kr]->parameterCurve()->point(trim_segments[kr]->startparam());
par2 =
trim_segments[kr]->parameterCurve()->point(trim_segments[kr]->endparam());
if (!((par1.dist(vx_par2) < epsge || par2.dist(vx_par2) < epsge) &&
(par1.dist(vx_par1) < epsge || par2.dist(vx_par1) < epsge)))
trim_segments.erase(trim_segments.begin()+kr);
else
++kr;
}
}
//==========================================================================
bool
RegularizeUtils::checkCandVx(shared_ptr<ftSurface> face,
shared_ptr<Vertex> vx1, shared_ptr<Vertex> vx2,
double bend)
//==========================================================================
{
vector<ftEdge*> edgs1 = vx1->getEdges(face.get());
vector<ftEdge*> edgs2 = vx2->getEdges(face.get());
if (edgs1.size() != 2 || edgs2.size() != 2)
return true; // Strange situation, not considered in this test
Point vec = vx2->getVertexPoint() - vx1->getVertexPoint();
Point tan1 = edgs1[0]->tangent(edgs1[0]->parAtVertex(vx1.get()));
Point tan2 = edgs1[1]->tangent(edgs1[1]->parAtVertex(vx1.get()));
Point tan3 = edgs2[0]->tangent(edgs2[0]->parAtVertex(vx2.get()));
Point tan4 = edgs2[1]->tangent(edgs2[1]->parAtVertex(vx2.get()));
// Compute minimum angle between tangent and chord
double ang1 = vec.angle(tan1);
double ang2 = vec.angle(tan2);
double ang3 = vec.angle(tan3);
double ang4 = vec.angle(tan4);
// Minimum and maximum angle at both vertices
double min_ang1 = std::min(ang1, ang2);
double max_ang1 = std::max(ang1, ang2);
double min_ang2 = std::min(ang3, ang4);
double max_ang2 = std::max(ang3, ang4);
double fac = 2.0;
if ((min_ang1 < fac*bend && max_ang2 > M_PI-fac*bend) ||
(min_ang2 < fac*bend && max_ang1 > M_PI-fac*bend))
return false;
else
return true;
}
//==========================================================================
void
RegularizeUtils::checkTrimConfig(shared_ptr<ftSurface> face,
vector<shared_ptr<CurveOnSurface> >& trim_segments,
shared_ptr<Vertex> vx,
vector<shared_ptr<Vertex> >& corners,
double epsge)
// Remove intersections that would lead to 3-sided surface
//==========================================================================
{
// Fetch the edge corresponding to end points of trim segments and count the
// number of corners between the given vertex and the end point of the segment
Point vx_point = vx->getVertexPoint();
vector<ftEdge*> vx_edges = vx->getFaceEdges(face.get());
if (vx_edges.size() != 2)
return; // An unexpected number of edges meeting in vertex
Point dummy_vec;
for (size_t kr=0; kr<trim_segments.size(); )
{
Point pos1 = trim_segments[kr]->ParamCurve::point(trim_segments[kr]->startparam());
Point pos2 = trim_segments[kr]->ParamCurve::point(trim_segments[kr]->endparam());
if (pos1.dist(vx_point) > epsge && pos2.dist(vx_point) > epsge)
{
kr++; // Not a candidate for this test
continue;
}
Point pos = (pos1.dist(vx_point) < pos2.dist(vx_point)) ? pos2 : pos1;
Point close;
double upar, vpar, par, dist;
ftEdgeBase* tmp_edge = face->closestBoundaryPoint(pos, dummy_vec, upar, vpar, close,
dist, par);
ftEdge* edge2 = tmp_edge->geomEdge();
if (!edge2)
{
kr++; // Something mysterious
continue;
}
// Check if the trim_segment joins in an edge
double tol = std::max(1.0e-10, 1.0e-6*(pos1.dist(pos2)));
shared_ptr<Vertex> other_vx;
shared_ptr<Vertex> vx2_1, vx2_2;
edge2->getVertices(vx2_1, vx2_2);
if (pos.dist(vx2_1->getVertexPoint()) < tol)
other_vx = vx2_1;
else if (pos.dist(vx2_2->getVertexPoint()) < tol)
other_vx = vx2_2;
// Count number of corners in both directions from the given vertex
ftEdge* edge1 = vx_edges[0];
bool forward = (vx.get() == edge1->getVertex(true).get());
int nmbc1 = 0;
shared_ptr<Vertex> v1 = edge1->getOtherVertex(vx.get());
while (edge1 != edge2)
{
size_t kj;
for (kj=0; kj<corners.size(); ++kj)
if (v1.get() == corners[kj].get())
{
nmbc1++;
break;
}
edge1 = (forward) ? edge1->next()->geomEdge() : edge1->prev()->geomEdge();
v1 = edge1->getOtherVertex(v1.get());
if (edge1 == vx_edges[0])
break;
if (v1.get() == other_vx.get())
break;
}
edge1 = vx_edges[1];
forward = (vx.get() == edge1->getVertex(true).get());
int nmbc2 = 0;
v1 = edge1->getOtherVertex(vx.get());
while (edge1 != edge2)
{
size_t kj;
for (kj=0; kj<corners.size(); ++kj)
if (v1.get() == corners[kj].get())
{
nmbc2++;
break;
}
edge1 = (forward) ? edge1->next()->geomEdge() : edge1->prev()->geomEdge();
v1 = edge1->getOtherVertex(v1.get());
if (edge1 == vx_edges[1])
break;
if (v1.get() == other_vx.get())
break;
}
if (nmbc1 < 2 || nmbc2 < 2)
trim_segments.erase(trim_segments.begin()+kr);
else
kr++;
}
}
//==========================================================================
ftEdge* RegularizeUtils::getOppositeBoundaryPar(shared_ptr<ftSurface> face,
shared_ptr<Vertex> vx,
vector<shared_ptr<Vertex> >& corners,
double epsge, double tol2,
Point& point,
double& par, double& dist)
//==========================================================================
{
int cx = -1;
for (cx=0; cx<(int)corners.size(); ++cx)
if (corners[cx].get() == vx.get())
break;
int id1, id2;
if (cx == (int)corners.size() && corners.size() != 4)
return NULL; // vx is not a corner
else if (cx == (int)corners.size())
{
// Fetch adjacent corners
vector<ftEdge*> edges = vx->getFaceEdges(face.get());
if (edges.size() != 2)
return NULL; // An unexpected number of edges meeting in vertex
ftEdge* edge1 = edges[0];
ftEdge* edge2 = edges[1];
shared_ptr<Vertex> v1 = edge1->getOtherVertex(vx.get());
shared_ptr<Vertex> v2 = edge2->getOtherVertex(vx.get());
// Identify corners corresponding to the adjacent edges
id1 = id2 = -1;
while (v1.get() != vx.get())
{
cx = -1;
for (cx=0; cx<(int)corners.size(); ++cx)
if (corners[cx].get() == v1.get())
break;
if (cx == (int)corners.size())
{
if (v1.get() == edge1->getVertex(true).get())
edge1 = edge1->prev()->geomEdge();
else
edge1 = edge1->next()->geomEdge();
v1 = edge1->getOtherVertex(v1.get());
}
else
{
id1 = cx;
break;
}
}
while (v2.get() != vx.get())
{
cx = -1;
for (cx=0; cx<(int)corners.size(); ++cx)
if (corners[cx].get() == v2.get())
break;
if (cx == (int)corners.size())
{
if (v2.get() == edge2->getVertex(true).get())
edge2 = edge2->prev()->geomEdge();
else
edge2 = edge2->next()->geomEdge();
v2 = edge2->getOtherVertex(v2.get());
}
else
{
id2 = cx;
break;
}
}
if (id1 == -1 || id2 == -1)
return NULL; // No corners found
// Check consistency
if (id2 > id1)
std::swap(id1, id2);
if (id2 == 0 && id1 == 3)
std::swap(id1, id2);
if (!(id1-id2 == 1 || (id1 == 0 && id2 == 3)))
return NULL;
// Set indices
id1 = (int)((id1+1)%corners.size());
id2--;
if (id2 < 0)
id2 = (int)corners.size()+id2;
}
else
{
// Set indices of corners on each side of the relevant edges.
id1 = (int)((cx + 2)%corners.size());
id2 = (cx - 2);
if (id2 < 0)
id2 = (int)corners.size()+id2;
}
// Find path between selected corners
vector<ftEdge*> edges = corners[id1]->getFaceEdges(face.get());
vector<ftEdge*> path;
shared_ptr<Vertex> curr_vx = corners[id1];
size_t ki;
for (ki=0; ki<edges.size(); ++ki)
{
ftEdge *edg = edges[ki];
shared_ptr<Vertex> other;
while (true)
{
path.push_back(edg);
other = edg->getOtherVertex(curr_vx.get());
if (other.get() == vx.get() || other.get() == corners[id2].get() ||
other.get() == corners[id1].get())
break;
vector<ftEdge*> edges2 = other->getFaceEdges(face.get());
if (edges2.size() != 2)
break;
edg = (edges2[0] == edg) ? edges2[1] : edges2[0];
curr_vx = other;
}
if (other.get() == corners[id2].get())
break;
path.clear();
curr_vx = corners[id1];
}
if (path.size() == 0)
return NULL; // No edges
// Perform closest point to the found edges
Point vx_point = vx->getVertexPoint();
dist = std::numeric_limits<double>::max(); // A huge number
int idx = -1;
double min_sc = 1.0e8;
for (ki=0; ki<path.size(); ++ki)
{
double par2, dist2;
Point point2;
path[ki]->closestPoint(vx_point, par2, point2, dist2);
Point tang = path[ki]->tangent(par2);
tang.normalize();
Point vec = point2 - vx_point;
vec.normalize();
double sc = fabs(tang*vec);
if (sc < min_sc)
{
min_sc = sc;
dist = dist2;
par = par2;
point = point2;
idx = (int)ki;
}
}
// Check resut
if (idx >= 0)
{
Point pos1 = path[idx]->point(path[idx]->tMin());
Point pos2 = path[idx]->point(path[idx]->tMax());
double dd1 = pos1.dist(point);
double dd2 = pos2.dist(point);
double del = (path[idx]->tMax() - path[idx]->tMin())*tol2/pos1.dist(pos2);
if (dd1 < tol2 && dd1 >= epsge && dd2 > tol2)
{
par += del;
}
if (dd2 < tol2 && dd2 >= epsge && dd1 > tol2)
{
par -= del;
}
}
return (idx >= 0) ? path[idx] : NULL;
}
//==========================================================================
Point RegularizeUtils::getInVec(shared_ptr<Vertex> vx,
shared_ptr<ftSurface> face)
//==========================================================================
{
double a_tol = 1.0e-8;
double anglim = 0.01;
vector<ftEdge*> edges = vx->getFaceEdges(face.get());
// Don't expect more than two edges
double t1 = edges[0]->parAtVertex(vx.get());
double t2 = edges[1]->parAtVertex(vx.get());
Point tan1 = edges[0]->tangent(t1);
Point tan2 = edges[1]->tangent(t2);
double ang = tan1.angle(tan2);
if (tan1.length() > a_tol)
tan1.normalize();
if (tan2.length() > a_tol)
tan2.normalize();
Point vec0 = 0.5*(tan1 + tan2);
if (edges[0]->tMax() - t1 < t1 - edges[0]->tMin())
tan1 *= -1;
if (edges[1]->tMax() - t2 < t2 - edges[1]->tMin())
tan2 *= -1;
Point par = vx->getFacePar(face.get());
Point vec = 0.5*(tan1 + tan2);
Point norm1 = face->normal(par[0], par[1]);
Point norm2 = norm1.cross(vec0);
Point vec2 = vec - norm1*(vec*norm1); // Problematic for concave corners
return /*(ang > anglim && ang < 0.5*M_PI) ? vec2 :*/ norm2;
}
//==========================================================================
shared_ptr<ParamCurve> RegularizeUtils::checkStrightParCv(shared_ptr<ftSurface> face,
shared_ptr<Vertex> vx1,
shared_ptr<Vertex> vx2,
double epsge,
double angtol)
//==========================================================================
{
double eps = 1.0e-9;
vector<ftEdge*> edges1 = vx1->getFaceEdges(face.get());
vector<ftEdge*> edges2 = vx2->getFaceEdges(face.get());
// Fetch tangents in the face boundary at the vertices
// Don't expect more than two edges
vector<Point> tan(4);
double t1 = edges1[0]->parAtVertex(vx1.get());
double t2 = edges1[1]->parAtVertex(vx1.get());
tan[0] = edges1[0]->tangent(t1);
tan[1] = edges1[1]->tangent(t2);
if (edges1[0]->tMax() - t1 > t1 - edges1[0]->tMin())
tan[0] *= -1;
if (edges1[1]->tMax() - t2 > t2 - edges1[1]->tMin())
tan[1] *= -1;
Point invec1 = getInVec(vx1, face);
double t3 = edges2[0]->parAtVertex(vx2.get());
double t4 = edges2[1]->parAtVertex(vx2.get());
tan[2] = edges2[0]->tangent(t3);
tan[3] = edges2[1]->tangent(t4);
if (edges2[0]->tMax() - t3 > t3 - edges2[0]->tMin())
tan[2] *= -1;
if (edges2[1]->tMax() - t4 > t4 - edges2[1]->tMin())
tan[3] *= -1;
Point invec2 = getInVec(vx2, face);
Point geo_vec = vx2->getVertexPoint() - vx1->getVertexPoint();
// Project into the parameter domain
Point par1 = vx1->getFacePar(face.get());
Point par2 = vx2->getFacePar(face.get());
// Compute partial derivatives in the surface
shared_ptr<ParamSurface> surf = face->surface();
vector<Point> sf_der1(3), sf_der2(3);
surf->point(sf_der1, par1[0], par1[1], 1);
surf->point(sf_der2, par2[0], par2[1], 1);
// For each tangent vector describe it as a linear combination of the
// surface derivatives to find the tangents in the parameter domain
int ki;
vector<Point> ptan(4);
int dim = surf->dimension();
double coef1, coef2;
for (ki=0; ki<2; ++ki)
{
CoonsPatchGen::blendcoef(&sf_der1[1][0], &sf_der1[2][0], &tan[ki][0], dim, 1,
&coef1, &coef2);
ptan[ki] = Point(coef1, coef2);
}
for (ki=0; ki<2; ++ki)
{
CoonsPatchGen::blendcoef(&sf_der2[1][0], &sf_der2[2][0], &tan[2+ki][0], dim, 1,
&coef1, &coef2);
ptan[2+ki] = Point(coef1, coef2);
}
double coef3, coef4;
CoonsPatchGen::blendcoef(&sf_der1[1][0], &sf_der1[2][0], &invec1[0], dim, 1,
&coef3, &coef4);
Point invecp1(coef3, coef4);
CoonsPatchGen::blendcoef(&sf_der2[1][0], &sf_der2[2][0], &invec2[0], dim, 1,
&coef3, &coef4);
Point invecp2(coef3, coef4);
// Vector of stright curve in the parameter domain
Point vec = par2 - par1;
Point vec2 = par1 - par2;
// Check if this vector is well within the sector defined by the tangents in the
// parameter domain
double ang1 = ptan[0].angle(ptan[1]);
ang1 = std::min(ang1, fabs(M_PI-ang1));
double ang2 = ptan[0].angle(vec);
ang2 = std::min(ang2, fabs(M_PI-ang2));
double ang3 = ptan[1].angle(vec);
ang3 = std::min(ang3, fabs(M_PI-ang3));
double inang1_0 = vec.angle(invecp1);
double inang1_1 = ptan[0].angle(invecp1);
double inang1_2 = ptan[1].angle(invecp1);
double ang4 = ptan[2].angle(ptan[3]);
ang4 = std::min(ang4, fabs(M_PI-ang4));
double ang5 = ptan[2].angle(vec);
ang5 = std::min(ang5, fabs(M_PI-ang5));
double ang6 = ptan[3].angle(vec);
ang6 = std::min(ang6, fabs(M_PI-ang6));
double inang2_0 = vec2.angle(invecp2);
double inang2_1 = ptan[2].angle((-invecp2));
double inang2_2 = ptan[3].angle((-invecp2));
bool make_pcrv = false;
double fac = 0.75;
Point d1(0.0, 0.0), d2(0.0, 0.0);
double angtol2 = 2.0*angtol;
if (ang1 < angtol &&
(std::max(ang2, ang3) < angtol || vec*invecp1 < 0.0))
{
make_pcrv = true;
d1[0] = -ptan[0][1];
d1[1] = ptan[0][0];
if (d1.length() > eps)
d1.normalize();
Point tmp = ptan[0];
if (tmp.length() > eps)
tmp.normalize();
if (tmp*vec < 0)
tmp *= -1;
if (d1*invecp1 < 0.0)
d1 *= -1;
d1 = (1.0-fac)*d1 + fac*tmp;
}
else if ((ang2 < angtol2 && (vec*ptan[0] < 0.0 || vec*invecp1 < 0.0)) ||
(ang3 < angtol2 && (vec*ptan[1] > 0.0 || vec*invecp1 < 0.0)) ||
inang1_0 > std::max(inang1_1, inang1_2))
{
make_pcrv = true;
// int sgn1 = (vec*ptan[0] < 0.0) ? 1 : -1;
// int sgn2 = (vec*ptan[1] > 0.0) ? 1 : -1;
// Point tmp = 0.5*(sgn1*ptan[0]+sgn2*ptan[1]);
// d1 = Point(-tmp[1], tmp[0]);
d1 = invecp1;
if (d1.length() > eps)
d1.normalize();
Point tmp = vec;
if (tmp.length() > eps)
tmp.normalize();
d1 = (1.0-fac)*d1 + fac*tmp;
}
if (ang4 < angtol &&
(std::max(ang5, ang6) < angtol || vec*invecp2 > 0.0))
{
make_pcrv = true;
d2[0] = -ptan[2][1];
d2[1] = ptan[2][0];
if (d2.length() > eps)
d2.normalize();
Point tmp = ptan[2];
if (tmp.length() > eps)
tmp.normalize();
if (tmp*vec > 0)
tmp *= -1;
if (d2*invecp2 < 0.0)
d2 *= -1;
d2 = (1.0-fac)*d2 + fac*tmp;
}
else if ((ang5 < angtol2 && (vec*ptan[2] > 0.0 || vec*invecp2 > 0.0)) ||
(ang6 < angtol2 && (vec*ptan[3] < 0.0 || vec*invecp2 > 0.0)) ||
inang2_0 > std::max(inang2_1, inang2_2))
{
make_pcrv = true;
// int sgn1 = (vec*ptan[2] > 0.0) ? 1 : -1;
// int sgn2 = (vec*ptan[3] < 0.0) ? 1 : -1;
// Point tmp = 0.5*(sgn1*ptan[2]+sgn2*ptan[3]);
// d2 = Point(-tmp[1], tmp[0]);
d2 = invecp2;
if (d2.length() > eps)
d2.normalize();
Point tmp = -vec;
if (tmp.length() > eps)
tmp.normalize();
d2 = (1.0-fac)*d2 + fac*tmp;
}
shared_ptr<ParamCurve> pcrv;
if (make_pcrv && (d1.length() > epsge || d2.length() > epsge))
{
// Set length of tangents
double len_fac = 3.0; //0.1; //5.0; //0.1;
double len = vec.length();
if (d1.length() > eps)
d1.normalize();
d1 *= 0.3; //len_fac*len;
if (d2.length() > eps)
d2.normalize();
d2 *= -0.3; // -1; //len_fac*len;
// Prepare for interpolation using sisl
vector<double> epoint;
vector<int> ntype;
epoint.insert(epoint.end(), par1.begin(), par1.end());
ntype.push_back(1);
if (d1.length() > epsge)
{
epoint.insert(epoint.end(), d1.begin(), d1.end());
ntype.push_back(4);
}
epoint.insert(epoint.end(), par2.begin(), par2.end());
ntype.push_back(1);
if (d2.length() > epsge)
{
epoint.insert(epoint.end(), d2.begin(), d2.end());
ntype.push_back(4);
}
// Interpolate
SISLCurve *qc = NULL;
double *gpar = NULL;
double endpar;
int nbpar = 0;
int status = 0;
s1356(&epoint[0], (int)ntype.size(), 2, &ntype[0], 0, 0, 1, 3, 0.0,
&endpar, &qc, &gpar, &nbpar, &status);
if (status >= 0)
pcrv = shared_ptr<ParamCurve>(SISLCurve2Go(qc));
if (qc) freeCurve(qc);
if (gpar) free(gpar);
}
return pcrv;
}
//==========================================================================
shared_ptr<ParamCurve> RegularizeUtils::checkStrightParCv(shared_ptr<ftSurface> face,
const Point& pos1,
const Point& pos2,
double epsge,
double angtol)
//==========================================================================
{
// Find end boundary points associated to the input points
Point dummy_vec;
double u1, v1, dt1, p1, u2, v2, dt2, p2;
Point clo1, clo2;
ftEdgeBase *edge1 = face->closestBoundaryPoint(pos1, dummy_vec, u1, v1, clo1,
dt1, p1);
ftEdgeBase *edge2 = face->closestBoundaryPoint(pos2, dummy_vec, u2, v2, clo2,
dt2, p2);
// Fetch tangents in the face boundary points
vector<Point> tan(2);
tan[0] = edge1->tangent(p1);
tan[1] = edge2->tangent(p2);
// Project into the parameter domain
Point par1(u1, v1);
Point par2(u2, v2);
// Compute partial derivatives in the surface
shared_ptr<ParamSurface> surf = face->surface();
vector<Point> sf_der1(3), sf_der2(3);
surf->point(sf_der1, par1[0], par1[1], 1);
surf->point(sf_der2, par2[0], par2[1], 1);
// For each tangent vector describe it as a linear combination of the
// surface derivatives to find the tangents in the parameter domain
int ki;
vector<Point> ptan(2);
int dim = surf->dimension();
double coef1, coef2;
CoonsPatchGen::blendcoef(&sf_der1[1][0], &sf_der1[2][0], &tan[0][0], dim, 1,
&coef1, &coef2);
ptan[0] = Point(coef1, coef2);
CoonsPatchGen::blendcoef(&sf_der2[1][0], &sf_der2[2][0], &tan[1][0], dim, 1,
&coef1, &coef2);
ptan[1] = Point(coef1, coef2);
// Vector of stright curve in the parameter domain
Point vec = par2 - par1;
// Check if this vector is well within the sector defined by the tangents in the
// parameter domain
double ang1 = ptan[0].angle(vec);
ang1 = std::min(ang1, fabs(M_PI-ang1));
vec *= -1;
double ang2 = ptan[1].angle(vec);
ang2 = std::min(ang2, fabs(M_PI-ang2));
bool make_pcrv = false;
double fac = 0.9;
Point d1(0.0, 0.0), d2(0.0, 0.0);
d1[0] = -ptan[0][1];
d1[1] = ptan[0][0];
if (ang1 < angtol || d1*(par2-par1) <= 0)
{
make_pcrv = true;
d1.normalize();
Point tmp = ptan[0];
tmp.normalize();
if (tmp*(par2-par1) < 0)
tmp *= -1;
double fac2 = 0.5;
d1 = (1.0-fac2)*d1 + fac2*tmp;
}
else
d1[0] = d1[1] = 0.0;
d2[0] = -ptan[1][1];
d2[1] = ptan[1][0];
if (ang2 < angtol || d2*vec <= 0)
{
make_pcrv = true;
d2.normalize();
Point tmp = ptan[1];
tmp.normalize();
if (tmp*vec < 0)
tmp *= -1;
double fac2 = 0.5;
d2 = (1.0-fac2)*d2 + fac2*tmp;
}
else
d2[0] = d2[1] = 0.0;
shared_ptr<ParamCurve> pcrv;
if (make_pcrv && (d1.length() > epsge || d2.length() > epsge))
{
// Set length of tangents
double len_fac = 3.0; //10.0; //5.0; //0.1;
double len = vec.length();
if (d1.length() > epsge)
d1.normalize();
d1 *= 0.3;
//d1 *= len_fac*len;
if (d2.length() > epsge)
d2.normalize();
d2 *= -0.3; //len_fac*len;
// Prepare for interpolation using sisl
vector<double> epoint;
vector<int> ntype;
epoint.insert(epoint.end(), par1.begin(), par1.end());
ntype.push_back(1);
if (d1.length() > epsge)
{
epoint.insert(epoint.end(), d1.begin(), d1.end());
ntype.push_back(4);
}
epoint.insert(epoint.end(), par2.begin(), par2.end());
ntype.push_back(1);
if (d2.length() > epsge)
{
epoint.insert(epoint.end(), d2.begin(), d2.end());
ntype.push_back(4);
}
// Interpolate
SISLCurve *qc = NULL;
double *gpar = NULL;
double endpar;
int nbpar = 0;
int status = 0;
s1356(&epoint[0], (int)ntype.size(), 2, &ntype[0], 0, 0, 1, 3, 0.0,
&endpar, &qc, &gpar, &nbpar, &status);
if (status >= 0)
pcrv = shared_ptr<ParamCurve>(SISLCurve2Go(qc));
if (qc) free(qc);
if (gpar) free(gpar);
}
return pcrv;
}
//==========================================================================
shared_ptr<ParamCurve> RegularizeUtils::checkStrightParCv(shared_ptr<ftSurface> face,
shared_ptr<Vertex> vx1,
const Point& mid,
double epsge,
double angtol)
//==========================================================================
{
vector<ftEdge*> edges1 = vx1->getFaceEdges(face.get());
// Fetch tangents in the face boundary at the vertices
// Don't expect more than two edges
vector<Point> tan(4);
double t1 = edges1[0]->parAtVertex(vx1.get());
double t2 = edges1[1]->parAtVertex(vx1.get());
tan[0] = edges1[0]->tangent(t1);
tan[1] = edges1[1]->tangent(t2);
tan[0].normalize();
tan[1].normalize();
if (edges1[0]->tMax() - t1 > t1 - edges1[0]->tMin())
tan[0] *= -1;
if (edges1[1]->tMax() - t2 > t2 - edges1[1]->tMin())
tan[1] *= -1;
// Project into the parameter domain
Point par1 = vx1->getFacePar(face.get());
Point invec1 = getInVec(vx1, face);
// The point will typically lie inside a hole. Thus, we need the underlying
// surface.
shared_ptr<ParamSurface> surf = face->surface();
shared_ptr<BoundedSurface> bd_sf = dynamic_pointer_cast<BoundedSurface,ParamSurface>(surf);
if (bd_sf.get())
surf = bd_sf->underlyingSurface();
Point close;
double paru, parv, dist;
surf->closestPoint(mid, paru, parv, close, dist, epsge);
Point par2(paru, parv);
// Compute partial derivatives in the surface
vector<Point> sf_der1(3);
surf->point(sf_der1, par1[0], par1[1], 1);
// Describe the tangent vector as a linear combination of the
// surface derivatives to find the tangents in the parameter domain
int ki;
vector<Point> ptan(2);
int dim = surf->dimension();
double coef1, coef2;
for (ki=0; ki<2; ++ki)
{
CoonsPatchGen::blendcoef(&sf_der1[1][0], &sf_der1[2][0], &tan[ki][0], dim, 1,
&coef1, &coef2);
ptan[ki] = Point(coef1, coef2);
}
double coef3, coef4;
CoonsPatchGen::blendcoef(&sf_der1[1][0], &sf_der1[2][0], &invec1[0], dim, 1,
&coef3, &coef4);
Point invecp1(coef3, coef4);
// Vector of stright curve in the parameter domain
Point vec = par2 - par1;
// Check if this vector is well within the sector defined by the tangents in the
// parameter domain
double ang1 = ptan[0].angle(ptan[1]);
ang1 = std::min(ang1, fabs(M_PI-ang1));
double ang2 = ptan[0].angle(vec);
ang2 = std::min(ang2, fabs(M_PI-ang2));
double ang3 = ptan[1].angle(vec);
ang3 = std::min(ang3, fabs(M_PI-ang3));
bool make_pcrv = false;
double fac = 0.75;
Point d1(0.0, 0.0);
double angtol2 = 2.0*angtol;
if (ang1 < angtol &&
(std::max(ang2, ang3) < angtol || vec*invecp1 < 0.0))
{
make_pcrv = true;
d1[0] = -ptan[0][1];
d1[1] = ptan[0][0];
if (d1.length() > epsge)
d1.normalize();
Point tmp = ptan[0];
if (tmp.length() > epsge)
tmp.normalize();
if (tmp*vec < 0)
tmp *= -1;
if (d1*invecp1 < 0.0)
d1 *= -1;
d1 = (1.0-fac)*d1 + fac*tmp;
}
else if ((ang2 < angtol2 && (vec*ptan[0] < 0.0 || vec*invecp1 < 0.0)) ||
(ang3 < angtol2 && (vec*ptan[1] > 0.0 || vec*invecp1 < 0.0)))
{
make_pcrv = true;
// int sgn1 = (vec*ptan[0] > 0.0) ? 1 : -1;
// int sgn2 = (vec*ptan[1] > -epsge) ? 1 : -1;
// Point tmp = 0.5*(sgn1*ptan[0] + sgn2*ptan[1]);
// d1[0] = -tmp[1];
// d1[1] = tmp[0];
d1 = invecp1;
if (d1.length() > epsge)
d1.normalize();
Point tmp = vec;
if (tmp.length() > epsge)
tmp.normalize();
d1 = (1.0-fac)*d1 + fac*tmp;
}
// Check if the given point lies at a face boundary and must be checked towards
// the boundary tangent
Point dummy_vec;
double u2, v2, dt2, p2;
Point clo2;
ftEdgeBase *edg2 = face->closestBoundaryPoint(mid, dummy_vec, u2, v2, clo2,
dt2, p2);
Point d2(0.0, 0.0);
if (dt2 <= epsge)
{
Point tan2 = edg2->tangent(p2);
vector<Point> sf_der2(3);
surf->point(sf_der2, par2[0], par2[1], 1);
CoonsPatchGen::blendcoef(&sf_der2[1][0], &sf_der2[2][0], &tan2[0], dim, 1,
&coef1, &coef2);
Point ptan2 = Point(coef1, coef2);
double angle = ptan2.angle(vec);
d2[0] = -ptan2[1];
d2[1] = ptan2[0];
if (angle < angtol || d2*(par1-par2) <= 0)
{
make_pcrv = true;
d2.normalize();
Point tmp = ptan2;
tmp.normalize();
if (tmp*(par1-par2) < 0)
tmp *= -1;
d2 = (1.0-fac)*d2 + fac*tmp;
}
else
d2[0] = d2[1] = 0.0;
}
shared_ptr<ParamCurve> pcrv;
if (make_pcrv /*&& d1.length() > epsge*/)
{
// Set length of tangent
double len_fac = 3.0; //10.0; //6.0; //3.0; //0.3;
double len = vec.length();
if (d1.length() > epsge)
d1.normalize();
d1 *= 0.3;
//d1 *= len_fac*len;
if (d2.length() > epsge)
d2.normalize();
d2 *= -0.3; //len_fac*len;
// Prepare for interpolation using sisl
vector<double> epoint;
vector<int> ntype;
epoint.insert(epoint.end(), par1.begin(), par1.end());
ntype.push_back(1);
if (d1.length() > epsge)
{
epoint.insert(epoint.end(), d1.begin(), d1.end());
ntype.push_back(4);
}
epoint.insert(epoint.end(), par2.begin(), par2.end());
ntype.push_back(1);
if (d2.length() > epsge)
{
epoint.insert(epoint.end(), d2.begin(), d2.end());
ntype.push_back(4);
}
// Interpolate
SISLCurve *qc = NULL;
double *gpar = NULL;
double endpar;
int nbpar = 0;
int status = 0;
s1356(&epoint[0], (int)ntype.size(), 2, &ntype[0], 0, 0, 1, 3, 0.0,
&endpar, &qc, &gpar, &nbpar, &status);
if (status >= 0)
pcrv = shared_ptr<ParamCurve>(SISLCurve2Go(qc));
if (qc) free(qc);
if (gpar) free(gpar);
}
return pcrv;
}
//==========================================================================
bool RegularizeUtils::checkRegularity(vector<shared_ptr<Vertex> >& cand_vx,
shared_ptr<ftSurface> face,
bool checkConvex)
//==========================================================================
{
if (cand_vx.size() != 4)
return false;
// For the time being, we apply a simple check that requires the the difference
// in length between opposite edges to be less than 50% and corner angles to
// be between pi/4 and 3pi/4.
vector<Point> pos(4);
int ki, kj;
for (ki=0; ki<4; ++ki)
pos[ki] = cand_vx[ki]->getVertexPoint();
vector<Point> vec(4);
for (ki=0; ki<4; ++ki)
vec[ki] = pos[(ki+1)%4] - pos[ki];
double frac = 0.1;
for (ki=0; ki<2; ++ki)
{
double l1 = vec[ki].length();
double l2 = vec[ki+2].length();
if (std::min(l1,l2) < frac*std::max(l1,l2))
return false;
if (vec[ki]*vec[ki+2] >= 0.0)
return false;
}
double level_ang = 0.1*M_PI; //0.25*M_PI;
for (ki=0; ki<4; ki++)
{
kj = (ki+1)%4;
double ang = vec[ki].angle(vec[kj]);
if (ang < level_ang || ang > M_PI-level_ang)
return false;
}
if (checkConvex)
{
// An extra check for the tangent in the concave vertex
ftEdge *edge = cand_vx[0]->getCommonEdge(cand_vx[1].get());
if (!edge)
return false;
Point tan = edge->tangent(edge->parAtVertex(cand_vx[0].get()));
double ang = tan.angle(vec[3]);
if (ang < level_ang || ang > M_PI-level_ang)
return false;
// Make sure that the new edges lies inside the material
Point invec = getInVec(cand_vx[0], face);
if (invec*vec[3] > 0.0)
return false;
}
return true;
}
//==========================================================================
vector<shared_ptr<Vertex> > RegularizeUtils::endVxInChain(shared_ptr<ftSurface> face,
ftSurface* face1,
ftSurface* face2,
shared_ptr<Vertex> vx,
shared_ptr<Vertex> prev,
shared_ptr<Vertex> vx0,
vector<shared_ptr<Vertex> >& met_already)
//==========================================================================
{
vector<shared_ptr<Vertex> > end_vx;
// Fetch vertex edges not bounding the current face
vector<ftEdge*> edges = vx->uniqueEdges();
size_t kr;
for (kr=0; kr<edges.size(); )
{
if (edges[kr]->face() == face1 ||
(edges[kr]->twin() && edges[kr]->twin()->geomEdge()->face() == face1))
edges.erase(edges.begin()+kr);
else if (face2 &&
(edges[kr]->face() == face2 ||
(edges[kr]->twin() && edges[kr]->twin()->geomEdge()->face() == face2)))
edges.erase(edges.begin()+kr);
else
kr++;
}
// Traverse all candidate edges
for (kr=0; kr<edges.size(); ++kr)
{
shared_ptr<Vertex> vx2 = edges[kr]->getOtherVertex(vx.get());
#ifdef DEBUG_REG
std::ofstream of("vx2.g2");
of << "400 1 0 4 0 255 0 255 " << std::endl;
of << "1" << std::endl;
of << vx2->getVertexPoint() << std::endl;
#endif
if (vx2.get() == prev.get())
continue; // Do not go back in loop
if (vx2.get() == vx0.get())
continue; // Stop loop
if (face1 != face.get() && vx2->hasFace(face.get()))
{
// A candidate endpoint is found
end_vx.push_back(vx2);
continue;
}
// Check if this path is pursued before
size_t kj;
for (kj=0; kj<met_already.size(); ++kj)
if (met_already[kj].get() == vx2.get())
break;
if (kj < met_already.size())
continue;
// Fetch faces adjacent to current edge and continue the search
ftSurface* curr_face1 = edges[kr]->face()->asFtSurface();
ftSurface* curr_face2 = (edges[kr]->twin()) ?
edges[kr]->twin()->face()->asFtSurface() : NULL;
if (face1 != face.get() && face2 == NULL && curr_face2 == NULL)
continue; // Not a good patch
met_already.push_back(vx2);
vector<shared_ptr<Vertex> > curr_end_vx = endVxInChain(face, curr_face1,
curr_face2, vx2,
vx, vx0, met_already);
if (curr_end_vx.size() > 0)
end_vx.insert(end_vx.end(), curr_end_vx.begin(), curr_end_vx.end());
}
return end_vx;
}
//==========================================================================
int RegularizeUtils::traverseUntilTJoint(vector<ftSurface*> vx_faces,
shared_ptr<Vertex> vx,
shared_ptr<Vertex>& vx2,
vector<ftSurface*>& vx_faces2)
//==========================================================================
{
int status = 2; // Indicate not a smooth transition
Body *bd0 = vx_faces[0]->getBody();
shared_ptr<Vertex> vx0 = vx;
shared_ptr<Vertex> vx1 = vx2;
size_t ki, kj;
while (vx_faces2.size() < 3)
{
// Get next edge
vector<ftEdge*> edges2 = vx1->uniqueEdges();
if (edges2.size() > 2)
return status;
for (ki=0; ki<edges2.size(); ++ki)
{
shared_ptr<Vertex> vx3 = edges2[ki]->getOtherVertex(vx1.get());
if (vx3.get() == vx0.get())
continue;
vx2 = vx3;
vx_faces2 = vx2->faces();
// Remove faces from other bodies
for (kj=0; kj<vx_faces2.size();)
{
if (vx_faces2[kj]->getBody() != bd0)
vx_faces2.erase(vx_faces2.begin()+kj);
else
kj++;
}
if (vx_faces2.size() > 3)
continue;
shared_ptr<FaceConnectivity<ftEdgeBase> > info =
edges2[ki]->getConnectivityInfo();
status = info->WorstStatus();
if (status > 1)
return status;
}
vx0 = vx1;
vx1 = vx2;
}
return status;
}
//==========================================================================
void RegularizeUtils::angleInEndpoints(shared_ptr<CurveOnSurface> seg,
shared_ptr<Vertex> vx1,
shared_ptr<Vertex> vx2,
shared_ptr<ftSurface> face,
double& min_ang1, double& min_ang2)
//==========================================================================
{
vector<ftEdge*> edg1 = vx1->getFaceEdges(face.get());
vector<ftEdge*> edg2 = vx2->getFaceEdges(face.get());
vector<Point> der1(2), der2(2);
seg->point(der1, seg->startparam(), 1);
seg->point(der2, seg->endparam(), 1);
Point pos1 = vx1->getVertexPoint();
Point pos2 = vx2->getVertexPoint();
if (der1[0].dist(pos1) > der1[0].dist(pos2))
std::swap(der1, der2);
// First endpoint
size_t ki;
min_ang1 = M_PI;
for (ki=0; ki<edg1.size(); ++ki)
{
double t1 = edg1[ki]->parAtVertex(vx1.get());
Point tan = edg1[ki]->tangent(t1);
double ang = der1[1].angle(tan);
if (fabs(M_PI-ang) < ang)
ang = fabs(M_PI-ang);
min_ang1 = std::min(min_ang1, ang);
}
// Second endpoint
min_ang2 = M_PI;
for (ki=0; ki<edg2.size(); ++ki)
{
double t1 = edg2[ki]->parAtVertex(vx2.get());
Point tan = edg2[ki]->tangent(t1);
double ang = der2[1].angle(tan);
if (fabs(M_PI-ang) < ang)
ang = fabs(M_PI-ang);
min_ang2 = std::min(min_ang2, ang);
}
}
//==========================================================================
void RegularizeUtils::getSourceCvs(vector<shared_ptr<ftEdge> >& all_edg,
vector<shared_ptr<ParamCurve> >& all_cvs)
//==========================================================================
{
all_cvs.resize(all_edg.size());
for (size_t ki=0; ki<all_edg.size(); ++ki)
{
shared_ptr<ParamCurve> curr = all_edg[ki]->geomCurve();
// Make sure to have access to the geometry space curve
shared_ptr<CurveOnSurface> sf_cv =
dynamic_pointer_cast<CurveOnSurface,ParamCurve>(curr);
if (sf_cv.get())
curr = sf_cv->spaceCurve();
// Check if the curve is a spline representation of an elementary curve
shared_ptr<SplineCurve> spline_cv =
dynamic_pointer_cast<SplineCurve,ParamCurve>(curr);
if (spline_cv.get() && spline_cv->isElementaryCurve())
all_cvs[ki] = spline_cv->getElementaryCurve();
else
all_cvs[ki] = curr;
}
}
//==========================================================================
void RegularizeUtils::adjustVertexPosition(shared_ptr<ParamSurface> surf,
Point& vx_pos, Point& vx_par,
double tol)
//==========================================================================
{
// Fetch all surface corners
vector<pair<Point,Point> > corners;
surf->getCornerPoints(corners);
// Find closest surface corner
double min_dist = std::numeric_limits<double>::max();
int min_ix = -1;
for (int ki=0; ki<(int)corners.size(); ++ki)
{
double dist = vx_pos.dist(corners[ki].first);
if (dist < min_dist)
{
min_dist = dist;
min_ix = ki;
}
}
if (min_dist < tol)
{
// Replace vertex position and parameter
// First check accuracy of corner information
Point par_pos = surf->point(corners[min_ix].second[0],
corners[min_ix].second[1]);
double dist = par_pos.dist(corners[min_ix].first);
vx_pos = corners[min_ix].first;
vx_par = corners[min_ix].second;
}
}
//==========================================================================
void
RegularizeUtils::checkCornerConfig(vector<shared_ptr<Vertex> >& corner,
shared_ptr<ftSurface>& face,
double angtol)
//==========================================================================
{
// Remove corners with a relatively small angle, where only two surfaces
// meet and where at least one of the adjacent edges is a gap edge.
// Relevant for models with gaps
size_t kr;
Body *body = face->getBody();
for (kr=0; kr<corner.size(); )
{
// Check number of faces
vector<ftSurface*> faces = corner[kr]->faces(body);
if (faces.size() != 2)
{
++kr;
continue;
}
// Check angle
vector<ftEdge*> edgs = corner[kr]->getEdges(face.get());
if (edgs.size() != 2)
{
++kr;
continue;
}
Point tan1 = edgs[0]->tangent(edgs[0]->parAtVertex(corner[kr].get()));
Point tan2 = edgs[1]->tangent(edgs[1]->parAtVertex(corner[kr].get()));
double ang = tan1.angle(tan2);
if (ang > angtol)
{
++kr;
continue;
}
// Check edge status
// int stat1 = edgs[0]->getConnectivityInfo()->WorstStatus();
// int stat2 = edgs[1]->getConnectivityInfo()->WorstStatus();
// if (true) //stat1 >= 3 || stat2 >= 3)
corner.erase(corner.begin()+kr);
// else
// ++kr;
}
}
| agpl-3.0 |
DerDu/SPHERE-Framework | Library/MOC-V/Component/Router/Vendor/Symfony/Component/HttpKernel/Tests/CacheClearer/ChainCacheClearerTest.php | 1488 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Tests\CacheClearer;
use Symfony\Component\HttpKernel\CacheClearer\ChainCacheClearer;
class ChainCacheClearerTest extends \PHPUnit_Framework_TestCase
{
protected static $cacheDir;
public static function setUpBeforeClass()
{
self::$cacheDir = tempnam(sys_get_temp_dir(), 'sf2_cache_clearer_dir');
}
public static function tearDownAfterClass()
{
@unlink(self::$cacheDir);
}
public function testInjectClearersInConstructor()
{
$clearer = $this->getMockClearer();
$clearer
->expects($this->once())
->method('clear');
$chainClearer = new ChainCacheClearer(array($clearer));
$chainClearer->clear(self::$cacheDir);
}
protected function getMockClearer()
{
return $this->getMock('Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface');
}
public function testInjectClearerUsingAdd()
{
$clearer = $this->getMockClearer();
$clearer
->expects($this->once())
->method('clear');
$chainClearer = new ChainCacheClearer();
$chainClearer->add($clearer);
$chainClearer->clear(self::$cacheDir);
}
}
| agpl-3.0 |
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/scipy/stats/tests/test_continuous_basic.py | 13471 | from __future__ import division, print_function, absolute_import
import warnings
import numpy as np
import numpy.testing as npt
from scipy import integrate
from scipy import stats
from common_tests import (check_normalization, check_moment, check_mean_expect,
check_var_expect, check_skew_expect, check_kurt_expect,
check_entropy, check_private_entropy, NUMPY_BELOW_1_7,
check_edge_support, check_named_args)
from scipy.stats._distr_params import distcont
"""
Test all continuous distributions.
Parameters were chosen for those distributions that pass the
Kolmogorov-Smirnov test. This provides safe parameters for each
distributions so that we can perform further testing of class methods.
These tests currently check only/mostly for serious errors and exceptions,
not for numerically exact results.
"""
DECIMAL = 5 # specify the precision of the tests # increased from 0 to 5
## Last four of these fail all around. Need to be checked
distcont_extra = [
['betaprime', (100, 86)],
['fatiguelife', (5,)],
['mielke', (4.6420495492121487, 0.59707419545516938)],
['invweibull', (0.58847112119264788,)],
# burr: sample mean test fails still for c<1
['burr', (0.94839838075366045, 4.3820284068855795)],
# genextreme: sample mean test, sf-logsf test fail
['genextreme', (3.3184017469423535,)],
]
# for testing only specific functions
# distcont = [
## ['fatiguelife', (29,)], #correction numargs = 1
## ['loggamma', (0.41411931826052117,)]]
# for testing ticket:767
# distcont = [
## ['genextreme', (3.3184017469423535,)],
## ['genextreme', (0.01,)],
## ['genextreme', (0.00001,)],
## ['genextreme', (0.0,)],
## ['genextreme', (-0.01,)]
## ]
# distcont = [['gumbel_l', ()],
## ['gumbel_r', ()],
## ['norm', ()]
## ]
# distcont = [['norm', ()]]
distmissing = ['wald', 'gausshyper', 'genexpon', 'rv_continuous',
'loglaplace', 'rdist', 'semicircular', 'invweibull', 'ksone',
'cosine', 'kstwobign', 'truncnorm', 'mielke', 'recipinvgauss', 'levy',
'johnsonsu', 'levy_l', 'powernorm', 'wrapcauchy',
'johnsonsb', 'truncexpon', 'rice', 'invgauss', 'invgamma',
'powerlognorm']
distmiss = [[dist,args] for dist,args in distcont if dist in distmissing]
distslow = ['rdist', 'gausshyper', 'recipinvgauss', 'ksone', 'genexpon',
'vonmises', 'vonmises_line', 'mielke', 'semicircular',
'cosine', 'invweibull', 'powerlognorm', 'johnsonsu', 'kstwobign']
# distslow are sorted by speed (very slow to slow)
# NB: not needed anymore?
def _silence_fp_errors(func):
# warning: don't apply to test_ functions as is, then those will be skipped
def wrap(*a, **kw):
olderr = np.seterr(all='ignore')
try:
return func(*a, **kw)
finally:
np.seterr(**olderr)
wrap.__name__ = func.__name__
return wrap
def test_cont_basic():
# this test skips slow distributions
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=integrate.IntegrationWarning)
for distname, arg in distcont[:]:
if distname in distslow:
continue
if distname is 'levy_stable':
continue
distfn = getattr(stats, distname)
np.random.seed(765456)
sn = 500
rvs = distfn.rvs(size=sn, *arg)
sm = rvs.mean()
sv = rvs.var()
m, v = distfn.stats(*arg)
yield check_sample_meanvar_, distfn, arg, m, v, sm, sv, sn, \
distname + 'sample mean test'
yield check_cdf_ppf, distfn, arg, distname
yield check_sf_isf, distfn, arg, distname
yield check_pdf, distfn, arg, distname
yield check_pdf_logpdf, distfn, arg, distname
yield check_cdf_logcdf, distfn, arg, distname
yield check_sf_logsf, distfn, arg, distname
if distname in distmissing:
alpha = 0.01
yield check_distribution_rvs, distname, arg, alpha, rvs
locscale_defaults = (0, 1)
meths = [distfn.pdf, distfn.logpdf, distfn.cdf, distfn.logcdf,
distfn.logsf]
# make sure arguments are within support
spec_x = {'frechet_l': -0.5, 'weibull_max': -0.5, 'levy_l': -0.5,
'pareto': 1.5, 'tukeylambda': 0.3}
x = spec_x.get(distname, 0.5)
yield check_named_args, distfn, x, arg, locscale_defaults, meths
# Entropy
skp = npt.dec.skipif
yield check_entropy, distfn, arg, distname
if distfn.numargs == 0:
yield skp(NUMPY_BELOW_1_7)(check_vecentropy), distfn, arg
if distfn.__class__._entropy != stats.rv_continuous._entropy:
yield check_private_entropy, distfn, arg, stats.rv_continuous
yield check_edge_support, distfn, arg
knf = npt.dec.knownfailureif
yield knf(distname == 'truncnorm')(check_ppf_private), distfn, \
arg, distname
@npt.dec.slow
def test_cont_basic_slow():
# same as above for slow distributions
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=integrate.IntegrationWarning)
for distname, arg in distcont[:]:
if distname not in distslow:
continue
if distname is 'levy_stable':
continue
distfn = getattr(stats, distname)
np.random.seed(765456)
sn = 500
rvs = distfn.rvs(size=sn,*arg)
sm = rvs.mean()
sv = rvs.var()
m, v = distfn.stats(*arg)
yield check_sample_meanvar_, distfn, arg, m, v, sm, sv, sn, \
distname + 'sample mean test'
yield check_cdf_ppf, distfn, arg, distname
yield check_sf_isf, distfn, arg, distname
yield check_pdf, distfn, arg, distname
yield check_pdf_logpdf, distfn, arg, distname
yield check_cdf_logcdf, distfn, arg, distname
yield check_sf_logsf, distfn, arg, distname
# yield check_oth, distfn, arg # is still missing
if distname in distmissing:
alpha = 0.01
yield check_distribution_rvs, distname, arg, alpha, rvs
locscale_defaults = (0, 1)
meths = [distfn.pdf, distfn.logpdf, distfn.cdf, distfn.logcdf,
distfn.logsf]
# make sure arguments are within support
x = 0.5
if distname == 'invweibull':
arg = (1,)
elif distname == 'ksone':
arg = (3,)
yield check_named_args, distfn, x, arg, locscale_defaults, meths
# Entropy
skp = npt.dec.skipif
ks_cond = distname in ['ksone', 'kstwobign']
yield skp(ks_cond)(check_entropy), distfn, arg, distname
if distfn.numargs == 0:
yield skp(NUMPY_BELOW_1_7)(check_vecentropy), distfn, arg
if distfn.__class__._entropy != stats.rv_continuous._entropy:
yield check_private_entropy, distfn, arg, stats.rv_continuous
yield check_edge_support, distfn, arg
@npt.dec.slow
def test_moments():
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=integrate.IntegrationWarning)
knf = npt.dec.knownfailureif
fail_normalization = set(['vonmises', 'ksone'])
fail_higher = set(['vonmises', 'ksone', 'ncf'])
for distname, arg in distcont[:]:
if distname is 'levy_stable':
continue
distfn = getattr(stats, distname)
m, v, s, k = distfn.stats(*arg, moments='mvsk')
cond1, cond2 = distname in fail_normalization, distname in fail_higher
msg = distname + ' fails moments'
yield knf(cond1, msg)(check_normalization), distfn, arg, distname
yield knf(cond2, msg)(check_mean_expect), distfn, arg, m, distname
yield knf(cond2, msg)(check_var_expect), distfn, arg, m, v, distname
yield knf(cond2, msg)(check_skew_expect), distfn, arg, m, v, s, \
distname
yield knf(cond2, msg)(check_kurt_expect), distfn, arg, m, v, k, \
distname
yield check_loc_scale, distfn, arg, m, v, distname
yield check_moment, distfn, arg, m, v, distname
def check_sample_meanvar_(distfn, arg, m, v, sm, sv, sn, msg):
# this did not work, skipped silently by nose
if not np.isinf(m):
check_sample_mean(sm, sv, sn, m)
if not np.isinf(v):
check_sample_var(sv, sn, v)
def check_sample_mean(sm,v,n, popmean):
# from stats.stats.ttest_1samp(a, popmean):
# Calculates the t-obtained for the independent samples T-test on ONE group
# of scores a, given a population mean.
#
# Returns: t-value, two-tailed prob
df = n-1
svar = ((n-1)*v) / float(df) # looks redundant
t = (sm-popmean) / np.sqrt(svar*(1.0/n))
prob = stats.betai(0.5*df, 0.5, df/(df+t*t))
# return t,prob
npt.assert_(prob > 0.01, 'mean fail, t,prob = %f, %f, m, sm=%f,%f' %
(t, prob, popmean, sm))
def check_sample_var(sv,n, popvar):
# two-sided chisquare test for sample variance equal to hypothesized variance
df = n-1
chi2 = (n-1)*popvar/float(popvar)
pval = stats.chisqprob(chi2,df)*2
npt.assert_(pval > 0.01, 'var fail, t, pval = %f, %f, v, sv=%f, %f' %
(chi2,pval,popvar,sv))
def check_cdf_ppf(distfn,arg,msg):
values = [0.001, 0.5, 0.999]
npt.assert_almost_equal(distfn.cdf(distfn.ppf(values, *arg), *arg),
values, decimal=DECIMAL, err_msg=msg +
' - cdf-ppf roundtrip')
def check_sf_isf(distfn,arg,msg):
npt.assert_almost_equal(distfn.sf(distfn.isf([0.1,0.5,0.9], *arg), *arg),
[0.1,0.5,0.9], decimal=DECIMAL, err_msg=msg +
' - sf-isf roundtrip')
npt.assert_almost_equal(distfn.cdf([0.1,0.9], *arg),
1.0-distfn.sf([0.1,0.9], *arg),
decimal=DECIMAL, err_msg=msg +
' - cdf-sf relationship')
def check_pdf(distfn, arg, msg):
# compares pdf at median with numerical derivative of cdf
median = distfn.ppf(0.5, *arg)
eps = 1e-6
pdfv = distfn.pdf(median, *arg)
if (pdfv < 1e-4) or (pdfv > 1e4):
# avoid checking a case where pdf is close to zero or huge (singularity)
median = median + 0.1
pdfv = distfn.pdf(median, *arg)
cdfdiff = (distfn.cdf(median + eps, *arg) -
distfn.cdf(median - eps, *arg))/eps/2.0
# replace with better diff and better test (more points),
# actually, this works pretty well
npt.assert_almost_equal(pdfv, cdfdiff,
decimal=DECIMAL, err_msg=msg + ' - cdf-pdf relationship')
def check_pdf_logpdf(distfn, args, msg):
# compares pdf at several points with the log of the pdf
points = np.array([0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8])
vals = distfn.ppf(points, *args)
pdf = distfn.pdf(vals, *args)
logpdf = distfn.logpdf(vals, *args)
pdf = pdf[pdf != 0]
logpdf = logpdf[np.isfinite(logpdf)]
npt.assert_almost_equal(np.log(pdf), logpdf, decimal=7, err_msg=msg + " - logpdf-log(pdf) relationship")
def check_sf_logsf(distfn, args, msg):
# compares sf at several points with the log of the sf
points = np.array([0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8])
vals = distfn.ppf(points, *args)
sf = distfn.sf(vals, *args)
logsf = distfn.logsf(vals, *args)
sf = sf[sf != 0]
logsf = logsf[np.isfinite(logsf)]
npt.assert_almost_equal(np.log(sf), logsf, decimal=7, err_msg=msg + " - logsf-log(sf) relationship")
def check_cdf_logcdf(distfn, args, msg):
# compares cdf at several points with the log of the cdf
points = np.array([0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8])
vals = distfn.ppf(points, *args)
cdf = distfn.cdf(vals, *args)
logcdf = distfn.logcdf(vals, *args)
cdf = cdf[cdf != 0]
logcdf = logcdf[np.isfinite(logcdf)]
npt.assert_almost_equal(np.log(cdf), logcdf, decimal=7, err_msg=msg + " - logcdf-log(cdf) relationship")
def check_distribution_rvs(dist, args, alpha, rvs):
# test from scipy.stats.tests
# this version reuses existing random variables
D,pval = stats.kstest(rvs, dist, args=args, N=1000)
if (pval < alpha):
D,pval = stats.kstest(dist,'',args=args, N=1000)
npt.assert_(pval > alpha, "D = " + str(D) + "; pval = " + str(pval) +
"; alpha = " + str(alpha) + "\nargs = " + str(args))
def check_vecentropy(distfn, args):
npt.assert_equal(distfn.vecentropy(*args), distfn._entropy(*args))
@npt.dec.skipif(NUMPY_BELOW_1_7)
def check_loc_scale(distfn, arg, m, v, msg):
loc, scale = 10.0, 10.0
mt, vt = distfn.stats(loc=loc, scale=scale, *arg)
npt.assert_allclose(m*scale + loc, mt)
npt.assert_allclose(v*scale*scale, vt)
def check_ppf_private(distfn, arg, msg):
#fails by design for truncnorm self.nb not defined
ppfs = distfn._ppf(np.array([0.1, 0.5, 0.9]), *arg)
npt.assert_(not np.any(np.isnan(ppfs)), msg + 'ppf private is nan')
if __name__ == "__main__":
npt.run_module_suite()
| agpl-3.0 |
kuraju/CoAnSys | models/src/main/java/pl/edu/icm/coansys/models/constants/BWMetaConstants.java | 2032 | /*
* This file is part of CoAnSys project.
* Copyright (c) 2012-2015 ICM-UW
*
* CoAnSys is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* CoAnSys is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CoAnSys. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.coansys.models.constants;
import java.util.ArrayList;
import java.util.List;
/**
* @author pdendek
*/
public final class BWMetaConstants {
private BWMetaConstants() {
}
public static final String mimePdfOneApplicationPdf = "application/pdf";
public static final String mimePdfOneApplicationAcrobat = "application/acrobat";
public static final String mimePdfOneApplicationXPdf = "application/x-pdf";
public static final String mimePdfOneTextPdf = "text/pdf";
public static final String mimePdfOneTextXPdf = "text/x-pdf";
public static final List<String> mimePdfListExtension = new ArrayList<String>();
static {
mimePdfListExtension.add(BWMetaConstants.mimePdfOneApplicationAcrobat);
mimePdfListExtension.add(BWMetaConstants.mimePdfOneApplicationPdf);
mimePdfListExtension.add(BWMetaConstants.mimePdfOneApplicationXPdf);
mimePdfListExtension.add(BWMetaConstants.mimePdfOneTextPdf);
mimePdfListExtension.add(BWMetaConstants.mimePdfOneTextXPdf);
}
public static final String mimeTextPlain = "text/plain";
public static final List<String> mimeTxtListExtension = new ArrayList<String>();
static {
mimeTxtListExtension.add(BWMetaConstants.mimeTextPlain);
}
}
| agpl-3.0 |
edx/edx-demo-course | static/jsmol/j2s/org/jmol/shapespecial/Dipole.js | 5717 | Clazz.declarePackage ("org.jmol.shapespecial");
Clazz.load (null, "org.jmol.shapespecial.Dipole", ["org.jmol.util.Colix", "$.Escape", "$.Point3f", "$.StringXBuilder", "$.Vector3f"], function () {
c$ = Clazz.decorateAsClass (function () {
this.thisID = "";
this.mad = 0;
this.colix = 0;
this.type = 0;
this.origin = null;
this.center = null;
this.vector = null;
this.dipoleInfo = "";
this.dipoleValue = 0;
this.isUserValue = false;
this.offsetSide = 0;
this.offsetAngstroms = 0;
this.offsetPercent = 0;
this.visibilityFlags = 0;
this.modelIndex = 0;
this.visible = false;
this.noCross = false;
this.haveAtoms = false;
this.isValid = false;
this.atoms = null;
this.coords = null;
this.bond = null;
Clazz.instantialize (this, arguments);
}, org.jmol.shapespecial, "Dipole");
Clazz.prepareFields (c$, function () {
this.atoms = new Array (2);
this.coords = new Array (2);
});
Clazz.makeConstructor (c$,
function () {
});
Clazz.makeConstructor (c$,
function (modelIndex, thisID, dipoleInfo, colix, mad, visible) {
this.modelIndex = modelIndex;
this.thisID = thisID;
this.dipoleInfo = dipoleInfo;
this.colix = colix;
this.mad = mad;
this.visible = visible;
this.type = 0;
}, "~N,~S,~S,~N,~N,~B");
Clazz.defineMethod (c$, "setTranslucent",
function (isTranslucent, translucentLevel) {
this.colix = org.jmol.util.Colix.getColixTranslucent3 (this.colix, isTranslucent, translucentLevel);
}, "~B,~N");
Clazz.defineMethod (c$, "set",
function (thisID, dipoleInfo, atoms, dipoleValue, mad, offsetAngstroms, offsetPercent, offsetSide, origin, vector) {
this.thisID = thisID;
this.dipoleInfo = dipoleInfo;
this.dipoleValue = dipoleValue;
this.mad = mad;
this.offsetAngstroms = offsetAngstroms;
this.offsetPercent = offsetPercent;
this.offsetSide = offsetSide;
this.vector = org.jmol.util.Vector3f.newV (vector);
this.origin = org.jmol.util.Point3f.newP (origin);
this.haveAtoms = (atoms[0] != null);
if (this.haveAtoms) {
this.atoms[0] = atoms[0];
this.atoms[1] = atoms[1];
this.centerDipole ();
} else {
this.center = null;
}}, "~S,~S,~A,~N,~N,~N,~N,~N,org.jmol.util.Point3f,org.jmol.util.Vector3f");
Clazz.defineMethod (c$, "set",
($fz = function (pt1, pt2) {
this.coords[0] = org.jmol.util.Point3f.newP (pt1);
this.coords[1] = org.jmol.util.Point3f.newP (pt2);
this.isValid = (this.coords[0].distance (this.coords[1]) > 0.1);
if (this.dipoleValue < 0) {
this.origin = org.jmol.util.Point3f.newP (pt2);
this.vector = org.jmol.util.Vector3f.newV (pt1);
this.dipoleValue = -this.dipoleValue;
} else {
this.origin = org.jmol.util.Point3f.newP (pt1);
this.vector = org.jmol.util.Vector3f.newV (pt2);
}this.dipoleInfo = "" + this.origin + this.vector;
this.vector.sub (this.origin);
if (this.dipoleValue == 0) this.dipoleValue = this.vector.length ();
else this.vector.scale (this.dipoleValue / this.vector.length ());
this.type = 1;
}, $fz.isPrivate = true, $fz), "org.jmol.util.Point3f,org.jmol.util.Point3f");
Clazz.defineMethod (c$, "set",
function (value) {
var d = this.dipoleValue;
this.dipoleValue = value;
if (value == 0) this.isValid = false;
if (this.vector == null) return;
this.vector.scale (this.dipoleValue / this.vector.length ());
if (d * this.dipoleValue < 0) this.origin.sub (this.vector);
}, "~N");
Clazz.defineMethod (c$, "set",
function (pt1, pt2, value) {
this.dipoleValue = value;
this.atoms[0] = null;
this.set (pt1, pt2);
}, "org.jmol.util.Point3f,org.jmol.util.Point3f,~N");
Clazz.defineMethod (c$, "set",
function (pt1, dipole) {
this.set (dipole.length ());
var pt2 = org.jmol.util.Point3f.newP (pt1);
pt2.add (dipole);
this.set (pt1, pt2);
this.type = 5;
}, "org.jmol.util.Point3f,org.jmol.util.Vector3f");
Clazz.defineMethod (c$, "set",
function (atom1, atom2, value) {
this.set (value);
this.set (atom1, atom2);
this.offsetSide = 0.4;
this.mad = 5;
this.atoms[0] = atom1;
this.atoms[1] = atom2;
this.haveAtoms = true;
this.centerDipole ();
}, "org.jmol.modelset.Atom,org.jmol.modelset.Atom,~N");
Clazz.defineMethod (c$, "centerDipole",
function () {
this.isValid = (this.atoms[0] !== this.atoms[1] && this.dipoleValue != 0);
if (!this.isValid) return;
var f = this.atoms[0].distance (this.atoms[1]) / (2 * this.dipoleValue) - 0.5;
this.origin.scaleAdd2 (f, this.vector, this.atoms[0]);
this.center = new org.jmol.util.Point3f ();
this.center.scaleAdd2 (0.5, this.vector, this.origin);
this.bond = this.atoms[0].getBond (this.atoms[1]);
this.type = (this.bond == null ? 2 : 3);
});
Clazz.defineMethod (c$, "isBondType",
function () {
return (this.type == 2 || this.type == 3);
});
Clazz.defineMethod (c$, "getShapeState",
function () {
if (!this.isValid) return "";
var s = new org.jmol.util.StringXBuilder ();
s.append ("dipole ID ").append (this.thisID);
if (this.haveAtoms) s.append (" ({").appendI (this.atoms[0].getIndex ()).append (" ").appendI (this.atoms[1].getIndex ()).append ("})");
else if (this.coords[0] == null) return "";
else s.append (" ").append (org.jmol.util.Escape.escapePt (this.coords[0])).append (" ").append (org.jmol.util.Escape.escapePt (this.coords[1]));
if (this.isUserValue) s.append (" value ").appendF (this.dipoleValue);
if (this.mad != 5) s.append (" width ").appendF (this.mad / 1000);
if (this.offsetAngstroms != 0) s.append (" offset ").appendF (this.offsetAngstroms);
else if (this.offsetPercent != 0) s.append (" offset ").appendI (this.offsetPercent);
if (this.offsetSide != 0.4) s.append (" offsetSide ").appendF (this.offsetSide);
if (this.noCross) s.append (" nocross");
if (!this.visible) s.append (" off");
s.append (";\n");
return s.toString ();
});
Clazz.defineStatics (c$,
"DIPOLE_TYPE_UNKNOWN", 0,
"DIPOLE_TYPE_POINTS", 1,
"DIPOLE_TYPE_ATOMS", 2,
"DIPOLE_TYPE_BOND", 3,
"DIPOLE_TYPE_MOLECULAR", 4,
"DIPOLE_TYPE_POINTVECTOR", 5);
});
| agpl-3.0 |
anandy2k1/shop | engine/Library/Zend/Amf/Parse/Resource/Stream.php | 1317 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Stream.php 23772 2011-02-28 21:35:29Z ralph $
*/
/**
* This class will convert stream resource to string by just reading it
*
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Parse_Resource_Stream
{
/**
* Parse resource into string
*
* @param resource $resource Stream resource
* @return array
*/
public function parse($resource) {
return stream_get_contents($resource);
}
}
| agpl-3.0 |
errordeveloper/fe-devel | Native/Core/OCL/Debug.cpp | 210 | /*
* Copyright 2010-2012 Fabric Engine Inc. All rights reserved.
*/
#include "Debug.h"
#if defined(FABRIC_BUILD_DEBUG)
namespace Fabric
{
namespace OCL
{
bool gDebugEnabled = false;
};
};
#endif
| agpl-3.0 |
juju/juju | featuretests/cloudimagemetadata_test.go | 2241 | // Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package featuretests
import (
"github.com/juju/errors"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"github.com/juju/juju/api/imagemetadatamanager"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/juju/testing"
"github.com/juju/juju/mongo"
"github.com/juju/juju/rpc"
)
type cloudImageMetadataSuite struct {
testing.JujuConnSuite
client *imagemetadatamanager.Client
}
func (s *cloudImageMetadataSuite) SetUpTest(c *gc.C) {
s.JujuConnSuite.SetUpTest(c)
s.client = imagemetadatamanager.NewClient(s.APIState)
c.Assert(s.client, gc.NotNil)
s.AddCleanup(func(*gc.C) {
s.client.ClientFacade.Close()
})
}
func (s *cloudImageMetadataSuite) TestSaveAndFindAndDeleteMetadata(c *gc.C) {
metadata, err := s.client.List("", "", nil, nil, "", "")
c.Assert(errors.Cause(err), gc.DeepEquals, &rpc.RequestError{
Message: "matching cloud image metadata not found",
Code: "not found",
})
c.Assert(metadata, gc.HasLen, 0)
// check db too
conn := s.State.MongoSession()
coll, closer := mongo.CollectionFromName(conn.DB("juju"), "cloudimagemetadata")
defer closer()
before, err := coll.Count()
c.Assert(err, jc.ErrorIsNil)
c.Assert(before == 0, jc.IsTrue)
imageId := "1"
m := params.CloudImageMetadata{
Source: "custom",
Stream: "stream",
Region: "region",
Series: "trusty",
Arch: "arch",
VirtType: "virtType",
RootStorageType: "rootStorageType",
ImageId: imageId,
Priority: 50,
}
err = s.client.Save([]params.CloudImageMetadata{m})
c.Assert(err, jc.ErrorIsNil)
added, err := s.client.List("", "", nil, nil, "", "")
c.Assert(err, jc.ErrorIsNil)
// m.Version would be deduced from m.Series
m.Version = "14.04"
c.Assert(added, jc.DeepEquals, []params.CloudImageMetadata{m})
// make sure it's in db too
after, err := coll.Count()
c.Assert(err, jc.ErrorIsNil)
c.Assert(after == 1, jc.IsTrue)
err = s.client.Delete(imageId)
c.Assert(err, jc.ErrorIsNil)
// make sure it's no longer in db too
afterDelete, err := coll.Count()
c.Assert(err, jc.ErrorIsNil)
c.Assert(afterDelete, gc.Equals, 0)
}
| agpl-3.0 |
k10r/shopware | engine/Library/Enlight/Collection/ArrayCollection.php | 5653 | <?php
/**
* Enlight
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://enlight.de/license
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@shopware.de so we can send you a copy immediately.
*
* @category Enlight
* @package Enlight_Collection
* @copyright Copyright (c) 2011, shopware AG (http://www.shopware.de)
* @license http://enlight.de/license New BSD License
* @version $Id$
* @author $Author$
*/
/**
* Interface allows an easy implementation for the Countable, IteratorAggregate, ArrayAccess class
*
* Array collection class which implements the Enlight_Collection_Collection interface.
* The interface allows an easy implementation for the Countable, IteratorAggregate, ArrayAccess class.
*
* @category Enlight
* @package Enlight_Collection
* @copyright Copyright (c) 2011, shopware AG (http://www.shopware.de)
* @license http://enlight.de/license New BSD License
*/
class Enlight_Collection_ArrayCollection implements Enlight_Collection_Collection
{
/**
* This property contains all added elements.
*
* @var array
*/
protected $_elements;
/**
* Constructor method
* Expects an array as a parameter with default elements.
*
* @param array $elements
*/
public function __construct($elements = array())
{
$this->_elements = (array) $elements;
}
/**
* Counts the stored items.
*
* @return int
*/
public function count()
{
return count($this->_elements);
}
/**
* Sets a value of an element in the list.
*
* @param string $key
* @param mixed $value
* @return Enlight_Collection_ArrayCollection
*/
public function set($key, $value)
{
$this->_elements[$key] = $value;
return $this;
}
/**
* Returns a value of an element in the list.
*
* @param string $key
* @return mixed
*/
public function get($key)
{
return isset($this->_elements[$key]) ? $this->_elements[$key] : null;
}
/**
* Checks whether an element with a given name is stored.
*
* @param string $key
* @return bool
*/
public function containsKey($key)
{
return array_key_exists($key, $this->_elements);
}
/**
* Deletes an item from the list.
*
* @param string $key
* @return Enlight_Collection_ArrayCollection
*/
public function remove($key)
{
unset($this->_elements[$key]);
return $this;
}
/**
* Checks whether an element with a given name is stored.
*
* @param string $key
* @return bool
*/
public function offsetExists($key)
{
return $this->containsKey($key);
}
/**
* Deletes an item from the list.
*
* @param unknown_type $key
*/
public function offsetUnset($key)
{
$this->remove($key);
}
/**
* Returns a value of an element in the list.
*
* @param string $key
* @return mixed
*/
public function offsetGet($key)
{
return $this->get($key);
}
/**
* Sets a value of an element in the list.
*
* @param string $key
* @param mixed $value
*/
public function offsetSet($key, $value)
{
$this->set($key, $value);
}
/**
* Returns the iterator instance for the list.
*
* @return Iterator
*/
public function getIterator()
{
$ref = &$this->_elements;
return new ArrayIterator($ref);
}
/**
* Sets a value of an element in the list.
*
* @param string $key
* @param mixed $value
*/
public function __set($key, $value = null)
{
$this->set($key, $value);
}
/**
* Returns a value of an element in the list.
*
* @param string $key
* @return mixed
*/
public function __get($key)
{
return $this->get($key);
}
/**
* Checks whether an element with a given name is stored.
*
* @param string $key
* @return bool
*/
public function __isset($key)
{
return $this->containsKey($key);
}
/**
* Deletes an item from the list.
*
* @param string $key
* @return Enlight_Collection_ArrayCollection
*/
public function __unset($key)
{
$this->remove($key);
}
/**
* Captures the magic phone calls and executes them accordingly.
*
* @param string $name
* @param array $args
* @return mixed
*/
public function __call($name, $args = null)
{
switch (substr($name, 0, 3)) {
case 'get':
$key = strtolower(substr($name, 3, 1)) . substr($name, 4);
$key = strtolower(preg_replace('/([A-Z])/', '_$0', $key));
return $this->get($key);
case 'set':
$key = strtolower(substr($name, 3, 1)) . substr($name, 4);
$key = strtolower(preg_replace('/([A-Z])/', '_$0', $key));
return $this->set($key, isset($args[0]) ? $args[0] : null);
default:
throw new Enlight_Exception(
'Method "' . get_class($this) . '::' . $name . '" not found failure',
Enlight_Exception::METHOD_NOT_FOUND
);
}
}
}
| agpl-3.0 |
AyuntamientoMadrid/consul | db/migrate/20190307165132_remove_question_and_external_url_from_proposals.rb | 204 | class RemoveQuestionAndExternalUrlFromProposals < ActiveRecord::Migration[4.2]
def change
remove_column :proposals, :question, :string
remove_column :proposals, :external_url, :string
end
end
| agpl-3.0 |
takeit/web-renderer | src/SWP/Bundle/WebhookBundle/Model/WebhookInterface.php | 836 | <?php
declare(strict_types=1);
/*
* This file is part of the Superdesk Web Publisher Webhook Bundle.
*
* Copyright 2017 Sourcefabric z.ú. and contributors.
*
* For the full copyright and license information, please see the
* AUTHORS and LICENSE files distributed with this source code.
*
* @copyright 2017 Sourcefabric z.ú
* @license http://www.superdesk.org/license
*/
namespace SWP\Bundle\WebhookBundle\Model;
use SWP\Component\Storage\Model\PersistableInterface;
use SWP\Component\Webhook\Model\WebhookInterface as BaseWebhookInterface;
/**
* Interface WebhookInterface.
*/
interface WebhookInterface extends BaseWebhookInterface, PersistableInterface
{
/**
* @return int
*/
public function getId();
public function getEvents(): array;
public function setEvents(array $events): void;
}
| agpl-3.0 |
KadJ/amazon_new | modules/AOS_Products/metadata/detailviewdefs.php | 2506 | <?php
$module_name = 'AOS_Products';
$viewdefs [$module_name] =
array (
'DetailView' =>
array (
'templateMeta' =>
array (
'form' =>
array (
'buttons' =>
array (
0 => 'EDIT',
1 => 'DUPLICATE',
2 => 'DELETE',
),
),
'maxColumns' => '2',
'widths' =>
array (
0 =>
array (
'label' => '10',
'field' => '30',
),
1 =>
array (
'label' => '10',
'field' => '30',
),
),
'useTabs' => false,
'tabDefs' =>
array (
'DEFAULT' =>
array (
'newTab' => false,
'panelDefault' => 'expanded',
),
),
),
'panels' =>
array (
'default' =>
array (
0 =>
array (
0 =>
array (
'name' => 'name',
'label' => 'LBL_NAME',
),
1 =>
array (
'name' => 'maincode',
'label' => 'LBL_MAINCODE',
),
),
1 =>
array (
0 =>
array (
'name' => 'part_number',
'label' => 'LBL_PART_NUMBER',
),
1 =>
array (
'name' => 'category',
'label' => 'LBL_CATEGORY',
),
),
2 =>
array (
0 =>
array (
'name' => 'url',
'label' => 'LBL_URL',
),
1 =>
array (
'name' => 'type',
'label' => 'LBL_TYPE',
),
),
3 =>
array (
0 =>
array (
'name' => 'cost',
'label' => 'LBL_COST',
),
1 =>
array (
'name' => 'price',
'label' => 'LBL_PRICE',
),
),
4 =>
array (
0 =>
array (
'name' => 'contact',
'label' => 'LBL_CONTACT',
),
),
5 =>
array (
0 =>
array (
'name' => 'description',
'label' => 'LBL_DESCRIPTION',
),
),
6 =>
array (
0 =>
array (
'name' => 'product_image',
'label' => 'LBL_PRODUCT_IMAGE',
'customCode' => '<img src="{$fields.product_image.value}"/>',
),
),
),
),
),
);
?>
| agpl-3.0 |
t0mk/python-stdnum | stdnum/be/vat.py | 2332 | # vat.py - functions for handling Belgian VAT numbers
#
# Copyright (C) 2012, 2013 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""BTW, TVA, NWSt (Belgian VAT number).
>>> compact('BE403019261')
'0403019261'
>>> compact('(0)403019261')
'0403019261'
>>> validate('BE 428759497')
'0428759497'
>>> validate('BE431150351')
Traceback (most recent call last):
...
InvalidChecksum: ...
"""
from stdnum.exceptions import *
from stdnum.util import clean
def compact(number):
"""Convert the number to the minimal representation. This strips the
number of any valid separators and removes surrounding whitespace."""
number = clean(number, ' -./').upper().strip()
if number.startswith('BE'):
number = number[2:]
if number.startswith('(0)'):
number = '0' + number[3:]
if len(number) == 9:
number = '0' + number # old format had 9 digits
return number
def checksum(number):
"""Calculate the checksum."""
return (int(number[:-2]) + int(number[-2:])) % 97
def validate(number):
"""Checks to see if the number provided is a valid VAT number. This checks
the length, formatting and check digit."""
number = compact(number)
if not number.isdigit():
raise InvalidFormat()
if len(number) != 10:
raise InvalidLength()
if checksum(number) != 0:
raise InvalidChecksum()
return number
def is_valid(number):
"""Checks to see if the number provided is a valid VAT number. This checks
the length, formatting and check digit."""
try:
return bool(validate(number))
except ValidationError:
return False
| lgpl-2.1 |
Radi0actvChickn/Polyglot-Trait-Extension | src/polyglot/types/UnavailableTypeException.java | 2409 | /*******************************************************************************
* This file is part of the Polyglot extensible compiler framework.
*
* Copyright (c) 2000-2012 Polyglot project group, Cornell University
* Copyright (c) 2006-2012 IBM Corporation
* All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License v1.0 which accompanies this
* distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* This program and the accompanying materials are made available under
* the terms of the Lesser GNU Public License v2.0 which accompanies this
* distribution.
*
* The development of the Polyglot project has been supported by a
* number of funding sources, including DARPA Contract F30602-99-1-0533,
* monitored by USAF Rome Laboratory, ONR Grants N00014-01-1-0968 and
* N00014-09-1-0652, NSF Grants CNS-0208642, CNS-0430161, CCF-0133302,
* and CCF-1054172, AFRL Contract FA8650-10-C-7022, an Alfred P. Sloan
* Research Fellowship, and an Intel Research Ph.D. Fellowship.
*
* See README for contributors.
******************************************************************************/
package polyglot.types;
import polyglot.frontend.Job;
import polyglot.frontend.SchedulerException;
import polyglot.util.Position;
import polyglot.util.SerialVersionUID;
/**
* An {@code UnavailableTypeException} is an exception thrown when a type
* object is not in a required state to continue a pass.
*
* @author nystrom
*/
public class UnavailableTypeException extends SchedulerException {
private static final long serialVersionUID = SerialVersionUID.generate();
protected Job job;
protected Position position;
/**
* @param job
* @param fullName
*/
public UnavailableTypeException(Job job, String fullName) {
this(job, fullName, null);
}
/**
* @param job
* @param fullName
* @param position
*/
public UnavailableTypeException(Job job, String fullName, Position position) {
super(fullName);
this.job = job;
this.position = position;
}
public UnavailableTypeException(ParsedTypeObject ct) {
this(ct.job(), ct.fullName(), ct.position());
}
public Job job() {
return job;
}
public Position position() {
return position;
}
}
| lgpl-2.1 |
celements/celements-structuredDataEditor | web-module/src/main/webapp/resources/structEditJS/select2/i18n/sr.js | 986 | /*! Select2 4.1.0-beta.1 | https://github.com/select2/select2/blob/master/LICENSE.md */
!function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var n=jQuery.fn.select2.amd;n.define("select2/i18n/sr",[],function(){function n(n,e,r,t){return n%10==1&&n%100!=11?e:n%10>=2&&n%10<=4&&(n%100<12||n%100>14)?r:t}return{errorLoading:function(){return"Preuzimanje nije uspelo."},inputTooLong:function(e){var r=e.input.length-e.maximum,t="Obrišite "+r+" simbol";return t+=n(r,"","a","a")},inputTooShort:function(e){var r=e.minimum-e.input.length,t="Ukucajte bar još "+r+" simbol";return t+=n(r,"","a","a")},loadingMore:function(){return"Preuzimanje još rezultata…"},maximumSelected:function(e){var r="Možete izabrati samo "+e.maximum+" stavk";return r+=n(e.maximum,"u","e","i")},noResults:function(){return"Ništa nije pronađeno"},searching:function(){return"Pretraga…"},removeAllItems:function(){return"Уклоните све ставке"}}}),n.define,n.require}(); | lgpl-2.1 |
soul2zimate/wildfly-core | server/src/test/java/org/jboss/as/server/test/InterfaceManagementUnitTestCase.java | 24763 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.server.test;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ANY_ADDRESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.jboss.as.controller.AbstractControllerService;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ControlledProcessState;
import org.jboss.as.controller.DelegatingResourceDefinition;
import org.jboss.as.controller.ExpressionResolver;
import org.jboss.as.controller.ManagementModel;
import org.jboss.as.controller.ModelController;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.ProcessType;
import org.jboss.as.controller.ResourceDefinition;
import org.jboss.as.controller.RunningMode;
import org.jboss.as.controller.RunningModeControl;
import org.jboss.as.controller.access.management.DelegatingConfigurableAuthorizer;
import org.jboss.as.controller.access.management.ManagementSecurityIdentitySupplier;
import org.jboss.as.controller.audit.AuditLogger;
import org.jboss.as.controller.CapabilityRegistry;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.extension.ExtensionRegistry;
import org.jboss.as.controller.extension.RuntimeHostControllerInfoAccessor;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.as.controller.persistence.AbstractConfigurationPersister;
import org.jboss.as.controller.persistence.ConfigurationPersistenceException;
import org.jboss.as.controller.persistence.ModelMarshallingContext;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.controller.resource.InterfaceDefinition;
import org.jboss.as.controller.services.path.PathManagerService;
import org.jboss.as.repository.ContentReference;
import org.jboss.as.repository.ContentRepository;
import org.jboss.as.repository.DeploymentFileRepository;
import org.jboss.as.server.ServerEnvironment;
import org.jboss.as.server.Services;
import org.jboss.as.server.controller.resources.ServerRootResourceDefinition;
import org.jboss.as.server.parsing.StandaloneXml;
import org.jboss.as.server.services.net.NetworkInterfaceService;
import org.jboss.as.version.ProductConfig;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.modules.Module;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.staxmapper.XMLElementWriter;
import org.jboss.vfs.VirtualFile;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Basic server controller unit test.
*
* @author Emanuel Muckenhuber
*/
public class InterfaceManagementUnitTestCase {
private final ServiceContainer container = ServiceContainer.Factory.create();
private ModelController controller;
private volatile boolean dependentStarted;
@Before
public void before() throws Exception {
dependentStarted = false;
final ServiceTarget target = container.subTarget();
final ExtensionRegistry extensionRegistry =
new ExtensionRegistry(ProcessType.STANDALONE_SERVER, new RunningModeControl(RunningMode.NORMAL), null, null, null, RuntimeHostControllerInfoAccessor.SERVER);
final StringConfigurationPersister persister = new StringConfigurationPersister(Collections.<ModelNode>emptyList(), new StandaloneXml(null, null, extensionRegistry));
extensionRegistry.setWriterRegistry(persister);
final ControlledProcessState processState = new ControlledProcessState(true);
final ModelControllerService svc = new ModelControllerService(processState, persister, new ServerDelegatingResourceDefinition());
final ServiceBuilder<ModelController> builder = target.addService(Services.JBOSS_SERVER_CONTROLLER, svc);
builder.install();
// Create demand for the ON_DEMAND interface service we'll be adding so we can validate what happens in start()
Service<Void> dependentService = new Service<Void>() {
@Override
public void start(StartContext context) throws StartException {
dependentStarted = true;
}
@Override
public void stop(StopContext context) {
dependentStarted = false;
}
@Override
public Void getValue() throws IllegalStateException, IllegalArgumentException {
return null;
}
};
final ServiceBuilder sb = target.addService(ServiceName.JBOSS.append("interface", "management", "test", "case", "dependent"), dependentService);
sb.requires(NetworkInterfaceService.JBOSS_NETWORK_INTERFACE.append("test"));
ServiceController<Void> dependentController = sb.install();
svc.latch.await(20, TimeUnit.SECONDS);
this.controller = svc.getValue();
container.awaitStability(20, TimeUnit.SECONDS);
Assert.assertTrue(dependentController.getState() == ServiceController.State.DOWN
&& dependentController.getUnavailableDependencies().size() > 0);
}
@After
public void after() {
container.shutdown();
}
@Test
public void testInterfacesAlternatives() throws IOException {
final ModelControllerClient client = controller.createClient(Executors.newCachedThreadPool());
final ModelNode base = new ModelNode();
base.get(ModelDescriptionConstants.OP).set("add");
base.get(ModelDescriptionConstants.OP_ADDR).add("interface", "test");
{
// any-address is not valid with the normal criteria
final ModelNode operation = base.clone();
operation.get(ANY_ADDRESS).set(true);
populateCritieria(operation, Nesting.TOP);
executeForNonServiceFailure(client, operation);
}
// Disabled. See https://github.com/wildfly/wildfly-core/commit/ae0ca95c42b481ef519246b9a6eab2b50c48472e
// {
// // AS7-2685 had a notion of disallowing LOOPBACK and LINK_LOCAL_ADDRESS
// final ModelNode operation = base.clone();
// populateCritieria(operation, Nesting.TOP, InterfaceDefinition.LOOPBACK, InterfaceDefinition.LINK_LOCAL_ADDRESS);
// executeForNonServiceFailure(client, operation);
// }
{
// The full set of normal criteria is ok, although it won't resolve properly
final ModelNode operation = base.clone();
populateCritieria(operation, Nesting.TOP);
executeForServiceFailure(client, operation);
}
}
@Test
public void testUpdateInterface() throws IOException {
final ModelControllerClient client = controller.createClient(Executors.newCachedThreadPool());
final ModelNode address = new ModelNode();
address.add("interface", "test");
{
final ModelNode operation = new ModelNode();
operation.get(ModelDescriptionConstants.OP).set("add");
operation.get(ModelDescriptionConstants.OP_ADDR).set(address);
operation.get(ANY_ADDRESS).set(true);
executeForResult(client, operation);
final ModelNode resource = readResource(client, operation.get(ModelDescriptionConstants.OP_ADDR));
Assert.assertTrue(resource.get(ANY_ADDRESS).asBoolean());
}
{
final ModelNode composite = new ModelNode();
composite.get(ModelDescriptionConstants.OP).set("composite");
composite.get(ModelDescriptionConstants.OP_ADDR).setEmptyList();
final ModelNode one = composite.get(ModelDescriptionConstants.STEPS).add();
one.get(ModelDescriptionConstants.OP).set("write-attribute");
one.get(ModelDescriptionConstants.OP_ADDR).set(address);
one.get(ModelDescriptionConstants.NAME).set(ANY_ADDRESS);
one.get(ModelDescriptionConstants.VALUE);
final ModelNode two = composite.get(ModelDescriptionConstants.STEPS).add();
two.get(ModelDescriptionConstants.OP).set("write-attribute");
two.get(ModelDescriptionConstants.OP_ADDR).set(address);
two.get(ModelDescriptionConstants.NAME).set("inet-address");
two.get(ModelDescriptionConstants.VALUE).set("127.0.0.1");
executeForResult(client, composite);
final ModelNode resource = readResource(client, address);
Assert.assertFalse(resource.hasDefined(ANY_ADDRESS));
Assert.assertEquals("127.0.0.1", resource.get("inet-address").asString());
}
}
@Test
public void testComplexInterface() throws IOException {
final ModelNode operation = new ModelNode();
operation.get(ModelDescriptionConstants.OP).set("add");
operation.get(ModelDescriptionConstants.OP_ADDR).add("interface", "test");
// This won't be resolvable with the runtime layer enabled
populateCritieria(operation, Nesting.TOP,
InterfaceDefinition.LOOPBACK);
populateCritieria(operation.get("not"), Nesting.NOT,
InterfaceDefinition.PUBLIC_ADDRESS,
InterfaceDefinition.LINK_LOCAL_ADDRESS,
InterfaceDefinition.SITE_LOCAL_ADDRESS,
InterfaceDefinition.VIRTUAL,
InterfaceDefinition.UP,
InterfaceDefinition.MULTICAST,
InterfaceDefinition.LOOPBACK_ADDRESS,
InterfaceDefinition.POINT_TO_POINT);
populateCritieria(operation.get("any"), Nesting.ANY);
final ModelControllerClient client = controller.createClient(Executors.newCachedThreadPool());
executeForServiceFailure(client, operation);
}
protected void populateCritieria(final ModelNode model, final Nesting nesting, final AttributeDefinition...excluded) {
Set<AttributeDefinition> excludedCriteria = new HashSet<AttributeDefinition>(Arrays.asList(excluded));
for(final AttributeDefinition def : InterfaceDefinition.NESTED_ATTRIBUTES) {
if (excludedCriteria.contains(def)) {
continue;
}
final ModelNode node = model.get(def.getName());
if(def.getType() == ModelType.BOOLEAN) {
node.set(true);
} else if (def == InterfaceDefinition.INET_ADDRESS || def == InterfaceDefinition.LOOPBACK_ADDRESS) {
if (nesting == Nesting.ANY && def == InterfaceDefinition.INET_ADDRESS) {
node.add("127.0.0.1");
} else if (nesting == Nesting.NOT && def == InterfaceDefinition.INET_ADDRESS) {
node.add("10.0.0.1");
} else {
node.set("127.0.0.1");
}
} else if (def == InterfaceDefinition.NIC || def == InterfaceDefinition.NIC_MATCH) {
if (nesting == Nesting.ANY) {
node.add("lo");
} else if (nesting == Nesting.NOT) {
node.add("en3");
} else {
node.set("lo");
}
} else if (def == InterfaceDefinition.SUBNET_MATCH) {
if (nesting == Nesting.ANY) {
node.add("127.0.0.1/24");
} else if (nesting == Nesting.NOT) {
node.add("10.0.0.1/24");
} else {
node.set("127.0.0.0/24");
}
}
}
}
private static class ModelControllerService extends AbstractControllerService {
final CountDownLatch latch = new CountDownLatch(1);
final StringConfigurationPersister persister;
final ControlledProcessState processState;
final ServerDelegatingResourceDefinition rootResourceDefinition;
final ServerEnvironment environment;
final ExtensionRegistry extensionRegistry;
final CapabilityRegistry capabilityRegistry;
volatile ManagementResourceRegistration rootRegistration;
volatile Exception error;
ModelControllerService(final ControlledProcessState processState, final StringConfigurationPersister persister, final ServerDelegatingResourceDefinition rootResourceDefinition) {
super(ProcessType.EMBEDDED_SERVER, new RunningModeControl(RunningMode.ADMIN_ONLY), persister, processState, rootResourceDefinition, null, ExpressionResolver.TEST_RESOLVER,
AuditLogger.NO_OP_LOGGER, new DelegatingConfigurableAuthorizer(), new ManagementSecurityIdentitySupplier(), new CapabilityRegistry(true));
this.persister = persister;
this.processState = processState;
this.rootResourceDefinition = rootResourceDefinition;
Properties properties = new Properties();
properties.put("jboss.home.dir", System.getProperty("basedir", ".") + File.separatorChar + "target");
final String hostControllerName = "hostControllerName"; // Host Controller name may not be null when in a managed domain
environment = new ServerEnvironment(hostControllerName, properties, new HashMap<String, String>(), null, null,
ServerEnvironment.LaunchType.DOMAIN, null, ProductConfig.fromFilesystemSlot(Module.getBootModuleLoader(), ".", properties), false);
extensionRegistry =
new ExtensionRegistry(ProcessType.STANDALONE_SERVER, new RunningModeControl(RunningMode.NORMAL), null, null, null, RuntimeHostControllerInfoAccessor.SERVER);
capabilityRegistry = new CapabilityRegistry(processType.isServer());
}
@Override
protected void initModel(ManagementModel managementModel, Resource modelControllerResource) {
this.rootRegistration = managementModel.getRootResourceRegistration();
}
@Override
protected boolean boot(List<ModelNode> bootOperations, boolean rollbackOnRuntimeFailure) throws ConfigurationPersistenceException {
try {
return super.boot(persister.bootOperations, rollbackOnRuntimeFailure);
} catch (Exception e) {
error = e;
} catch (Throwable t) {
error = new Exception(t);
} finally {
latch.countDown();
}
return false;
}
@Override
public void start(StartContext context) throws StartException {
rootResourceDefinition.setDelegate(new ServerRootResourceDefinition(MockRepository.INSTANCE,
persister, environment, processState, null, extensionRegistry, false, MOCK_PATH_MANAGER, null,
authorizer, securityIdentitySupplier, AuditLogger.NO_OP_LOGGER, getMutableRootResourceRegistrationProvider(), getBootErrorCollector(), capabilityRegistry));
super.start(context);
}
}
static final class ServerDelegatingResourceDefinition extends DelegatingResourceDefinition {
@Override
public void setDelegate(ResourceDefinition delegate) {
super.setDelegate(delegate);
}
}
static class StringConfigurationPersister extends AbstractConfigurationPersister {
private final List<ModelNode> bootOperations;
volatile String marshalled;
public StringConfigurationPersister(List<ModelNode> bootOperations, XMLElementWriter<ModelMarshallingContext> rootDeparser) {
super(rootDeparser);
this.bootOperations = bootOperations;
}
@Override
public PersistenceResource store(ModelNode model, Set<PathAddress> affectedAddresses)
throws ConfigurationPersistenceException {
return new StringPersistenceResource(model, this);
}
@Override
public List<ModelNode> load() throws ConfigurationPersistenceException {
return bootOperations;
}
private class StringPersistenceResource implements PersistenceResource {
private byte[] bytes;
private final AbstractConfigurationPersister persister;
StringPersistenceResource(final ModelNode model, final AbstractConfigurationPersister persister) throws ConfigurationPersistenceException {
this.persister = persister;
ByteArrayOutputStream output = new ByteArrayOutputStream(1024 * 8);
try {
try {
persister.marshallAsXml(model, output);
} finally {
try {
output.close();
} catch (Exception ignore) {
}
bytes = output.toByteArray();
}
} catch (Exception e) {
throw new ConfigurationPersistenceException("Failed to marshal configuration", e);
}
}
@Override
public void commit() {
StringConfigurationPersister.this.marshalled = new String(bytes, StandardCharsets.UTF_8);
}
@Override
public void rollback() {
marshalled = null;
}
}
}
static ModelNode readResource(final ModelControllerClient client, final ModelNode address) {
final ModelNode operation = new ModelNode();
operation.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION);
operation.get(ModelDescriptionConstants.OP_ADDR).set(address);
return executeForResult(client, operation);
}
/**
* Assert that the operation failed, but not with the failure message that indicates a service start problem.
* Use this to check that problems that should be detected in the OSH and not in the service are properly
* detected.
*
* @param client the client to use to execute the operation
* @param operation the operation to execute
*/
private static void executeForNonServiceFailure(final ModelControllerClient client, final ModelNode operation) {
try {
final ModelNode result = client.execute(operation);
if (! result.hasDefined("outcome") && ! ModelDescriptionConstants.FAILED.equals(result.get("outcome").asString())) {
Assert.fail("Operation outcome is " + result.get("outcome").asString());
}
System.out.println("Failure for " + operation + "\n is:\n" + result);
Assert.assertFalse(result.toString(), result.get(ModelDescriptionConstants.FAILURE_DESCRIPTION).toString().contains(ControllerLogger.MGMT_OP_LOGGER.failedServices()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Assert that the operation failed, but only with the failure message that indicates a service start problem.
* Use this for instead of executeFoResult in tests that use criteria that may not be resolvable on a real machine,
* but which are not explicitly disallowed in the model. The inability to resolve a matching interface will lead to the service start problem.
*
* @param client the client to use to execute the operation
* @param operation the operation to execute
*/
private void executeForServiceFailure(final ModelControllerClient client, final ModelNode operation) {
try {
final ModelNode result = client.execute(operation);
if (result.hasDefined(OUTCOME) && ! ModelDescriptionConstants.FAILED.equals(result.get(OUTCOME).asString())) {
// The dependent service we add in before() should have demanded the ON_DEMAND interface service.
// And that should have failed start. So if the op succeeded but didn't start the dependent, that's
// a clue as to why the op succeeded; i.e. the demand didn't get picked up. This is basically
// a diagnostic for WFCORE-2630
Assert.assertTrue("Adding interface service did not trigger start of dependent service", dependentStarted);
// If we get here the interface service must have started when it shouldn't have
Assert.fail("Operation outcome is " + result.get(OUTCOME).asString());
}
System.out.println("Failure for " + operation + "\n is:\n" + result);
Assert.assertTrue(result.toString(), result.get(ModelDescriptionConstants.FAILURE_DESCRIPTION).toString().contains(ControllerLogger.MGMT_OP_LOGGER.failedServices()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static ModelNode executeForResult(final ModelControllerClient client, final ModelNode operation) {
try {
final ModelNode result = client.execute(operation);
if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) {
return result.get("result");
} else {
Assert.fail("Operation outcome is " + result.get("outcome").asString() + " " + result.get("failure-description"));
throw new RuntimeException(); // not reached
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static final class MockRepository implements ContentRepository, DeploymentFileRepository {
static MockRepository INSTANCE = new MockRepository();
@Override
public File[] getDeploymentFiles(ContentReference reference) {
return null;
}
@Override
public File getDeploymentRoot(ContentReference reference) {
return null;
}
@Override
public void deleteDeployment(ContentReference reference) {
}
@Override
public byte[] addContent(InputStream stream) throws IOException {
return null;
}
@Override
public boolean syncContent(ContentReference reference) {
return hasContent(reference.getHash());
}
@Override
public VirtualFile getContent(byte[] hash) {
return null;
}
@Override
public boolean hasContent(byte[] hash) {
return false;
}
@Override
public void removeContent(ContentReference reference) {
}
@Override
public void addContentReference(ContentReference reference) {
}
@Override
public Map<String, Set<String>> cleanObsoleteContent() {
return null;
}
}
private static PathManagerService MOCK_PATH_MANAGER = new PathManagerService() {
};
private enum Nesting {
TOP,
ANY,
NOT
}
}
| lgpl-2.1 |
platosinski/EntityAudit | tests/SimpleThings/Tests/EntityAudit/Fixtures/Issue/Issue156Contact.php | 2012 | <?php
/**
* Created by PhpStorm.
* User: david
* Date: 23/02/2016
* Time: 15:57
*/
namespace SimpleThings\EntityAudit\Tests\Fixtures\Issue;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Issue156Contact
* @package SimpleThings\EntityAudit\Tests\Fixtures\Issue
* @ORM\Entity()
* @ORM\InheritanceType("SINGLE_TABLE")
* @ORM\DiscriminatorColumn(name="discriminator", type="string")
*/
class Issue156Contact
{
/** @var int @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */
protected $id;
/**
* @var ArrayCollection|Issue156ContactTelephoneNumber[]
* ORM\OneToMany(targetEntity="Issue156ContactTelephoneNumber", mappedBy="contact")
*/
protected $telephoneNumbers;
public function __construct()
{
$this->telephoneNumbers = new ArrayCollection();
}
/**
* @param int $id
* @return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param Issue156ContactTelephoneNumber $telephoneNumber
* @return $this
*/
public function addTelephoneNumber(Issue156ContactTelephoneNumber $telephoneNumber)
{
if (!$this->telephoneNumbers->contains($telephoneNumber)) {
$telephoneNumber->setContact($this);
$this->telephoneNumbers[] = $telephoneNumber;
}
return $this;
}
/**
* @param Issue156ContactTelephoneNumber $telephoneNumber
* @return $this
*/
public function removeTelephoneNumber(Issue156ContactTelephoneNumber $telephoneNumber)
{
$this->telephoneNumbers->removeElement($telephoneNumber);
return $this;
}
/**
* @return ArrayCollection|Issue156ContactTelephoneNumber[]
*/
public function getTelephoneNumbers()
{
return $this->telephoneNumbers;
}
}
| lgpl-2.1 |
maui-packages/qt-creator | src/plugins/perforce/annotationhighlighter.cpp | 2025 | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "annotationhighlighter.h"
namespace Perforce {
namespace Internal {
PerforceAnnotationHighlighter::PerforceAnnotationHighlighter(const ChangeNumbers &changeNumbers,
QTextDocument *document) :
VcsBase::BaseAnnotationHighlighter(changeNumbers, document),
m_colon(QLatin1Char(':'))
{
}
QString PerforceAnnotationHighlighter::changeNumber(const QString &block) const
{
const int pos = block.indexOf(m_colon);
return pos > 1 ? block.left(pos) : QString();
}
} // Internal
} // Perforce
| lgpl-2.1 |
gabriel-ozeas/knoma-djatoka | src/gov/lanl/adore/djatoka/ICompress.java | 3364 | /*
* Copyright (c) 2008 Los Alamos National Security, LLC.
*
* Los Alamos National Laboratory
* Research Library
* Digital Library Research & Prototyping Team
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package gov.lanl.adore.djatoka;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Abstract compression interface. Allows use of common input method
* (e.g. String path, InputStream, BufferedImage) and output methods. The
* underlying implementations are responsible for handling these variants.
* @author Ryan Chute
*
*/
public interface ICompress {
/**
* Compress input using provided DjatokaEncodeParam parameters.
* @param input absolute file path for input file.
* @param output absolute file path for output file.
* @param params DjatokaEncodeParam containing compression parameters.
* @throws DjatokaException
*/
public void compressImage(String input, String output,
DjatokaEncodeParam params) throws DjatokaException;
/**
* Compress input using provided DjatokaEncodeParam parameters.
* @param input InputStream containing image bitstream
* @param output absolute file path for output file.
* @param params DjatokaEncodeParam containing compression parameters.
* @throws DjatokaException
*/
public void compressImage(InputStream input, String output,
DjatokaEncodeParam params) throws DjatokaException;
/**
* Compress input using provided DjatokaEncodeParam parameters.
* @param input InputStream containing image bitstream
* @param output OutputStream to serialize compressed image.
* @param params DjatokaEncodeParam containing compression parameters.
* @throws DjatokaException
*/
public void compressImage(InputStream input, OutputStream output,
DjatokaEncodeParam params) throws DjatokaException;
/**
* Compress input BufferedImage using provided DjatokaEncodeParam parameters.
* @param bi in-memory image to be compressed
* @param output OutputStream to serialize compressed image.
* @param params DjatokaEncodeParam containing compression parameters.
* @throws DjatokaException
*/
public void compressImage(BufferedImage bi, OutputStream output,
DjatokaEncodeParam params) throws DjatokaException;
/**
* Compress input BufferedImage using provided DjatokaEncodeParam parameters.
* @param bi in-memory image to be compressed
* @param output absolute file path for output file.
* @param params DjatokaEncodeParam containing compression parameters.
* @throws DjatokaException
*/
public void compressImage(BufferedImage bi, String output,
DjatokaEncodeParam params) throws DjatokaException;
} | lgpl-2.1 |
MeinAccount/WCF | wcfsetup/install/files/lib/form/EmailActivationForm.class.php | 3468 | <?php
namespace wcf\form;
use wcf\data\user\User;
use wcf\data\user\UserAction;
use wcf\system\event\EventHandler;
use wcf\system\exception\IllegalLinkException;
use wcf\system\exception\NamedUserException;
use wcf\system\exception\UserInputException;
use wcf\system\request\LinkHandler;
use wcf\system\WCF;
use wcf\util\HeaderUtil;
use wcf\util\UserUtil;
/**
* Shows the email activation form.
*
* @author Marcel Werk
* @copyright 2001-2015 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package com.woltlab.wcf
* @subpackage form
* @category Community Framework
*/
class EmailActivationForm extends AbstractForm {
/**
* user id
* @var integer
*/
public $userID = null;
/**
* activation code
* @var integer
*/
public $activationCode = '';
/**
* User object
* @var \wcf\data\user\User
*/
public $user = null;
/**
* @see \wcf\page\IPage::readParameters()
*/
public function readParameters() {
parent::readParameters();
if (isset($_GET['u']) && !empty($_GET['u'])) $this->userID = intval($_GET['u']);
if (isset($_GET['a']) && !empty($_GET['a'])) $this->activationCode = intval($_GET['a']);
}
/**
* @see \wcf\form\IForm::readFormParameters()
*/
public function readFormParameters() {
parent::readFormParameters();
if (isset($_POST['u']) && !empty($_POST['u'])) $this->userID = intval($_POST['u']);
if (isset($_POST['a']) && !empty($_POST['a'])) $this->activationCode = intval($_POST['a']);
}
/**
* @see \wcf\form\IForm::validate()
*/
public function validate() {
EventHandler::getInstance()->fireAction($this, 'validate');
// check given user id
$this->user = new User($this->userID);
if (!$this->user->userID) {
throw new UserInputException('u', 'notValid');
}
// user is already enabled
if ($this->user->reactivationCode == 0) {
throw new NamedUserException(WCF::getLanguage()->get('wcf.user.emailActivation.error.emailAlreadyEnabled'));
}
// check whether the new email isn't unique anymore
if (!UserUtil::isAvailableEmail($this->user->newEmail)) {
throw new NamedUserException(WCF::getLanguage()->get('wcf.user.email.error.notUnique'));
}
// check given activation code
if ($this->user->reactivationCode != $this->activationCode) {
throw new UserInputException('a', 'notValid');
}
}
/**
* @see \wcf\form\IForm::save()
*/
public function save() {
parent::save();
// enable new email
$this->objectAction = new UserAction(array($this->user), 'update', array(
'data' => array_merge($this->additionalFields, array(
'email' => $this->user->newEmail,
'newEmail' => '',
'reactivationCode' => 0
))
));
$this->objectAction->executeAction();
$this->saved();
// forward to index page
HeaderUtil::delayedRedirect(LinkHandler::getInstance()->getLink(), WCF::getLanguage()->get('wcf.user.emailActivation.success'));
exit;
}
/**
* @see \wcf\page\IPage::assignVariables()
*/
public function assignVariables() {
parent::assignVariables();
WCF::getTPL()->assign(array(
'u' => $this->userID,
'a' => $this->activationCode
));
}
/**
* @see \wcf\page\IPage::show()
*/
public function show() {
if (REGISTER_ACTIVATION_METHOD != 1) {
throw new IllegalLinkException();
}
if (empty($_POST) && $this->userID !== null && $this->activationCode != 0) {
$this->submit();
}
parent::show();
}
}
| lgpl-2.1 |
bmolyneaux/VrPlayer | VrPlayer.Helpers/Converters/ObjectToStringConverter.cs | 614 | using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Input;
namespace VrPlayer.Helpers.Converters
{
public class ObjectToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var key = (Key)value;
return key.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return (Key)Enum.Parse(typeof(Key), value.ToString());
}
}
} | lgpl-2.1 |
TerraMA2/terrama2 | src/examples/analysis/ReprocessingHistoricalData.cpp | 7473 | #include <terrama2/core/Shared.hpp>
#include <terrama2/core/utility/Utils.hpp>
#include <terrama2/core/utility/TimeUtils.hpp>
#include <terrama2/core/utility/TerraMA2Init.hpp>
#include <terrama2/core/utility/DataAccessorFactory.hpp>
#include <terrama2/core/utility/Logger.hpp>
#include <terrama2/core/utility/ServiceManager.hpp>
#include <terrama2/core/utility/SemanticsManager.hpp>
#include <terrama2/core/data-model/DataProvider.hpp>
#include <terrama2/core/data-model/DataSeries.hpp>
#include <terrama2/core/data-model/DataSet.hpp>
#include <terrama2/core/data-model/DataSetOccurrence.hpp>
#include <terrama2/services/analysis/core/Analysis.hpp>
#include <terrama2/services/analysis/core/DataManager.hpp>
#include <terrama2/services/analysis/core/Service.hpp>
#include <terrama2/services/analysis/core/python/PythonInterpreter.hpp>
#include <terrama2/services/analysis/core/utility/PythonInterpreterInit.hpp>
#include <terrama2/services/analysis/core/Shared.hpp>
#include <terrama2/services/analysis/mock/MockAnalysisLogger.hpp>
#include <terrama2/impl/Utils.hpp>
#include <examples/data/ResultAnalysisPostGis.hpp>
#include <examples/data/OccurrenceWFP.hpp>
#include <examples/data/StaticPostGis.hpp>
// STL
#include <iostream>
#include <memory>
// QT
#include <QTimer>
#include <QCoreApplication>
#include <QUrl>
#include "../../terrama2/services/analysis/core/AnalysisLogger.hpp"
using namespace terrama2::services::analysis::core;
int main(int argc, char* argv[])
{
terrama2::core::TerraMA2Init terramaRaii("example", 0);
Q_UNUSED(terramaRaii);
terrama2::core::registerFactories();
terrama2::services::analysis::core::PythonInterpreterInit pythonInterpreterInit;
QCoreApplication app(argc, argv);
auto& serviceManager = terrama2::core::ServiceManager::getInstance();
auto dataManager = std::make_shared<terrama2::services::analysis::core::DataManager>();
auto loggerCopy = std::make_shared<terrama2::core::MockAnalysisLogger>();
EXPECT_CALL(*loggerCopy, setConnectionInfo(::testing::_)).WillRepeatedly(::testing::Return());
EXPECT_CALL(*loggerCopy, setTableName(::testing::_)).WillRepeatedly(::testing::Return());
EXPECT_CALL(*loggerCopy, getLastProcessTimestamp(::testing::_)).WillRepeatedly(::testing::Return(nullptr));
EXPECT_CALL(*loggerCopy, getDataLastTimestamp(::testing::_)).WillRepeatedly(::testing::Return(nullptr));
EXPECT_CALL(*loggerCopy, done(::testing::_, ::testing::_)).WillRepeatedly(::testing::Return());
EXPECT_CALL(*loggerCopy, start(::testing::_)).WillRepeatedly(::testing::Return(0));
EXPECT_CALL(*loggerCopy, isValid()).WillRepeatedly(::testing::Return(true));
auto logger = std::make_shared<terrama2::core::MockAnalysisLogger>();
EXPECT_CALL(*logger, setConnectionInfo(::testing::_)).WillRepeatedly(::testing::Return());
EXPECT_CALL(*logger, setTableName(::testing::_)).WillRepeatedly(::testing::Return());
EXPECT_CALL(*logger, getLastProcessTimestamp(::testing::_)).WillRepeatedly(::testing::Return(nullptr));
EXPECT_CALL(*logger, getDataLastTimestamp(::testing::_)).WillRepeatedly(::testing::Return(nullptr));
EXPECT_CALL(*logger, done(::testing::_, ::testing::_)).WillRepeatedly(::testing::Return());
EXPECT_CALL(*logger, start(::testing::_)).WillRepeatedly(::testing::Return(0));
EXPECT_CALL(*logger, clone()).WillRepeatedly(::testing::Return(loggerCopy));
EXPECT_CALL(*logger, isValid()).WillRepeatedly(::testing::Return(true));
Service service(dataManager);
serviceManager.setInstanceId(1);
serviceManager.setLogger(logger);
serviceManager.setLogConnectionInfo(te::core::URI(""));
service.setLogger(logger);
service.start();
/*
* DataProvider and dataSeries Static
*/
auto dataProviderStatic = terrama2::staticpostgis::dataProviderStaticPostGis();
dataManager->add(dataProviderStatic);
auto dataSeries = terrama2::staticpostgis::dataSeriesEstados2010(dataProviderStatic);
dataManager->add(dataSeries);
AnalysisDataSeries monitoredObjectADS;
monitoredObjectADS.id = 1;
monitoredObjectADS.dataSeriesId = dataSeries->id;
monitoredObjectADS.type = AnalysisDataSeriesType::DATASERIES_MONITORED_OBJECT_TYPE;
monitoredObjectADS.metadata["identifier"] = "fid";
/*
* DataProvider and dataSeries result
*/
auto dataProviderResult = terrama2::resultanalysis::dataProviderResultAnalysis();
dataManager->add(dataProviderResult);
auto outputDataSeries = terrama2::resultanalysis::dataSeriesResultAnalysisPostGis(dataProviderResult, terrama2::resultanalysis::tablename::reprocessing_result, dataSeries);
dataManager->add(outputDataSeries);
std::shared_ptr<terrama2::services::analysis::core::Analysis> analysis = std::make_shared<terrama2::services::analysis::core::Analysis>();
std::string script = R"(moBuffer = Buffer()
x = occurrence.zonal.count("Occurrence", "6h", moBuffer)
add_value("count", x))";
analysis->id = 1;
analysis->name = "Analysis";
analysis->active = true;
analysis->script = script;
analysis->outputDataSeriesId = outputDataSeries->id;
analysis->outputDataSetId = outputDataSeries->datasetList.front()->id;
analysis->scriptLanguage = ScriptLanguage::PYTHON;
analysis->type = AnalysisType::MONITORED_OBJECT_TYPE;
analysis->serviceInstanceId = 1;
/*
* DataProvider and dataSeries Occurrence
*/
auto dataProviderOcc = terrama2::occurrencewfp::dataProviderPostGisOccWFP();
dataManager->add(dataProviderOcc);
auto occurrenceDataSeries = terrama2::occurrencewfp::dataSeriesOccWFPPostGis(dataProviderOcc);
dataManager->add(occurrenceDataSeries);
AnalysisDataSeries occurrenceADS;
occurrenceADS.id = 2;
occurrenceADS.dataSeriesId = occurrenceDataSeries->id;
occurrenceADS.type = AnalysisDataSeriesType::ADDITIONAL_DATA_TYPE;
occurrenceADS.alias = "occ";
std::vector<AnalysisDataSeries> analysisDataSeriesList;
analysisDataSeriesList.push_back(monitoredObjectADS);
analysisDataSeriesList.push_back(occurrenceADS);
analysis->analysisDataSeriesList = analysisDataSeriesList;
auto reprocessingHistoricalData = new terrama2::core::ReprocessingHistoricalData();
terrama2::core::ReprocessingHistoricalDataPtr reprocessingHistoricalDataPtr(reprocessingHistoricalData);
boost::local_time::time_zone_ptr zone(new boost::local_time::posix_time_zone("-03"));
std::string startDate = "2016-04-30 20:15:00";
boost::posix_time::ptime startBoostDate(boost::posix_time::time_from_string(startDate));
boost::local_time::local_date_time lstartDate(startBoostDate.date(), startBoostDate.time_of_day(), zone, true);
reprocessingHistoricalData->startDate = std::make_shared<te::dt::TimeInstantTZ>(lstartDate);
std::string endDate = "2016-05-01 08:00:00";
boost::posix_time::ptime endBoostDate(boost::posix_time::time_from_string(endDate));
boost::local_time::local_date_time lendDate(endBoostDate.date(), endBoostDate.time_of_day(), zone, true);
reprocessingHistoricalData->endDate = std::make_shared<te::dt::TimeInstantTZ>(lendDate);
analysis->schedule.reprocessingHistoricalData = reprocessingHistoricalDataPtr;
dataManager->add(analysis);
analysis->schedule.frequency = 15;
analysis->schedule.frequencyUnit = "min";
service.addToQueue(analysis, terrama2::core::TimeUtils::stringToTimestamp("2016-04-30T00:00:00-03", terrama2::core::TimeUtils::webgui_timefacet));
QTimer timer;
QObject::connect(&timer, SIGNAL(timeout()), QCoreApplication::instance(), SLOT(quit()));
timer.start(10000);
app.exec();
return 0;
}
| lgpl-3.0 |
holiman/go-ethereum | common/types_test.go | 14643 | // Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package common
import (
"bytes"
"database/sql/driver"
"encoding/json"
"fmt"
"math/big"
"reflect"
"strings"
"testing"
)
func TestBytesConversion(t *testing.T) {
bytes := []byte{5}
hash := BytesToHash(bytes)
var exp Hash
exp[31] = 5
if hash != exp {
t.Errorf("expected %x got %x", exp, hash)
}
}
func TestIsHexAddress(t *testing.T) {
tests := []struct {
str string
exp bool
}{
{"0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed", true},
{"5aaeb6053f3e94c9b9a09f33669435e7ef1beaed", true},
{"0X5aaeb6053f3e94c9b9a09f33669435e7ef1beaed", true},
{"0XAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", true},
{"0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", true},
{"0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed1", false},
{"0x5aaeb6053f3e94c9b9a09f33669435e7ef1beae", false},
{"5aaeb6053f3e94c9b9a09f33669435e7ef1beaed11", false},
{"0xxaaeb6053f3e94c9b9a09f33669435e7ef1beaed", false},
}
for _, test := range tests {
if result := IsHexAddress(test.str); result != test.exp {
t.Errorf("IsHexAddress(%s) == %v; expected %v",
test.str, result, test.exp)
}
}
}
func TestHashJsonValidation(t *testing.T) {
var tests = []struct {
Prefix string
Size int
Error string
}{
{"", 62, "json: cannot unmarshal hex string without 0x prefix into Go value of type common.Hash"},
{"0x", 66, "hex string has length 66, want 64 for common.Hash"},
{"0x", 63, "json: cannot unmarshal hex string of odd length into Go value of type common.Hash"},
{"0x", 0, "hex string has length 0, want 64 for common.Hash"},
{"0x", 64, ""},
{"0X", 64, ""},
}
for _, test := range tests {
input := `"` + test.Prefix + strings.Repeat("0", test.Size) + `"`
var v Hash
err := json.Unmarshal([]byte(input), &v)
if err == nil {
if test.Error != "" {
t.Errorf("%s: error mismatch: have nil, want %q", input, test.Error)
}
} else {
if err.Error() != test.Error {
t.Errorf("%s: error mismatch: have %q, want %q", input, err, test.Error)
}
}
}
}
func TestAddressUnmarshalJSON(t *testing.T) {
var tests = []struct {
Input string
ShouldErr bool
Output *big.Int
}{
{"", true, nil},
{`""`, true, nil},
{`"0x"`, true, nil},
{`"0x00"`, true, nil},
{`"0xG000000000000000000000000000000000000000"`, true, nil},
{`"0x0000000000000000000000000000000000000000"`, false, big.NewInt(0)},
{`"0x0000000000000000000000000000000000000010"`, false, big.NewInt(16)},
}
for i, test := range tests {
var v Address
err := json.Unmarshal([]byte(test.Input), &v)
if err != nil && !test.ShouldErr {
t.Errorf("test #%d: unexpected error: %v", i, err)
}
if err == nil {
if test.ShouldErr {
t.Errorf("test #%d: expected error, got none", i)
}
if got := new(big.Int).SetBytes(v.Bytes()); got.Cmp(test.Output) != 0 {
t.Errorf("test #%d: address mismatch: have %v, want %v", i, got, test.Output)
}
}
}
}
func TestAddressHexChecksum(t *testing.T) {
var tests = []struct {
Input string
Output string
}{
// Test cases from https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md#specification
{"0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed", "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed"},
{"0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359", "0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359"},
{"0xdbf03b407c01e7cd3cbea99509d93f8dddc8c6fb", "0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB"},
{"0xd1220a0cf47c7b9be7a2e6ba89f429762e7b9adb", "0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb"},
// Ensure that non-standard length input values are handled correctly
{"0xa", "0x000000000000000000000000000000000000000A"},
{"0x0a", "0x000000000000000000000000000000000000000A"},
{"0x00a", "0x000000000000000000000000000000000000000A"},
{"0x000000000000000000000000000000000000000a", "0x000000000000000000000000000000000000000A"},
}
for i, test := range tests {
output := HexToAddress(test.Input).Hex()
if output != test.Output {
t.Errorf("test #%d: failed to match when it should (%s != %s)", i, output, test.Output)
}
}
}
func BenchmarkAddressHex(b *testing.B) {
testAddr := HexToAddress("0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed")
for n := 0; n < b.N; n++ {
testAddr.Hex()
}
}
func TestMixedcaseAccount_Address(t *testing.T) {
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md
// Note: 0X{checksum_addr} is not valid according to spec above
var res []struct {
A MixedcaseAddress
Valid bool
}
if err := json.Unmarshal([]byte(`[
{"A" : "0xae967917c465db8578ca9024c205720b1a3651A9", "Valid": false},
{"A" : "0xAe967917c465db8578ca9024c205720b1a3651A9", "Valid": true},
{"A" : "0XAe967917c465db8578ca9024c205720b1a3651A9", "Valid": false},
{"A" : "0x1111111111111111111112222222222223333323", "Valid": true}
]`), &res); err != nil {
t.Fatal(err)
}
for _, r := range res {
if got := r.A.ValidChecksum(); got != r.Valid {
t.Errorf("Expected checksum %v, got checksum %v, input %v", r.Valid, got, r.A.String())
}
}
//These should throw exceptions:
var r2 []MixedcaseAddress
for _, r := range []string{
`["0x11111111111111111111122222222222233333"]`, // Too short
`["0x111111111111111111111222222222222333332"]`, // Too short
`["0x11111111111111111111122222222222233333234"]`, // Too long
`["0x111111111111111111111222222222222333332344"]`, // Too long
`["1111111111111111111112222222222223333323"]`, // Missing 0x
`["x1111111111111111111112222222222223333323"]`, // Missing 0
`["0xG111111111111111111112222222222223333323"]`, //Non-hex
} {
if err := json.Unmarshal([]byte(r), &r2); err == nil {
t.Errorf("Expected failure, input %v", r)
}
}
}
func TestHash_Scan(t *testing.T) {
type args struct {
src interface{}
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "working scan",
args: args{src: []byte{
0xb2, 0x6f, 0x2b, 0x34, 0x2a, 0xab, 0x24, 0xbc, 0xf6, 0x3e,
0xa2, 0x18, 0xc6, 0xa9, 0x27, 0x4d, 0x30, 0xab, 0x9a, 0x15,
0xa2, 0x18, 0xc6, 0xa9, 0x27, 0x4d, 0x30, 0xab, 0x9a, 0x15,
0x10, 0x00,
}},
wantErr: false,
},
{
name: "non working scan",
args: args{src: int64(1234567890)},
wantErr: true,
},
{
name: "invalid length scan",
args: args{src: []byte{
0xb2, 0x6f, 0x2b, 0x34, 0x2a, 0xab, 0x24, 0xbc, 0xf6, 0x3e,
0xa2, 0x18, 0xc6, 0xa9, 0x27, 0x4d, 0x30, 0xab, 0x9a, 0x15,
0xa2, 0x18, 0xc6, 0xa9, 0x27, 0x4d, 0x30, 0xab, 0x9a, 0x15,
}},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := &Hash{}
if err := h.Scan(tt.args.src); (err != nil) != tt.wantErr {
t.Errorf("Hash.Scan() error = %v, wantErr %v", err, tt.wantErr)
}
if !tt.wantErr {
for i := range h {
if h[i] != tt.args.src.([]byte)[i] {
t.Errorf(
"Hash.Scan() didn't scan the %d src correctly (have %X, want %X)",
i, h[i], tt.args.src.([]byte)[i],
)
}
}
}
})
}
}
func TestHash_Value(t *testing.T) {
b := []byte{
0xb2, 0x6f, 0x2b, 0x34, 0x2a, 0xab, 0x24, 0xbc, 0xf6, 0x3e,
0xa2, 0x18, 0xc6, 0xa9, 0x27, 0x4d, 0x30, 0xab, 0x9a, 0x15,
0xa2, 0x18, 0xc6, 0xa9, 0x27, 0x4d, 0x30, 0xab, 0x9a, 0x15,
0x10, 0x00,
}
var usedH Hash
usedH.SetBytes(b)
tests := []struct {
name string
h Hash
want driver.Value
wantErr bool
}{
{
name: "Working value",
h: usedH,
want: b,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := tt.h.Value()
if (err != nil) != tt.wantErr {
t.Errorf("Hash.Value() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Hash.Value() = %v, want %v", got, tt.want)
}
})
}
}
func TestAddress_Scan(t *testing.T) {
type args struct {
src interface{}
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "working scan",
args: args{src: []byte{
0xb2, 0x6f, 0x2b, 0x34, 0x2a, 0xab, 0x24, 0xbc, 0xf6, 0x3e,
0xa2, 0x18, 0xc6, 0xa9, 0x27, 0x4d, 0x30, 0xab, 0x9a, 0x15,
}},
wantErr: false,
},
{
name: "non working scan",
args: args{src: int64(1234567890)},
wantErr: true,
},
{
name: "invalid length scan",
args: args{src: []byte{
0xb2, 0x6f, 0x2b, 0x34, 0x2a, 0xab, 0x24, 0xbc, 0xf6, 0x3e,
0xa2, 0x18, 0xc6, 0xa9, 0x27, 0x4d, 0x30, 0xab, 0x9a,
}},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
a := &Address{}
if err := a.Scan(tt.args.src); (err != nil) != tt.wantErr {
t.Errorf("Address.Scan() error = %v, wantErr %v", err, tt.wantErr)
}
if !tt.wantErr {
for i := range a {
if a[i] != tt.args.src.([]byte)[i] {
t.Errorf(
"Address.Scan() didn't scan the %d src correctly (have %X, want %X)",
i, a[i], tt.args.src.([]byte)[i],
)
}
}
}
})
}
}
func TestAddress_Value(t *testing.T) {
b := []byte{
0xb2, 0x6f, 0x2b, 0x34, 0x2a, 0xab, 0x24, 0xbc, 0xf6, 0x3e,
0xa2, 0x18, 0xc6, 0xa9, 0x27, 0x4d, 0x30, 0xab, 0x9a, 0x15,
}
var usedA Address
usedA.SetBytes(b)
tests := []struct {
name string
a Address
want driver.Value
wantErr bool
}{
{
name: "Working value",
a: usedA,
want: b,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := tt.a.Value()
if (err != nil) != tt.wantErr {
t.Errorf("Address.Value() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Address.Value() = %v, want %v", got, tt.want)
}
})
}
}
func TestAddress_Format(t *testing.T) {
b := []byte{
0xb2, 0x6f, 0x2b, 0x34, 0x2a, 0xab, 0x24, 0xbc, 0xf6, 0x3e,
0xa2, 0x18, 0xc6, 0xa9, 0x27, 0x4d, 0x30, 0xab, 0x9a, 0x15,
}
var addr Address
addr.SetBytes(b)
tests := []struct {
name string
out string
want string
}{
{
name: "println",
out: fmt.Sprintln(addr),
want: "0xB26f2b342AAb24BCF63ea218c6A9274D30Ab9A15\n",
},
{
name: "print",
out: fmt.Sprint(addr),
want: "0xB26f2b342AAb24BCF63ea218c6A9274D30Ab9A15",
},
{
name: "printf-s",
out: func() string {
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "%s", addr)
return buf.String()
}(),
want: "0xB26f2b342AAb24BCF63ea218c6A9274D30Ab9A15",
},
{
name: "printf-q",
out: fmt.Sprintf("%q", addr),
want: `"0xB26f2b342AAb24BCF63ea218c6A9274D30Ab9A15"`,
},
{
name: "printf-x",
out: fmt.Sprintf("%x", addr),
want: "b26f2b342aab24bcf63ea218c6a9274d30ab9a15",
},
{
name: "printf-X",
out: fmt.Sprintf("%X", addr),
want: "B26F2B342AAB24BCF63EA218C6A9274D30AB9A15",
},
{
name: "printf-#x",
out: fmt.Sprintf("%#x", addr),
want: "0xb26f2b342aab24bcf63ea218c6a9274d30ab9a15",
},
{
name: "printf-v",
out: fmt.Sprintf("%v", addr),
want: "0xB26f2b342AAb24BCF63ea218c6A9274D30Ab9A15",
},
// The original default formatter for byte slice
{
name: "printf-d",
out: fmt.Sprintf("%d", addr),
want: "[178 111 43 52 42 171 36 188 246 62 162 24 198 169 39 77 48 171 154 21]",
},
// Invalid format char.
{
name: "printf-t",
out: fmt.Sprintf("%t", addr),
want: "%!t(address=b26f2b342aab24bcf63ea218c6a9274d30ab9a15)",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.out != tt.want {
t.Errorf("%s does not render as expected:\n got %s\nwant %s", tt.name, tt.out, tt.want)
}
})
}
}
func TestHash_Format(t *testing.T) {
var hash Hash
hash.SetBytes([]byte{
0xb2, 0x6f, 0x2b, 0x34, 0x2a, 0xab, 0x24, 0xbc, 0xf6, 0x3e,
0xa2, 0x18, 0xc6, 0xa9, 0x27, 0x4d, 0x30, 0xab, 0x9a, 0x15,
0xa2, 0x18, 0xc6, 0xa9, 0x27, 0x4d, 0x30, 0xab, 0x9a, 0x15,
0x10, 0x00,
})
tests := []struct {
name string
out string
want string
}{
{
name: "println",
out: fmt.Sprintln(hash),
want: "0xb26f2b342aab24bcf63ea218c6a9274d30ab9a15a218c6a9274d30ab9a151000\n",
},
{
name: "print",
out: fmt.Sprint(hash),
want: "0xb26f2b342aab24bcf63ea218c6a9274d30ab9a15a218c6a9274d30ab9a151000",
},
{
name: "printf-s",
out: func() string {
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "%s", hash)
return buf.String()
}(),
want: "0xb26f2b342aab24bcf63ea218c6a9274d30ab9a15a218c6a9274d30ab9a151000",
},
{
name: "printf-q",
out: fmt.Sprintf("%q", hash),
want: `"0xb26f2b342aab24bcf63ea218c6a9274d30ab9a15a218c6a9274d30ab9a151000"`,
},
{
name: "printf-x",
out: fmt.Sprintf("%x", hash),
want: "b26f2b342aab24bcf63ea218c6a9274d30ab9a15a218c6a9274d30ab9a151000",
},
{
name: "printf-X",
out: fmt.Sprintf("%X", hash),
want: "B26F2B342AAB24BCF63EA218C6A9274D30AB9A15A218C6A9274D30AB9A151000",
},
{
name: "printf-#x",
out: fmt.Sprintf("%#x", hash),
want: "0xb26f2b342aab24bcf63ea218c6a9274d30ab9a15a218c6a9274d30ab9a151000",
},
{
name: "printf-#X",
out: fmt.Sprintf("%#X", hash),
want: "0XB26F2B342AAB24BCF63EA218C6A9274D30AB9A15A218C6A9274D30AB9A151000",
},
{
name: "printf-v",
out: fmt.Sprintf("%v", hash),
want: "0xb26f2b342aab24bcf63ea218c6a9274d30ab9a15a218c6a9274d30ab9a151000",
},
// The original default formatter for byte slice
{
name: "printf-d",
out: fmt.Sprintf("%d", hash),
want: "[178 111 43 52 42 171 36 188 246 62 162 24 198 169 39 77 48 171 154 21 162 24 198 169 39 77 48 171 154 21 16 0]",
},
// Invalid format char.
{
name: "printf-t",
out: fmt.Sprintf("%t", hash),
want: "%!t(hash=b26f2b342aab24bcf63ea218c6a9274d30ab9a15a218c6a9274d30ab9a151000)",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.out != tt.want {
t.Errorf("%s does not render as expected:\n got %s\nwant %s", tt.name, tt.out, tt.want)
}
})
}
}
| lgpl-3.0 |
denislaliberte/preuve-one-page | vendor/bundle/gems/jquery-ui-rails-4.0.5/app/assets/javascripts/jquery.ui.effect-shake.js | 1978 | //= require jquery.ui.effect
/*!
* jQuery UI Effects Shake 1.10.3
* http://jqueryui.com
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/shake-effect/
*
* Depends:
* jquery.ui.effect.js
*/
(function( $, undefined ) {
$.effects.effect.shake = function( o, done ) {
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
mode = $.effects.setMode( el, o.mode || "effect" ),
direction = o.direction || "left",
distance = o.distance || 20,
times = o.times || 3,
anims = times * 2 + 1,
speed = Math.round(o.duration/anims),
ref = (direction === "up" || direction === "down") ? "top" : "left",
positiveMotion = (direction === "up" || direction === "left"),
animation = {},
animation1 = {},
animation2 = {},
i,
// we will need to re-assemble the queue to stack our animations in place
queue = el.queue(),
queuelen = queue.length;
$.effects.save( el, props );
el.show();
$.effects.createWrapper( el );
// Animation
animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance;
animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2;
animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2;
// Animate
el.animate( animation, speed, o.easing );
// Shakes
for ( i = 1; i < times; i++ ) {
el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing );
}
el
.animate( animation1, speed, o.easing )
.animate( animation, speed / 2, o.easing )
.queue(function() {
if ( mode === "hide" ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
});
// inject all the animations we just queued to be first in line (after "inprogress")
if ( queuelen > 1) {
queue.splice.apply( queue,
[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
}
el.dequeue();
};
})(jQuery);
| unlicense |
tiagosatur/guyon | node_modules/colorette/colorette.d.ts | 1295 | interface Style {
(string: string): string
}
export const options: {
enabled: boolean
}
export const reset: Style
export const bold: Style
export const dim: Style
export const italic: Style
export const underline: Style
export const inverse: Style
export const hidden: Style
export const strikethrough: Style
export const black: Style
export const red: Style
export const green: Style
export const yellow: Style
export const blue: Style
export const magenta: Style
export const cyan: Style
export const white: Style
export const gray: Style
export const bgBlack: Style
export const bgRed: Style
export const bgGreen: Style
export const bgYellow: Style
export const bgBlue: Style
export const bgMagenta: Style
export const bgCyan: Style
export const bgWhite: Style
export const blackBright: Style
export const redBright: Style
export const greenBright: Style
export const yellowBright: Style
export const blueBright: Style
export const magentaBright: Style
export const cyanBright: Style
export const whiteBright: Style
export const bgBlackBright: Style
export const bgRedBright: Style
export const bgGreenBright: Style
export const bgYellowBright: Style
export const bgBlueBright: Style
export const bgMagentaBright: Style
export const bgCyanBright: Style
export const bgWhiteBright: Style
| unlicense |
kjniemi/activemq-artemis | tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/largemessage/ServerLargeMessageTest.java | 16097 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.tests.integration.largemessage;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.Message;
import org.apache.activemq.artemis.api.core.QueueConfiguration;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.api.core.client.ActiveMQClient;
import org.apache.activemq.artemis.api.core.client.ClientConsumer;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.client.ClientProducer;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.core.io.AbstractSequentialFile;
import org.apache.activemq.artemis.core.io.IOCallback;
import org.apache.activemq.artemis.core.io.SequentialFile;
import org.apache.activemq.artemis.core.io.buffer.TimedBuffer;
import org.apache.activemq.artemis.core.journal.EncodingSupport;
import org.apache.activemq.artemis.core.persistence.impl.journal.JournalStorageManager;
import org.apache.activemq.artemis.core.persistence.impl.journal.LargeServerMessageImpl;
import org.apache.activemq.artemis.core.security.Role;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServers;
import org.apache.activemq.artemis.spi.core.security.ActiveMQJAASSecurityManager;
import org.apache.activemq.artemis.tests.integration.security.SecurityTest;
import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.FakeSequentialFileFactory;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.apache.activemq.artemis.utils.critical.EmptyCriticalAnalyzer;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class ServerLargeMessageTest extends ActiveMQTestBase {
// Constants -----------------------------------------------------
// Attributes ----------------------------------------------------
// Static --------------------------------------------------------
String originalPath;
@Before
public void setupProperty() {
originalPath = System.getProperty("java.security.auth.login.config");
if (originalPath == null) {
URL resource = SecurityTest.class.getClassLoader().getResource("login.config");
if (resource != null) {
originalPath = resource.getFile();
System.setProperty("java.security.auth.login.config", originalPath);
}
}
}
@After
public void clearProperty() {
if (originalPath == null) {
System.clearProperty("java.security.auth.login.config");
} else {
System.setProperty("java.security.auth.login.config", originalPath);
}
}
// Constructors --------------------------------------------------
// Public --------------------------------------------------------
// The ClientConsumer should be able to also send ServerLargeMessages as that's done by the CoreBridge
@Test
public void testSendServerMessage() throws Exception {
ActiveMQServer server = createServer(true);
server.start();
ServerLocator locator = createInVMNonHALocator();
ClientSessionFactory sf = createSessionFactory(locator);
ClientSession session = sf.createSession(false, false);
try {
LargeServerMessageImpl fileMessage = new LargeServerMessageImpl((JournalStorageManager) server.getStorageManager());
fileMessage.setMessageID(1005);
for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) {
fileMessage.addBytes(new byte[]{ActiveMQTestBase.getSamplebyte(i)});
}
// The server would be doing this
fileMessage.putLongProperty(Message.HDR_LARGE_BODY_SIZE, 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE);
fileMessage.releaseResources(false, true);
session.createQueue(new QueueConfiguration("A").setRoutingType(RoutingType.ANYCAST));
ClientProducer prod = session.createProducer("A");
prod.send(fileMessage);
fileMessage.deleteFile();
session.commit();
session.start();
ClientConsumer cons = session.createConsumer("A");
ClientMessage msg = cons.receive(5000);
Assert.assertNotNull(msg);
Assert.assertEquals(msg.getBodySize(), 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE);
for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) {
Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg.getBodyBuffer().readByte());
}
msg.acknowledge();
session.commit();
} finally {
sf.close();
locator.close();
server.stop();
}
}
@Test
public void testSendServerMessageWithValidatedUser() throws Exception {
ActiveMQJAASSecurityManager securityManager = new ActiveMQJAASSecurityManager("PropertiesLogin");
ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig().setSecurityEnabled(true), ManagementFactory.getPlatformMBeanServer(), securityManager, false));
server.getConfiguration().setPopulateValidatedUser(true);
Role role = new Role("programmers", true, true, true, true, true, true, true, true, true, true);
Set<Role> roles = new HashSet<>();
roles.add(role);
server.getSecurityRepository().addMatch("#", roles);
server.start();
ServerLocator locator = createInVMNonHALocator();
ClientSessionFactory sf = createSessionFactory(locator);
try {
ClientSession session = sf.createSession("first", "secret", false, true, true, false, 0);
ClientMessage clientMessage = session.createMessage(false);
clientMessage.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE));
session.createQueue(new QueueConfiguration("A").setRoutingType(RoutingType.ANYCAST));
ClientProducer prod = session.createProducer("A");
prod.send(clientMessage);
session.commit();
session.start();
ClientConsumer cons = session.createConsumer("A");
ClientMessage msg = cons.receive(5000);
assertEquals("first", msg.getValidatedUserID());
} finally {
sf.close();
locator.close();
server.stop();
}
}
@Test
public void testLargeServerMessageSync() throws Exception {
final AtomicBoolean open = new AtomicBoolean(false);
final AtomicBoolean sync = new AtomicBoolean(false);
JournalStorageManager storageManager = new JournalStorageManager(createDefaultInVMConfig(), EmptyCriticalAnalyzer.getInstance(), getOrderedExecutor(), getOrderedExecutor()) {
@Override
public SequentialFile createFileForLargeMessage(long messageID, LargeMessageExtension extension) {
return new SequentialFile() {
@Override
public boolean isOpen() {
return open.get();
}
@Override
public boolean exists() {
return true;
}
@Override
public void open() throws Exception {
open.set(true);
}
@Override
public void open(int maxIO, boolean useExecutor) throws Exception {
open.set(true);
}
@Override
public boolean fits(int size) {
return false;
}
@Override
public int calculateBlockStart(int position) throws Exception {
return 0;
}
@Override
public ByteBuffer map(int position, long size) throws IOException {
return null;
}
@Override
public String getFileName() {
return null;
}
@Override
public void fill(int size) throws Exception {
}
@Override
public void delete() throws IOException, InterruptedException, ActiveMQException {
}
@Override
public void write(ActiveMQBuffer bytes, boolean sync, IOCallback callback) throws Exception {
}
@Override
public void write(ActiveMQBuffer bytes, boolean sync) throws Exception {
}
@Override
public void write(EncodingSupport bytes, boolean sync, IOCallback callback) throws Exception {
}
@Override
public void write(EncodingSupport bytes, boolean sync) throws Exception {
}
@Override
public void writeDirect(ByteBuffer bytes, boolean sync, IOCallback callback) {
}
@Override
public void writeDirect(ByteBuffer bytes, boolean sync) throws Exception {
}
@Override
public void blockingWriteDirect(ByteBuffer bytes, boolean sync, boolean releaseBuffer) throws Exception {
}
@Override
public int read(ByteBuffer bytes, IOCallback callback) throws Exception {
return 0;
}
@Override
public int read(ByteBuffer bytes) throws Exception {
return 0;
}
@Override
public void position(long pos) throws IOException {
}
@Override
public long position() {
return 0;
}
@Override
public void close() throws Exception {
open.set(false);
}
@Override
public void sync() throws IOException {
sync.set(true);
}
@Override
public long size() throws Exception {
return 0;
}
@Override
public void renameTo(String newFileName) throws Exception {
}
@Override
public SequentialFile cloneFile() {
return null;
}
@Override
public void copyTo(SequentialFile newFileName) throws Exception {
}
@Override
public void setTimedBuffer(TimedBuffer buffer) {
}
@Override
public File getJavaFile() {
return null;
}
};
}
};
LargeServerMessageImpl largeServerMessage = new LargeServerMessageImpl(storageManager);
largeServerMessage.setMessageID(1234);
largeServerMessage.addBytes(new byte[0]);
assertTrue(open.get());
largeServerMessage.releaseResources(true, true);
assertTrue(sync.get());
}
@Test
public void testLargeServerMessageCopyIsolation() throws Exception {
ActiveMQServer server = createServer(true);
server.start();
try {
LargeServerMessageImpl largeMessage = new LargeServerMessageImpl((JournalStorageManager)server.getStorageManager());
largeMessage.setMessageID(23456);
for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) {
largeMessage.addBytes(new byte[]{ActiveMQTestBase.getSamplebyte(i)});
}
//now replace the underlying file with a fake
replaceFile(largeMessage);
Message copied = largeMessage.copy(99999);
assertEquals(99999, copied.getMessageID());
} finally {
server.stop();
}
}
private void replaceFile(LargeServerMessageImpl largeMessage) throws Exception {
SequentialFile originalFile = largeMessage.getAppendFile();
MockSequentialFile mockFile = new MockSequentialFile(originalFile);
largeMessage.getLargeBody().replaceFile(mockFile);
mockFile.close();
}
// Package protected ---------------------------------------------
// Protected -----------------------------------------------------
// Private -------------------------------------------------------
// Inner classes -------------------------------------------------
private class MockSequentialFile extends AbstractSequentialFile {
private SequentialFile originalFile;
MockSequentialFile(SequentialFile originalFile) throws Exception {
super(originalFile.getJavaFile().getParentFile(), originalFile.getFileName(), new FakeSequentialFileFactory(), null);
this.originalFile = originalFile;
this.originalFile.close();
}
@Override
public void open() throws Exception {
//open and close it right away to simulate failure condition
originalFile.open();
originalFile.close();
}
@Override
public void open(int maxIO, boolean useExecutor) throws Exception {
}
@Override
public ByteBuffer map(int position, long size) throws IOException {
return null;
}
@Override
public boolean isOpen() {
return originalFile.isOpen();
}
@Override
public int calculateBlockStart(int position) throws Exception {
return originalFile.calculateBlockStart(position);
}
@Override
public void fill(int size) throws Exception {
originalFile.fill(size);
}
@Override
public void writeDirect(ByteBuffer bytes, boolean sync, IOCallback callback) {
originalFile.writeDirect(bytes, sync, callback);
}
@Override
public void writeDirect(ByteBuffer bytes, boolean sync) throws Exception {
originalFile.writeDirect(bytes, sync);
}
@Override
public void blockingWriteDirect(ByteBuffer bytes, boolean sync, boolean releaseBuffer) throws Exception {
originalFile.blockingWriteDirect(bytes, sync, releaseBuffer);
}
@Override
public int read(ByteBuffer bytes, IOCallback callback) throws Exception {
return originalFile.read(bytes, callback);
}
@Override
public int read(ByteBuffer bytes) throws Exception {
return originalFile.read(bytes);
}
@Override
public void sync() throws IOException {
originalFile.sync();
}
@Override
public long size() throws Exception {
return originalFile.size();
}
@Override
public SequentialFile cloneFile() {
return originalFile.cloneFile();
}
}
}
| apache-2.0 |
thiagokimo/Alexei | library/src/main/java/com/kimo/lib/alexei/calculus/AverageColorCalculus.java | 1189 | package com.kimo.lib.alexei.calculus;
import android.graphics.Bitmap;
import android.graphics.Color;
import com.kimo.lib.alexei.Calculus;
/**
* Calculates the average RGB color of an image
*/
public class AverageColorCalculus extends Calculus<Integer> {
public static final String TAG = AverageColorCalculus.class.getSimpleName();
public AverageColorCalculus(Bitmap image) {
super(image);
}
@Override
protected Integer theCalculation(Bitmap image) {
if (null == image) return Color.TRANSPARENT;
else {
int pixelCount = image.getWidth() * image.getHeight();
int red, green, blue;
red = green = blue = 0;
for (int i = 0; i < image.getWidth(); i++)
for (int j = 0; j < image.getHeight(); j++) {
int pixel = image.getPixel(i, j);
red += Color.red(pixel);
green += Color.green(pixel);
blue += Color.blue(pixel);
}
red /= pixelCount;
green /= pixelCount;
blue /= pixelCount;
return Color.rgb(red, green, blue);
}
}
}
| apache-2.0 |
jyotisingh/gocd | server/webapp/WEB-INF/rails/webpack/views/components/modal/delete_confirm_modal.tsx | 1523 | /*
* Copyright 2018 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as m from "mithril";
import * as Buttons from "views/components/buttons";
import {Modal, Size} from "views/components/modal";
export class DeleteConfirmModal extends Modal {
private readonly message: m.Children;
private readonly modalTitle: string;
private ondelete: () => any;
constructor(message: m.Children,
ondelete: () => any,
title = "Are you sure?") {
super(Size.small);
this.message = message;
this.modalTitle = title;
this.ondelete = ondelete;
}
body(): m.Children {
return <div>{this.message}</div>;
}
title(): string {
return this.modalTitle;
}
buttons(): m.ChildArray {
return [
<Buttons.Danger data-test-id='button-delete' onclick={this.ondelete.bind(this)}>Yes Delete</Buttons.Danger>,
<Buttons.Cancel data-test-id='button-no-delete' onclick={this.close.bind(this)}>No</Buttons.Cancel>
];
}
}
| apache-2.0 |
christophd/camel | components/camel-csv/src/main/java/org/apache/camel/dataformat/csv/CsvDataFormat.java | 28521 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.dataformat.csv;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.StringJoiner;
import org.apache.camel.Exchange;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.spi.DataFormatName;
import org.apache.camel.spi.annotations.Dataformat;
import org.apache.camel.support.service.ServiceSupport;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.QuoteMode;
/**
* CSV Data format.
* <p/>
* By default, columns are autogenerated in the resulting CSV. Subsequent messages use the previously created columns
* with new fields being added at the end of the line. Thus, field order is the same from message to message.
* Autogeneration can be disabled. In this case, only the fields defined in csvConfig are written on the output.
*/
@Dataformat("csv")
public class CsvDataFormat extends ServiceSupport implements DataFormat, DataFormatName {
// CSV format options
private CSVFormat format = CSVFormat.DEFAULT;
private boolean commentMarkerDisabled;
private Character commentMarker;
private Character delimiter;
private boolean escapeDisabled;
private Character escape;
private boolean headerDisabled;
private String header;
private Boolean allowMissingColumnNames;
private Boolean ignoreEmptyLines;
private Boolean ignoreSurroundingSpaces;
private boolean nullStringDisabled;
private String nullString;
private boolean quoteDisabled;
private Character quote;
private QuoteMode quoteMode;
private boolean recordSeparatorDisabled;
private String recordSeparator;
private Boolean skipHeaderRecord;
private Boolean trim;
private Boolean ignoreHeaderCase;
private Boolean trailingDelimiter;
// Unmarshal options
private boolean captureHeaderRecord;
private boolean lazyLoad;
private boolean useMaps;
private boolean useOrderedMaps;
private CsvRecordConverter<?> recordConverter;
private CsvMarshallerFactory marshallerFactory = CsvMarshallerFactory.DEFAULT;
private volatile CsvMarshaller marshaller;
private volatile CsvUnmarshaller unmarshaller;
public CsvDataFormat() {
}
public CsvDataFormat(CSVFormat format) {
setFormat(format);
}
@Override
public String getDataFormatName() {
return "csv";
}
@Override
public void marshal(Exchange exchange, Object object, OutputStream outputStream) throws Exception {
marshaller.marshal(exchange, object, outputStream);
}
@Override
public Object unmarshal(Exchange exchange, InputStream inputStream) throws Exception {
return unmarshaller.unmarshal(exchange, inputStream);
}
@Override
protected void doInit() throws Exception {
super.doInit();
marshaller = marshallerFactory.create(getActiveFormat(), this);
unmarshaller = CsvUnmarshaller.create(getActiveFormat(), this);
}
@Override
protected void doStop() throws Exception {
// noop
}
CSVFormat getActiveFormat() {
CSVFormat answer = format;
if (commentMarkerDisabled) {
answer = answer.withCommentMarker(null); // null disables the comment marker
} else if (commentMarker != null) {
answer = answer.withCommentMarker(commentMarker);
}
if (delimiter != null) {
answer = answer.withDelimiter(delimiter);
}
if (escapeDisabled) {
answer = answer.withEscape(null); // null disables the escape
} else if (escape != null) {
answer = answer.withEscape(escape);
}
if (headerDisabled) {
answer = answer.withHeader((String[]) null); // null disables the header
} else if (header != null) {
if (header.indexOf(',') != -1) {
answer = answer.withHeader(header.split(","));
} else {
answer = answer.withHeader(header);
}
}
if (allowMissingColumnNames != null) {
answer = answer.withAllowMissingColumnNames(allowMissingColumnNames);
}
if (ignoreEmptyLines != null) {
answer = answer.withIgnoreEmptyLines(ignoreEmptyLines);
}
if (ignoreSurroundingSpaces != null) {
answer = answer.withIgnoreSurroundingSpaces(ignoreSurroundingSpaces);
}
if (nullStringDisabled) {
answer = answer.withNullString(null); // null disables the null string replacement
} else if (nullString != null) {
answer = answer.withNullString(nullString);
}
if (quoteDisabled) {
answer = answer.withQuote(null); // null disables quotes
} else if (quote != null) {
answer = answer.withQuote(quote);
}
if (quoteMode != null) {
answer = answer.withQuoteMode(quoteMode);
}
if (recordSeparatorDisabled) {
answer = answer.withRecordSeparator(null); // null disables the record separator
} else if (recordSeparator != null) {
answer = answer.withRecordSeparator(recordSeparator);
}
if (skipHeaderRecord != null) {
answer = answer.withSkipHeaderRecord(skipHeaderRecord);
}
if (trim != null) {
answer = answer.withTrim(trim);
}
if (ignoreHeaderCase != null) {
answer = answer.withIgnoreHeaderCase(ignoreHeaderCase);
}
if (trailingDelimiter != null) {
answer = answer.withTrailingDelimiter(trailingDelimiter);
}
return answer;
}
//region Getters/Setters
/**
* Gets the CSV format before applying any changes. It cannot be {@code null}, the default one is
* {@link org.apache.commons.csv.CSVFormat#DEFAULT}.
*
* @return CSV format
*/
public CSVFormat getFormat() {
return format;
}
/**
* Sets the CSV format before applying any changes. If {@code null}, then
* {@link org.apache.commons.csv.CSVFormat#DEFAULT} is used instead.
*
* @param format CSV format
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat
* @see org.apache.commons.csv.CSVFormat#DEFAULT
*/
public CsvDataFormat setFormat(CSVFormat format) {
this.format = (format == null) ? CSVFormat.DEFAULT : format;
return this;
}
/**
* Sets the {@link CsvMarshaller} factory. If {@code null}, then {@link CsvMarshallerFactory#DEFAULT} is used
* instead.
*
* @param marshallerFactory
* @return Current {@code CsvDataFormat}, fluent API
*/
public CsvDataFormat setMarshallerFactory(CsvMarshallerFactory marshallerFactory) {
this.marshallerFactory = (marshallerFactory == null) ? CsvMarshallerFactory.DEFAULT : marshallerFactory;
return this;
}
/**
* Returns the used {@link CsvMarshallerFactory}.
*
* @return never {@code null}.
*/
public CsvMarshallerFactory getMarshallerFactory() {
return marshallerFactory;
}
/**
* Sets the CSV format by name before applying any changes.
*
* @param name CSV format name
* @return Current {@code CsvDataFormat}, fluent API
* @see #setFormat(org.apache.commons.csv.CSVFormat)
* @see org.apache.commons.csv.CSVFormat
*/
public CsvDataFormat setFormatName(String name) {
if (name == null) {
setFormat(null);
} else if ("DEFAULT".equals(name)) {
setFormat(CSVFormat.DEFAULT);
} else if ("RFC4180".equals(name)) {
setFormat(CSVFormat.RFC4180);
} else if ("EXCEL".equals(name)) {
setFormat(CSVFormat.EXCEL);
} else if ("TDF".equals(name)) {
setFormat(CSVFormat.TDF);
} else if ("MYSQL".equals(name)) {
setFormat(CSVFormat.MYSQL);
} else {
throw new IllegalArgumentException("Unsupported format");
}
return this;
}
/**
* Indicates whether or not the comment markers are disabled.
*
* @return {@code true} if the comment markers are disabled, {@code false} otherwise
*/
public boolean isCommentMarkerDisabled() {
return commentMarkerDisabled;
}
/**
* Sets whether or not the comment markers are disabled.
*
* @param commentMarkerDisabled {@code true} if the comment markers are disabled, {@code false} otherwise
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withCommentMarker(java.lang.Character)
*/
public CsvDataFormat setCommentMarkerDisabled(boolean commentMarkerDisabled) {
this.commentMarkerDisabled = commentMarkerDisabled;
return this;
}
/**
* Gets the comment marker. If {@code null} then the default one of the format used.
*
* @return Comment marker
*/
public Character getCommentMarker() {
return commentMarker;
}
/**
* Sets the comment marker to use. If {@code null} then the default one of the format used.
*
* @param commentMarker Comment marker
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withCommentMarker(Character)
*/
public CsvDataFormat setCommentMarker(Character commentMarker) {
this.commentMarker = commentMarker;
return this;
}
/**
* Gets the delimiter. If {@code null} then the default one of the format used.
*
* @return Delimiter
*/
public Character getDelimiter() {
return delimiter;
}
/**
* Sets the delimiter. If {@code null} then the default one of the format used.
*
* @param delimiter Delimiter
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withDelimiter(char)
*/
public CsvDataFormat setDelimiter(Character delimiter) {
this.delimiter = delimiter;
return this;
}
/**
* Indicates whether or not the escaping is disabled.
*
* @return {@code true} if the escaping is disabled, {@code false} otherwise
*/
public boolean isEscapeDisabled() {
return escapeDisabled;
}
/**
* Sets whether or not the escaping is disabled.
*
* @param escapeDisabled {@code true} if the escaping is disabled, {@code false} otherwise
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withEscape(Character)
*/
public CsvDataFormat setEscapeDisabled(boolean escapeDisabled) {
this.escapeDisabled = escapeDisabled;
return this;
}
/**
* Gets the escape character. If {@code null} then the default one of the format used.
*
* @return Escape character
*/
public Character getEscape() {
return escape;
}
/**
* Sets the escape character. If {@code null} then the default one of the format used.
*
* @param escape Escape character
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withEscape(Character)
*/
public CsvDataFormat setEscape(Character escape) {
this.escape = escape;
return this;
}
/**
* Indicates whether or not the headers are disabled.
*
* @return {@code true} if the headers are disabled, {@code false} otherwise
*/
public boolean isHeaderDisabled() {
return headerDisabled;
}
/**
* Sets whether or not the headers are disabled.
*
* @param headerDisabled {@code true} if the headers are disabled, {@code false} otherwise
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withHeader(String...)
*/
public CsvDataFormat setHeaderDisabled(boolean headerDisabled) {
this.headerDisabled = headerDisabled;
return this;
}
/**
* Gets the header. Multiple values can be separated by comma.
*
* If {@code null} then the default one of the format used. If empty then it will be automatically handled.
*
* @return Header
*/
public String getHeader() {
return header;
}
/**
* Gets the header. Multiple values can be separated by comma.
*
* If {@code null} then the default one of the format used. If empty then it will be automatically handled.
*
* @param header Header
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withHeader(String...)
*/
public CsvDataFormat setHeader(String header) {
this.header = header;
return this;
}
public CsvDataFormat setHeader(String[] header) {
StringJoiner sj = new StringJoiner(",");
for (String s : header) {
sj.add(s);
}
this.header = sj.toString();
return this;
}
/**
* Indicates whether or not missing column names are allowed. If {@code null} then the default value of the format
* used.
*
* @return Whether or not missing column names are allowed
*/
public Boolean getAllowMissingColumnNames() {
return allowMissingColumnNames;
}
/**
* Sets whether or not missing column names are allowed. If {@code null} then the default value of the format used.
*
* @param allowMissingColumnNames Whether or not missing column names are allowed
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withAllowMissingColumnNames(boolean)
*/
public CsvDataFormat setAllowMissingColumnNames(Boolean allowMissingColumnNames) {
this.allowMissingColumnNames = allowMissingColumnNames;
return this;
}
/**
* Indicates whether or not empty lines must be ignored. If {@code null} then the default value of the format used.
*
* @return Whether or not empty lines must be ignored
*/
public Boolean getIgnoreEmptyLines() {
return ignoreEmptyLines;
}
/**
* Sets whether or not empty lines must be ignored. If {@code null} then the default value of the format used.
*
* @param ignoreEmptyLines Whether or not empty lines must be ignored
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withIgnoreEmptyLines(boolean)
*/
public CsvDataFormat setIgnoreEmptyLines(Boolean ignoreEmptyLines) {
this.ignoreEmptyLines = ignoreEmptyLines;
return this;
}
/**
* Indicates whether or not surrounding spaces must be ignored. If {@code null} then the default value of the format
* used.
*
* @return Whether or not surrounding spaces must be ignored
*/
public Boolean getIgnoreSurroundingSpaces() {
return ignoreSurroundingSpaces;
}
/**
* Sets whether or not surrounding spaces must be ignored. If {@code null} then the default value of the format
* used.
*
* @param ignoreSurroundingSpaces Whether or not surrounding spaces must be ignored
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withIgnoreSurroundingSpaces(boolean)
*/
public CsvDataFormat setIgnoreSurroundingSpaces(Boolean ignoreSurroundingSpaces) {
this.ignoreSurroundingSpaces = ignoreSurroundingSpaces;
return this;
}
/**
* Indicates whether or not the null string replacement is disabled.
*
* @return {@code true} if the null string replacement is disabled, {@code false} otherwise
*/
public boolean isNullStringDisabled() {
return nullStringDisabled;
}
/**
* Sets whether or not the null string replacement is disabled.
*
* @param nullStringDisabled {@code true} if the null string replacement is disabled, {@code false} otherwise
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withNullString(String)
*/
public CsvDataFormat setNullStringDisabled(boolean nullStringDisabled) {
this.nullStringDisabled = nullStringDisabled;
return this;
}
/**
* Gets the null string replacement. If {@code null} then the default one of the format used.
*
* @return Null string replacement
*/
public String getNullString() {
return nullString;
}
/**
* Sets the null string replacement. If {@code null} then the default one of the format used.
*
* @param nullString Null string replacement
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withNullString(String)
*/
public CsvDataFormat setNullString(String nullString) {
this.nullString = nullString;
return this;
}
/**
* Indicates whether or not quotes are disabled.
*
* @return {@code true} if quotes are disabled, {@code false} otherwise
*/
public boolean isQuoteDisabled() {
return quoteDisabled;
}
/**
* Sets whether or not quotes are disabled
*
* @param quoteDisabled {@code true} if quotes are disabled, {@code false} otherwise
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withQuote(Character)
*/
public CsvDataFormat setQuoteDisabled(boolean quoteDisabled) {
this.quoteDisabled = quoteDisabled;
return this;
}
/**
* Gets the quote character. If {@code null} then the default one of the format used.
*
* @return Quote character
*/
public Character getQuote() {
return quote;
}
/**
* Sets the quote character. If {@code null} then the default one of the format used.
*
* @param quote Quote character
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withQuote(Character)
*/
public CsvDataFormat setQuote(Character quote) {
this.quote = quote;
return this;
}
/**
* Gets the quote mode. If {@code null} then the default one of the format used.
*
* @return Quote mode
*/
public QuoteMode getQuoteMode() {
return quoteMode;
}
/**
* Sets the quote mode. If {@code null} then the default one of the format used.
*
* @param quoteMode Quote mode
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withQuoteMode(org.apache.commons.csv.QuoteMode)
*/
public CsvDataFormat setQuoteMode(QuoteMode quoteMode) {
this.quoteMode = quoteMode;
return this;
}
/**
* Indicates whether or not the record separator is disabled.
*
* @return {@code true} if the record separator disabled, {@code false} otherwise
*/
public boolean isRecordSeparatorDisabled() {
return recordSeparatorDisabled;
}
/**
* Sets whether or not the record separator is disabled.
*
* @param recordSeparatorDisabled {@code true} if the record separator disabled, {@code false} otherwise
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withRecordSeparator(String)
*/
public CsvDataFormat setRecordSeparatorDisabled(boolean recordSeparatorDisabled) {
this.recordSeparatorDisabled = recordSeparatorDisabled;
return this;
}
/**
* Gets the record separator. If {@code null} then the default one of the format used.
*
* @return Record separator
*/
public String getRecordSeparator() {
return recordSeparator;
}
/**
* Sets the record separator. If {@code null} then the default one of the format used.
*
* @param recordSeparator Record separator
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withRecordSeparator(String)
*/
public CsvDataFormat setRecordSeparator(String recordSeparator) {
this.recordSeparator = recordSeparator;
return this;
}
/**
* Indicates whether or not header record must be skipped. If {@code null} then the default value of the format
* used.
*
* @return Whether or not header record must be skipped
*/
public Boolean getSkipHeaderRecord() {
return skipHeaderRecord;
}
/**
* Sets whether or not header record must be skipped. If {@code null} then the default value of the format used.
*
* @param skipHeaderRecord Whether or not header record must be skipped
* @return Current {@code CsvDataFormat}, fluent API
* @see org.apache.commons.csv.CSVFormat#withSkipHeaderRecord(boolean)
*/
public CsvDataFormat setSkipHeaderRecord(Boolean skipHeaderRecord) {
this.skipHeaderRecord = skipHeaderRecord;
return this;
}
/**
* Indicates whether or not the unmarshalling should capture the header record.
*
* @return {@code true} for capture header record, {@code false} otherwise
*/
public boolean isCaptureHeaderRecord() {
return captureHeaderRecord;
}
/**
* Indicates whether or not the unmarshalling should capture the header record.
*
* @param captureHeaderRecord {@code true} for capture header record, {@code false} otherwise
* @return Current {@code CsvDataFormat}, fluent API
*/
public CsvDataFormat setCaptureHeaderRecord(boolean captureHeaderRecord) {
this.captureHeaderRecord = captureHeaderRecord;
return this;
}
/**
* Indicates whether or not the unmarshalling should lazily load the records.
*
* @return {@code true} for lazy loading, {@code false} otherwise
*/
public boolean isLazyLoad() {
return lazyLoad;
}
/**
* Indicates whether or not the unmarshalling should lazily load the records.
*
* @param lazyLoad {@code true} for lazy loading, {@code false} otherwise
* @return Current {@code CsvDataFormat}, fluent API
*/
public CsvDataFormat setLazyLoad(boolean lazyLoad) {
this.lazyLoad = lazyLoad;
return this;
}
/**
* Indicates whether or not the unmarshalling should produce maps instead of lists.
*
* @return {@code true} for maps, {@code false} for lists
*/
public boolean isUseMaps() {
return useMaps;
}
/**
* Sets whether or not the unmarshalling should produce maps instead of lists.
*
* @param useMaps {@code true} for maps, {@code false} for lists
* @return Current {@code CsvDataFormat}, fluent API
*/
public CsvDataFormat setUseMaps(boolean useMaps) {
this.useMaps = useMaps;
return this;
}
/**
* Indicates whether or not the unmarshalling should produce ordered maps instead of lists.
*
* @return {@code true} for maps, {@code false} for lists
*/
public boolean isUseOrderedMaps() {
return useOrderedMaps;
}
/**
* Sets whether or not the unmarshalling should produce ordered maps instead of lists.
*
* @param useOrderedMaps {@code true} for maps, {@code false} for lists
* @return Current {@code CsvDataFormat}, fluent API
*/
public CsvDataFormat setUseOrderedMaps(boolean useOrderedMaps) {
this.useOrderedMaps = useOrderedMaps;
return this;
}
/**
* Gets the record converter to use. If {@code null} then it will use {@link CsvDataFormat#isUseMaps()} for finding
* the proper converter.
*
* @return Record converter to use
*/
public CsvRecordConverter<?> getRecordConverter() {
return recordConverter;
}
/**
* Sets the record converter to use. If {@code null} then it will use {@link CsvDataFormat#isUseMaps()} for finding
* the proper converter.
*
* @param recordConverter Record converter to use
* @return Current {@code CsvDataFormat}, fluent API
*/
public CsvDataFormat setRecordConverter(CsvRecordConverter<?> recordConverter) {
this.recordConverter = recordConverter;
return this;
}
//endregion
/**
* Sets whether or not to trim leading and trailing blanks.
* <p>
* If {@code null} then the default value of the format used.
* </p>
*
* @param trim whether or not to trim leading and trailing blanks. <code>null</code> value allowed.
* @return Current {@code CsvDataFormat}, fluent API.
*/
public CsvDataFormat setTrim(Boolean trim) {
this.trim = trim;
return this;
}
/**
* Indicates whether or not to trim leading and trailing blanks.
*
* @return {@link Boolean#TRUE} if leading and trailing blanks should be trimmed. {@link Boolean#FALSE} otherwise.
* Could return <code>null</code> if value has NOT been set.
*/
public Boolean getTrim() {
return trim;
}
/**
* Sets whether or not to ignore case when accessing header names.
* <p>
* If {@code null} then the default value of the format used.
* </p>
*
* @param ignoreHeaderCase whether or not to ignore case when accessing header names. <code>null</code> value
* allowed.
* @return Current {@code CsvDataFormat}, fluent API.
*/
public CsvDataFormat setIgnoreHeaderCase(Boolean ignoreHeaderCase) {
this.ignoreHeaderCase = ignoreHeaderCase;
return this;
}
/**
* Indicates whether or not to ignore case when accessing header names.
*
* @return {@link Boolean#TRUE} if case should be ignored when accessing header name. {@link Boolean#FALSE}
* otherwise. Could return <code>null</code> if value has NOT been set.
*/
public Boolean getIgnoreHeaderCase() {
return ignoreHeaderCase;
}
/**
* Sets whether or not to add a trailing delimiter.
* <p>
* If {@code null} then the default value of the format used.
* </p>
*
* @param trailingDelimiter whether or not to add a trailing delimiter.
* @return Current {@code CsvDataFormat}, fluent API.
*/
public CsvDataFormat setTrailingDelimiter(Boolean trailingDelimiter) {
this.trailingDelimiter = trailingDelimiter;
return this;
}
/**
* Indicates whether or not to add a trailing delimiter.
*
* @return {@link Boolean#TRUE} if a trailing delimiter should be added. {@link Boolean#FALSE} otherwise. Could
* return <code>null</code> if value has NOT been set.
*/
public Boolean getTrailingDelimiter() {
return trailingDelimiter;
}
}
| apache-2.0 |
l0kod/rust | src/librustc_bitflags/lib.rs | 15952 | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustc_bitflags"]
#![feature(associated_consts)]
#![feature(staged_api)]
#![staged_api]
#![crate_type = "rlib"]
#![feature(no_std)]
#![no_std]
#![unstable(feature = "rustc_private")]
#![cfg_attr(test, feature(hash_default))]
//! A typesafe bitmask flag generator.
#[cfg(test)] #[macro_use] extern crate std;
/// The `bitflags!` macro generates a `struct` that holds a set of C-style
/// bitmask flags. It is useful for creating typesafe wrappers for C APIs.
///
/// The flags should only be defined for integer types, otherwise unexpected
/// type errors may occur at compile time.
///
/// # Examples
///
/// ```{.rust}
/// #![feature(rustc_private)]
/// #![feature(associated_consts)]
/// #[macro_use] extern crate rustc_bitflags;
///
/// bitflags! {
/// flags Flags: u32 {
/// const FLAG_A = 0b00000001,
/// const FLAG_B = 0b00000010,
/// const FLAG_C = 0b00000100,
/// const FLAG_ABC = Flags::FLAG_A.bits
/// | Flags::FLAG_B.bits
/// | Flags::FLAG_C.bits,
/// }
/// }
///
/// fn main() {
/// let e1 = Flags::FLAG_A | Flags::FLAG_C;
/// let e2 = Flags::FLAG_B | Flags::FLAG_C;
/// assert!((e1 | e2) == Flags::FLAG_ABC); // union
/// assert!((e1 & e2) == Flags::FLAG_C); // intersection
/// assert!((e1 - e2) == Flags::FLAG_A); // set difference
/// assert!(!e2 == Flags::FLAG_A); // set complement
/// }
/// ```
///
/// The generated `struct`s can also be extended with type and trait implementations:
///
/// ```{.rust}
/// #![feature(rustc_private)]
/// #[macro_use] extern crate rustc_bitflags;
///
/// use std::fmt;
///
/// bitflags! {
/// flags Flags: u32 {
/// const FLAG_A = 0b00000001,
/// const FLAG_B = 0b00000010,
/// }
/// }
///
/// impl Flags {
/// pub fn clear(&mut self) {
/// self.bits = 0; // The `bits` field can be accessed from within the
/// // same module where the `bitflags!` macro was invoked.
/// }
/// }
///
/// impl fmt::Debug for Flags {
/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
/// write!(f, "hi!")
/// }
/// }
///
/// fn main() {
/// let mut flags = Flags::FLAG_A | Flags::FLAG_B;
/// flags.clear();
/// assert!(flags.is_empty());
/// assert_eq!(format!("{:?}", flags), "hi!");
/// }
/// ```
///
/// # Attributes
///
/// Attributes can be attached to the generated `struct` by placing them
/// before the `flags` keyword.
///
/// # Derived traits
///
/// The `PartialEq` and `Clone` traits are automatically derived for the `struct` using
/// the `deriving` attribute. Additional traits can be derived by providing an
/// explicit `deriving` attribute on `flags`.
///
/// # Operators
///
/// The following operator traits are implemented for the generated `struct`:
///
/// - `BitOr`: union
/// - `BitAnd`: intersection
/// - `BitXor`: toggle
/// - `Sub`: set difference
/// - `Not`: set complement
///
/// # Methods
///
/// The following methods are defined for the generated `struct`:
///
/// - `empty`: an empty set of flags
/// - `all`: the set of all flags
/// - `bits`: the raw value of the flags currently stored
/// - `from_bits`: convert from underlying bit representation, unless that
/// representation contains bits that do not correspond to a flag
/// - `from_bits_truncate`: convert from underlying bit representation, dropping
/// any bits that do not correspond to flags
/// - `is_empty`: `true` if no flags are currently stored
/// - `is_all`: `true` if all flags are currently set
/// - `intersects`: `true` if there are flags common to both `self` and `other`
/// - `contains`: `true` all of the flags in `other` are contained within `self`
/// - `insert`: inserts the specified flags in-place
/// - `remove`: removes the specified flags in-place
/// - `toggle`: the specified flags will be inserted if not present, and removed
/// if they are.
#[macro_export]
macro_rules! bitflags {
($(#[$attr:meta])* flags $BitFlags:ident: $T:ty {
$($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+
}) => {
#[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)]
$(#[$attr])*
pub struct $BitFlags {
bits: $T,
}
impl $BitFlags {
$($(#[$Flag_attr])* pub const $Flag: $BitFlags = $BitFlags { bits: $value };)+
/// Returns an empty set of flags.
#[inline]
pub fn empty() -> $BitFlags {
$BitFlags { bits: 0 }
}
/// Returns the set containing all flags.
#[inline]
pub fn all() -> $BitFlags {
$BitFlags { bits: $($value)|+ }
}
/// Returns the raw value of the flags currently stored.
#[inline]
pub fn bits(&self) -> $T {
self.bits
}
/// Convert from underlying bit representation, unless that
/// representation contains bits that do not correspond to a flag.
#[inline]
pub fn from_bits(bits: $T) -> ::std::option::Option<$BitFlags> {
if (bits & !$BitFlags::all().bits()) != 0 {
::std::option::Option::None
} else {
::std::option::Option::Some($BitFlags { bits: bits })
}
}
/// Convert from underlying bit representation, dropping any bits
/// that do not correspond to flags.
#[inline]
pub fn from_bits_truncate(bits: $T) -> $BitFlags {
$BitFlags { bits: bits } & $BitFlags::all()
}
/// Returns `true` if no flags are currently stored.
#[inline]
pub fn is_empty(&self) -> bool {
*self == $BitFlags::empty()
}
/// Returns `true` if all flags are currently set.
#[inline]
pub fn is_all(&self) -> bool {
*self == $BitFlags::all()
}
/// Returns `true` if there are flags common to both `self` and `other`.
#[inline]
pub fn intersects(&self, other: $BitFlags) -> bool {
!(*self & other).is_empty()
}
/// Returns `true` all of the flags in `other` are contained within `self`.
#[inline]
pub fn contains(&self, other: $BitFlags) -> bool {
(*self & other) == other
}
/// Inserts the specified flags in-place.
#[inline]
pub fn insert(&mut self, other: $BitFlags) {
self.bits |= other.bits;
}
/// Removes the specified flags in-place.
#[inline]
pub fn remove(&mut self, other: $BitFlags) {
self.bits &= !other.bits;
}
/// Toggles the specified flags in-place.
#[inline]
pub fn toggle(&mut self, other: $BitFlags) {
self.bits ^= other.bits;
}
}
impl ::std::ops::BitOr for $BitFlags {
type Output = $BitFlags;
/// Returns the union of the two sets of flags.
#[inline]
fn bitor(self, other: $BitFlags) -> $BitFlags {
$BitFlags { bits: self.bits | other.bits }
}
}
impl ::std::ops::BitXor for $BitFlags {
type Output = $BitFlags;
/// Returns the left flags, but with all the right flags toggled.
#[inline]
fn bitxor(self, other: $BitFlags) -> $BitFlags {
$BitFlags { bits: self.bits ^ other.bits }
}
}
impl ::std::ops::BitAnd for $BitFlags {
type Output = $BitFlags;
/// Returns the intersection between the two sets of flags.
#[inline]
fn bitand(self, other: $BitFlags) -> $BitFlags {
$BitFlags { bits: self.bits & other.bits }
}
}
impl ::std::ops::Sub for $BitFlags {
type Output = $BitFlags;
/// Returns the set difference of the two sets of flags.
#[inline]
fn sub(self, other: $BitFlags) -> $BitFlags {
$BitFlags { bits: self.bits & !other.bits }
}
}
impl ::std::ops::Not for $BitFlags {
type Output = $BitFlags;
/// Returns the complement of this set of flags.
#[inline]
fn not(self) -> $BitFlags {
$BitFlags { bits: !self.bits } & $BitFlags::all()
}
}
};
($(#[$attr:meta])* flags $BitFlags:ident: $T:ty {
$($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+,
}) => {
bitflags! {
$(#[$attr])*
flags $BitFlags: $T {
$($(#[$Flag_attr])* const $Flag = $value),+
}
}
};
}
#[cfg(test)]
#[allow(non_upper_case_globals)]
mod tests {
use std::hash::{self, SipHasher};
use std::option::Option::{Some, None};
bitflags! {
#[doc = "> The first principle is that you must not fool yourself — and"]
#[doc = "> you are the easiest person to fool."]
#[doc = "> "]
#[doc = "> - Richard Feynman"]
flags Flags: u32 {
const FlagA = 0b00000001,
#[doc = "<pcwalton> macros are way better at generating code than trans is"]
const FlagB = 0b00000010,
const FlagC = 0b00000100,
#[doc = "* cmr bed"]
#[doc = "* strcat table"]
#[doc = "<strcat> wait what?"]
const FlagABC = Flags::FlagA.bits
| Flags::FlagB.bits
| Flags::FlagC.bits,
}
}
bitflags! {
flags AnotherSetOfFlags: i8 {
const AnotherFlag = -1,
}
}
#[test]
fn test_bits(){
assert_eq!(Flags::empty().bits(), 0b00000000);
assert_eq!(Flags::FlagA.bits(), 0b00000001);
assert_eq!(Flags::FlagABC.bits(), 0b00000111);
assert_eq!(AnotherSetOfFlags::empty().bits(), 0b00);
assert_eq!(AnotherSetOfFlags::AnotherFlag.bits(), !0);
}
#[test]
fn test_from_bits() {
assert!(Flags::from_bits(0) == Some(Flags::empty()));
assert!(Flags::from_bits(0b1) == Some(Flags::FlagA));
assert!(Flags::from_bits(0b10) == Some(Flags::FlagB));
assert!(Flags::from_bits(0b11) == Some(Flags::FlagA | Flags::FlagB));
assert!(Flags::from_bits(0b1000) == None);
assert!(AnotherSetOfFlags::from_bits(!0) == Some(AnotherSetOfFlags::AnotherFlag));
}
#[test]
fn test_from_bits_truncate() {
assert!(Flags::from_bits_truncate(0) == Flags::empty());
assert!(Flags::from_bits_truncate(0b1) == Flags::FlagA);
assert!(Flags::from_bits_truncate(0b10) == Flags::FlagB);
assert!(Flags::from_bits_truncate(0b11) == (Flags::FlagA | Flags::FlagB));
assert!(Flags::from_bits_truncate(0b1000) == Flags::empty());
assert!(Flags::from_bits_truncate(0b1001) == Flags::FlagA);
assert!(AnotherSetOfFlags::from_bits_truncate(0) == AnotherSetOfFlags::empty());
}
#[test]
fn test_is_empty(){
assert!(Flags::empty().is_empty());
assert!(!Flags::FlagA.is_empty());
assert!(!Flags::FlagABC.is_empty());
assert!(!AnotherSetOfFlags::AnotherFlag.is_empty());
}
#[test]
fn test_is_all() {
assert!(Flags::all().is_all());
assert!(!Flags::FlagA.is_all());
assert!(Flags::FlagABC.is_all());
assert!(AnotherSetOfFlags::AnotherFlag.is_all());
}
#[test]
fn test_two_empties_do_not_intersect() {
let e1 = Flags::empty();
let e2 = Flags::empty();
assert!(!e1.intersects(e2));
assert!(AnotherSetOfFlags::AnotherFlag.intersects(AnotherSetOfFlags::AnotherFlag));
}
#[test]
fn test_empty_does_not_intersect_with_full() {
let e1 = Flags::empty();
let e2 = Flags::FlagABC;
assert!(!e1.intersects(e2));
}
#[test]
fn test_disjoint_intersects() {
let e1 = Flags::FlagA;
let e2 = Flags::FlagB;
assert!(!e1.intersects(e2));
}
#[test]
fn test_overlapping_intersects() {
let e1 = Flags::FlagA;
let e2 = Flags::FlagA | Flags::FlagB;
assert!(e1.intersects(e2));
}
#[test]
fn test_contains() {
let e1 = Flags::FlagA;
let e2 = Flags::FlagA | Flags::FlagB;
assert!(!e1.contains(e2));
assert!(e2.contains(e1));
assert!(Flags::FlagABC.contains(e2));
assert!(AnotherSetOfFlags::AnotherFlag.contains(AnotherSetOfFlags::AnotherFlag));
}
#[test]
fn test_insert(){
let mut e1 = Flags::FlagA;
let e2 = Flags::FlagA | Flags::FlagB;
e1.insert(e2);
assert!(e1 == e2);
let mut e3 = AnotherSetOfFlags::empty();
e3.insert(AnotherSetOfFlags::AnotherFlag);
assert!(e3 == AnotherSetOfFlags::AnotherFlag);
}
#[test]
fn test_remove(){
let mut e1 = Flags::FlagA | Flags::FlagB;
let e2 = Flags::FlagA | Flags::FlagC;
e1.remove(e2);
assert!(e1 == Flags::FlagB);
let mut e3 = AnotherSetOfFlags::AnotherFlag;
e3.remove(AnotherSetOfFlags::AnotherFlag);
assert!(e3 == AnotherSetOfFlags::empty());
}
#[test]
fn test_operators() {
let e1 = Flags::FlagA | Flags::FlagC;
let e2 = Flags::FlagB | Flags::FlagC;
assert!((e1 | e2) == Flags::FlagABC); // union
assert!((e1 & e2) == Flags::FlagC); // intersection
assert!((e1 - e2) == Flags::FlagA); // set difference
assert!(!e2 == Flags::FlagA); // set complement
assert!(e1 ^ e2 == Flags::FlagA | Flags::FlagB); // toggle
let mut e3 = e1;
e3.toggle(e2);
assert!(e3 == Flags::FlagA | Flags::FlagB);
let mut m4 = AnotherSetOfFlags::empty();
m4.toggle(AnotherSetOfFlags::empty());
assert!(m4 == AnotherSetOfFlags::empty());
}
#[test]
fn test_lt() {
let mut a = Flags::empty();
let mut b = Flags::empty();
assert!(!(a < b) && !(b < a));
b = Flags::FlagB;
assert!(a < b);
a = Flags::FlagC;
assert!(!(a < b) && b < a);
b = Flags::FlagC | Flags::FlagB;
assert!(a < b);
}
#[test]
fn test_ord() {
let mut a = Flags::empty();
let mut b = Flags::empty();
assert!(a <= b && a >= b);
a = Flags::FlagA;
assert!(a > b && a >= b);
assert!(b < a && b <= a);
b = Flags::FlagB;
assert!(b > a && b >= a);
assert!(a < b && a <= b);
}
#[test]
fn test_hash() {
let mut x = Flags::empty();
let mut y = Flags::empty();
assert!(hash::hash::<Flags, SipHasher>(&x) == hash::hash::<Flags, SipHasher>(&y));
x = Flags::all();
y = Flags::FlagABC;
assert!(hash::hash::<Flags, SipHasher>(&x) == hash::hash::<Flags, SipHasher>(&y));
}
}
| apache-2.0 |
elonazoulay/presto | presto-main/src/test/java/com/facebook/presto/sql/gen/TestVarArgsToArrayAdapterGenerator.java | 5334 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.gen;
import com.facebook.presto.annotation.UsedByGeneratedCode;
import com.facebook.presto.metadata.BoundVariables;
import com.facebook.presto.metadata.FunctionKind;
import com.facebook.presto.metadata.FunctionRegistry;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.metadata.SqlScalarFunction;
import com.facebook.presto.operator.scalar.AbstractTestFunctions;
import com.facebook.presto.operator.scalar.ScalarFunctionImplementation;
import com.facebook.presto.spi.type.TypeManager;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.lang.invoke.MethodHandle;
import java.util.Optional;
import java.util.stream.IntStream;
import static com.facebook.presto.operator.scalar.ScalarFunctionImplementation.ArgumentProperty.valueTypeArgumentProperty;
import static com.facebook.presto.operator.scalar.ScalarFunctionImplementation.NullConvention.RETURN_NULL_ON_NULL;
import static com.facebook.presto.spi.type.IntegerType.INTEGER;
import static com.facebook.presto.sql.gen.TestVarArgsToArrayAdapterGenerator.TestVarArgsSum.VAR_ARGS_SUM;
import static com.facebook.presto.sql.gen.VarArgsToArrayAdapterGenerator.generateVarArgsToArrayAdapter;
import static com.facebook.presto.util.Reflection.methodHandle;
import static java.lang.String.format;
import static java.util.Collections.nCopies;
import static java.util.stream.Collectors.toSet;
public class TestVarArgsToArrayAdapterGenerator
extends AbstractTestFunctions
{
@BeforeClass
public void setUp()
{
registerScalarFunction(VAR_ARGS_SUM);
}
@Test
public void testArrayElements()
throws Exception
{
assertFunction("var_args_sum()", INTEGER, 0);
assertFunction("var_args_sum(1)", INTEGER, 1);
assertFunction("var_args_sum(1, 2)", INTEGER, 3);
assertFunction("var_args_sum(null)", INTEGER, null);
assertFunction("var_args_sum(1, null, 2, null, 3)", INTEGER, null);
assertFunction("var_args_sum(1, 2, 3)", INTEGER, 6);
// var_args_sum(1, 2, 3, ..., k)
int k = 100;
int expectedSum = (1 + k) * k / 2;
assertFunction(format("var_args_sum(%s)", Joiner.on(",").join(IntStream.rangeClosed(1, k).boxed().collect(toSet()))), INTEGER, expectedSum);
}
public static class TestVarArgsSum
extends SqlScalarFunction
{
public static final TestVarArgsSum VAR_ARGS_SUM = new TestVarArgsSum();
private static final MethodHandle METHOD_HANDLE = methodHandle(TestVarArgsSum.class, "varArgsSum", Object.class, long[].class);
private static final MethodHandle USER_STATE_FACTORY = methodHandle(TestVarArgsSum.class, "createState");
private TestVarArgsSum()
{
super(new Signature(
"var_args_sum",
FunctionKind.SCALAR,
ImmutableList.of(),
ImmutableList.of(),
INTEGER.getTypeSignature(),
ImmutableList.of(INTEGER.getTypeSignature()),
true));
}
@Override
public boolean isHidden()
{
return false;
}
@Override
public boolean isDeterministic()
{
return false;
}
@Override
public String getDescription()
{
return "return sum of all the parameters";
}
@Override
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry)
{
VarArgsToArrayAdapterGenerator.MethodHandleAndConstructor methodHandleAndConstructor = generateVarArgsToArrayAdapter(
long.class,
long.class,
arity,
METHOD_HANDLE,
USER_STATE_FACTORY);
return new ScalarFunctionImplementation(
false,
nCopies(arity, valueTypeArgumentProperty(RETURN_NULL_ON_NULL)),
methodHandleAndConstructor.getMethodHandle(),
Optional.of(methodHandleAndConstructor.getConstructor()),
isDeterministic());
}
@UsedByGeneratedCode
public static Object createState()
{
return null;
}
@UsedByGeneratedCode
public static long varArgsSum(Object state, long[] values)
{
long sum = 0;
for (long value : values) {
sum += value;
}
return sum;
}
}
}
| apache-2.0 |
efortuna/AndroidSDKClone | sdk/sources/android-20/android/media/MediaScanner.java | 74548 | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.media;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.IContentProvider;
import android.database.Cursor;
import android.database.SQLException;
import android.drm.DrmManagerClient;
import android.graphics.BitmapFactory;
import android.mtp.MtpConstants;
import android.net.Uri;
import android.os.Environment;
import android.os.RemoteException;
import android.os.SystemProperties;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Audio.Playlists;
import android.provider.MediaStore.Files;
import android.provider.MediaStore.Files.FileColumns;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Video;
import android.provider.Settings;
import android.sax.Element;
import android.sax.ElementListener;
import android.sax.RootElement;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import libcore.io.ErrnoException;
import libcore.io.Libcore;
/**
* Internal service helper that no-one should use directly.
*
* The way the scan currently works is:
* - The Java MediaScannerService creates a MediaScanner (this class), and calls
* MediaScanner.scanDirectories on it.
* - scanDirectories() calls the native processDirectory() for each of the specified directories.
* - the processDirectory() JNI method wraps the provided mediascanner client in a native
* 'MyMediaScannerClient' class, then calls processDirectory() on the native MediaScanner
* object (which got created when the Java MediaScanner was created).
* - native MediaScanner.processDirectory() calls
* doProcessDirectory(), which recurses over the folder, and calls
* native MyMediaScannerClient.scanFile() for every file whose extension matches.
* - native MyMediaScannerClient.scanFile() calls back on Java MediaScannerClient.scanFile,
* which calls doScanFile, which after some setup calls back down to native code, calling
* MediaScanner.processFile().
* - MediaScanner.processFile() calls one of several methods, depending on the type of the
* file: parseMP3, parseMP4, parseMidi, parseOgg or parseWMA.
* - each of these methods gets metadata key/value pairs from the file, and repeatedly
* calls native MyMediaScannerClient.handleStringTag, which calls back up to its Java
* counterparts in this file.
* - Java handleStringTag() gathers the key/value pairs that it's interested in.
* - once processFile returns and we're back in Java code in doScanFile(), it calls
* Java MyMediaScannerClient.endFile(), which takes all the data that's been
* gathered and inserts an entry in to the database.
*
* In summary:
* Java MediaScannerService calls
* Java MediaScanner scanDirectories, which calls
* Java MediaScanner processDirectory (native method), which calls
* native MediaScanner processDirectory, which calls
* native MyMediaScannerClient scanFile, which calls
* Java MyMediaScannerClient scanFile, which calls
* Java MediaScannerClient doScanFile, which calls
* Java MediaScanner processFile (native method), which calls
* native MediaScanner processFile, which calls
* native parseMP3, parseMP4, parseMidi, parseOgg or parseWMA, which calls
* native MyMediaScanner handleStringTag, which calls
* Java MyMediaScanner handleStringTag.
* Once MediaScanner processFile returns, an entry is inserted in to the database.
*
* The MediaScanner class is not thread-safe, so it should only be used in a single threaded manner.
*
* {@hide}
*/
public class MediaScanner
{
static {
System.loadLibrary("media_jni");
native_init();
}
private final static String TAG = "MediaScanner";
private static final String[] FILES_PRESCAN_PROJECTION = new String[] {
Files.FileColumns._ID, // 0
Files.FileColumns.DATA, // 1
Files.FileColumns.FORMAT, // 2
Files.FileColumns.DATE_MODIFIED, // 3
};
private static final String[] ID_PROJECTION = new String[] {
Files.FileColumns._ID,
};
private static final int FILES_PRESCAN_ID_COLUMN_INDEX = 0;
private static final int FILES_PRESCAN_PATH_COLUMN_INDEX = 1;
private static final int FILES_PRESCAN_FORMAT_COLUMN_INDEX = 2;
private static final int FILES_PRESCAN_DATE_MODIFIED_COLUMN_INDEX = 3;
private static final String[] PLAYLIST_MEMBERS_PROJECTION = new String[] {
Audio.Playlists.Members.PLAYLIST_ID, // 0
};
private static final int ID_PLAYLISTS_COLUMN_INDEX = 0;
private static final int PATH_PLAYLISTS_COLUMN_INDEX = 1;
private static final int DATE_MODIFIED_PLAYLISTS_COLUMN_INDEX = 2;
private static final String RINGTONES_DIR = "/ringtones/";
private static final String NOTIFICATIONS_DIR = "/notifications/";
private static final String ALARMS_DIR = "/alarms/";
private static final String MUSIC_DIR = "/music/";
private static final String PODCAST_DIR = "/podcasts/";
private static final String[] ID3_GENRES = {
// ID3v1 Genres
"Blues",
"Classic Rock",
"Country",
"Dance",
"Disco",
"Funk",
"Grunge",
"Hip-Hop",
"Jazz",
"Metal",
"New Age",
"Oldies",
"Other",
"Pop",
"R&B",
"Rap",
"Reggae",
"Rock",
"Techno",
"Industrial",
"Alternative",
"Ska",
"Death Metal",
"Pranks",
"Soundtrack",
"Euro-Techno",
"Ambient",
"Trip-Hop",
"Vocal",
"Jazz+Funk",
"Fusion",
"Trance",
"Classical",
"Instrumental",
"Acid",
"House",
"Game",
"Sound Clip",
"Gospel",
"Noise",
"AlternRock",
"Bass",
"Soul",
"Punk",
"Space",
"Meditative",
"Instrumental Pop",
"Instrumental Rock",
"Ethnic",
"Gothic",
"Darkwave",
"Techno-Industrial",
"Electronic",
"Pop-Folk",
"Eurodance",
"Dream",
"Southern Rock",
"Comedy",
"Cult",
"Gangsta",
"Top 40",
"Christian Rap",
"Pop/Funk",
"Jungle",
"Native American",
"Cabaret",
"New Wave",
"Psychadelic",
"Rave",
"Showtunes",
"Trailer",
"Lo-Fi",
"Tribal",
"Acid Punk",
"Acid Jazz",
"Polka",
"Retro",
"Musical",
"Rock & Roll",
"Hard Rock",
// The following genres are Winamp extensions
"Folk",
"Folk-Rock",
"National Folk",
"Swing",
"Fast Fusion",
"Bebob",
"Latin",
"Revival",
"Celtic",
"Bluegrass",
"Avantgarde",
"Gothic Rock",
"Progressive Rock",
"Psychedelic Rock",
"Symphonic Rock",
"Slow Rock",
"Big Band",
"Chorus",
"Easy Listening",
"Acoustic",
"Humour",
"Speech",
"Chanson",
"Opera",
"Chamber Music",
"Sonata",
"Symphony",
"Booty Bass",
"Primus",
"Porn Groove",
"Satire",
"Slow Jam",
"Club",
"Tango",
"Samba",
"Folklore",
"Ballad",
"Power Ballad",
"Rhythmic Soul",
"Freestyle",
"Duet",
"Punk Rock",
"Drum Solo",
"A capella",
"Euro-House",
"Dance Hall",
// The following ones seem to be fairly widely supported as well
"Goa",
"Drum & Bass",
"Club-House",
"Hardcore",
"Terror",
"Indie",
"Britpop",
null,
"Polsk Punk",
"Beat",
"Christian Gangsta",
"Heavy Metal",
"Black Metal",
"Crossover",
"Contemporary Christian",
"Christian Rock",
"Merengue",
"Salsa",
"Thrash Metal",
"Anime",
"JPop",
"Synthpop",
// 148 and up don't seem to have been defined yet.
};
private long mNativeContext;
private Context mContext;
private String mPackageName;
private IContentProvider mMediaProvider;
private Uri mAudioUri;
private Uri mVideoUri;
private Uri mImagesUri;
private Uri mThumbsUri;
private Uri mPlaylistsUri;
private Uri mFilesUri;
private Uri mFilesUriNoNotify;
private boolean mProcessPlaylists, mProcessGenres;
private int mMtpObjectHandle;
private final String mExternalStoragePath;
private final boolean mExternalIsEmulated;
/** whether to use bulk inserts or individual inserts for each item */
private static final boolean ENABLE_BULK_INSERTS = true;
// used when scanning the image database so we know whether we have to prune
// old thumbnail files
private int mOriginalCount;
/** Whether the database had any entries in it before the scan started */
private boolean mWasEmptyPriorToScan = false;
/** Whether the scanner has set a default sound for the ringer ringtone. */
private boolean mDefaultRingtoneSet;
/** Whether the scanner has set a default sound for the notification ringtone. */
private boolean mDefaultNotificationSet;
/** Whether the scanner has set a default sound for the alarm ringtone. */
private boolean mDefaultAlarmSet;
/** The filename for the default sound for the ringer ringtone. */
private String mDefaultRingtoneFilename;
/** The filename for the default sound for the notification ringtone. */
private String mDefaultNotificationFilename;
/** The filename for the default sound for the alarm ringtone. */
private String mDefaultAlarmAlertFilename;
/**
* The prefix for system properties that define the default sound for
* ringtones. Concatenate the name of the setting from Settings
* to get the full system property.
*/
private static final String DEFAULT_RINGTONE_PROPERTY_PREFIX = "ro.config.";
// set to true if file path comparisons should be case insensitive.
// this should be set when scanning files on a case insensitive file system.
private boolean mCaseInsensitivePaths;
private final BitmapFactory.Options mBitmapOptions = new BitmapFactory.Options();
private static class FileEntry {
long mRowId;
String mPath;
long mLastModified;
int mFormat;
boolean mLastModifiedChanged;
FileEntry(long rowId, String path, long lastModified, int format) {
mRowId = rowId;
mPath = path;
mLastModified = lastModified;
mFormat = format;
mLastModifiedChanged = false;
}
@Override
public String toString() {
return mPath + " mRowId: " + mRowId;
}
}
private static class PlaylistEntry {
String path;
long bestmatchid;
int bestmatchlevel;
}
private ArrayList<PlaylistEntry> mPlaylistEntries = new ArrayList<PlaylistEntry>();
private MediaInserter mMediaInserter;
private ArrayList<FileEntry> mPlayLists;
private DrmManagerClient mDrmManagerClient = null;
public MediaScanner(Context c) {
native_setup();
mContext = c;
mPackageName = c.getPackageName();
mBitmapOptions.inSampleSize = 1;
mBitmapOptions.inJustDecodeBounds = true;
setDefaultRingtoneFileNames();
mExternalStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();
mExternalIsEmulated = Environment.isExternalStorageEmulated();
//mClient.testGenreNameConverter();
}
private void setDefaultRingtoneFileNames() {
mDefaultRingtoneFilename = SystemProperties.get(DEFAULT_RINGTONE_PROPERTY_PREFIX
+ Settings.System.RINGTONE);
mDefaultNotificationFilename = SystemProperties.get(DEFAULT_RINGTONE_PROPERTY_PREFIX
+ Settings.System.NOTIFICATION_SOUND);
mDefaultAlarmAlertFilename = SystemProperties.get(DEFAULT_RINGTONE_PROPERTY_PREFIX
+ Settings.System.ALARM_ALERT);
}
private final MyMediaScannerClient mClient = new MyMediaScannerClient();
private boolean isDrmEnabled() {
String prop = SystemProperties.get("drm.service.enabled");
return prop != null && prop.equals("true");
}
private class MyMediaScannerClient implements MediaScannerClient {
private String mArtist;
private String mAlbumArtist; // use this if mArtist is missing
private String mAlbum;
private String mTitle;
private String mComposer;
private String mGenre;
private String mMimeType;
private int mFileType;
private int mTrack;
private int mYear;
private int mDuration;
private String mPath;
private long mLastModified;
private long mFileSize;
private String mWriter;
private int mCompilation;
private boolean mIsDrm;
private boolean mNoMedia; // flag to suppress file from appearing in media tables
private int mWidth;
private int mHeight;
public FileEntry beginFile(String path, String mimeType, long lastModified,
long fileSize, boolean isDirectory, boolean noMedia) {
mMimeType = mimeType;
mFileType = 0;
mFileSize = fileSize;
mIsDrm = false;
if (!isDirectory) {
if (!noMedia && isNoMediaFile(path)) {
noMedia = true;
}
mNoMedia = noMedia;
// try mimeType first, if it is specified
if (mimeType != null) {
mFileType = MediaFile.getFileTypeForMimeType(mimeType);
}
// if mimeType was not specified, compute file type based on file extension.
if (mFileType == 0) {
MediaFile.MediaFileType mediaFileType = MediaFile.getFileType(path);
if (mediaFileType != null) {
mFileType = mediaFileType.fileType;
if (mMimeType == null) {
mMimeType = mediaFileType.mimeType;
}
}
}
if (isDrmEnabled() && MediaFile.isDrmFileType(mFileType)) {
mFileType = getFileTypeFromDrm(path);
}
}
FileEntry entry = makeEntryFor(path);
// add some slack to avoid a rounding error
long delta = (entry != null) ? (lastModified - entry.mLastModified) : 0;
boolean wasModified = delta > 1 || delta < -1;
if (entry == null || wasModified) {
if (wasModified) {
entry.mLastModified = lastModified;
} else {
entry = new FileEntry(0, path, lastModified,
(isDirectory ? MtpConstants.FORMAT_ASSOCIATION : 0));
}
entry.mLastModifiedChanged = true;
}
if (mProcessPlaylists && MediaFile.isPlayListFileType(mFileType)) {
mPlayLists.add(entry);
// we don't process playlists in the main scan, so return null
return null;
}
// clear all the metadata
mArtist = null;
mAlbumArtist = null;
mAlbum = null;
mTitle = null;
mComposer = null;
mGenre = null;
mTrack = 0;
mYear = 0;
mDuration = 0;
mPath = path;
mLastModified = lastModified;
mWriter = null;
mCompilation = 0;
mWidth = 0;
mHeight = 0;
return entry;
}
@Override
public void scanFile(String path, long lastModified, long fileSize,
boolean isDirectory, boolean noMedia) {
// This is the callback funtion from native codes.
// Log.v(TAG, "scanFile: "+path);
doScanFile(path, null, lastModified, fileSize, isDirectory, false, noMedia);
}
public Uri doScanFile(String path, String mimeType, long lastModified,
long fileSize, boolean isDirectory, boolean scanAlways, boolean noMedia) {
Uri result = null;
// long t1 = System.currentTimeMillis();
try {
FileEntry entry = beginFile(path, mimeType, lastModified,
fileSize, isDirectory, noMedia);
// if this file was just inserted via mtp, set the rowid to zero
// (even though it already exists in the database), to trigger
// the correct code path for updating its entry
if (mMtpObjectHandle != 0) {
entry.mRowId = 0;
}
// rescan for metadata if file was modified since last scan
if (entry != null && (entry.mLastModifiedChanged || scanAlways)) {
if (noMedia) {
result = endFile(entry, false, false, false, false, false);
} else {
String lowpath = path.toLowerCase(Locale.ROOT);
boolean ringtones = (lowpath.indexOf(RINGTONES_DIR) > 0);
boolean notifications = (lowpath.indexOf(NOTIFICATIONS_DIR) > 0);
boolean alarms = (lowpath.indexOf(ALARMS_DIR) > 0);
boolean podcasts = (lowpath.indexOf(PODCAST_DIR) > 0);
boolean music = (lowpath.indexOf(MUSIC_DIR) > 0) ||
(!ringtones && !notifications && !alarms && !podcasts);
boolean isaudio = MediaFile.isAudioFileType(mFileType);
boolean isvideo = MediaFile.isVideoFileType(mFileType);
boolean isimage = MediaFile.isImageFileType(mFileType);
if (isaudio || isvideo || isimage) {
if (mExternalIsEmulated && path.startsWith(mExternalStoragePath)) {
// try to rewrite the path to bypass the sd card fuse layer
String directPath = Environment.getMediaStorageDirectory() +
path.substring(mExternalStoragePath.length());
File f = new File(directPath);
if (f.exists()) {
path = directPath;
}
}
}
// we only extract metadata for audio and video files
if (isaudio || isvideo) {
processFile(path, mimeType, this);
}
if (isimage) {
processImageFile(path);
}
result = endFile(entry, ringtones, notifications, alarms, music, podcasts);
}
}
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in MediaScanner.scanFile()", e);
}
// long t2 = System.currentTimeMillis();
// Log.v(TAG, "scanFile: " + path + " took " + (t2-t1));
return result;
}
private int parseSubstring(String s, int start, int defaultValue) {
int length = s.length();
if (start == length) return defaultValue;
char ch = s.charAt(start++);
// return defaultValue if we have no integer at all
if (ch < '0' || ch > '9') return defaultValue;
int result = ch - '0';
while (start < length) {
ch = s.charAt(start++);
if (ch < '0' || ch > '9') return result;
result = result * 10 + (ch - '0');
}
return result;
}
public void handleStringTag(String name, String value) {
if (name.equalsIgnoreCase("title") || name.startsWith("title;")) {
// Don't trim() here, to preserve the special \001 character
// used to force sorting. The media provider will trim() before
// inserting the title in to the database.
mTitle = value;
} else if (name.equalsIgnoreCase("artist") || name.startsWith("artist;")) {
mArtist = value.trim();
} else if (name.equalsIgnoreCase("albumartist") || name.startsWith("albumartist;")
|| name.equalsIgnoreCase("band") || name.startsWith("band;")) {
mAlbumArtist = value.trim();
} else if (name.equalsIgnoreCase("album") || name.startsWith("album;")) {
mAlbum = value.trim();
} else if (name.equalsIgnoreCase("composer") || name.startsWith("composer;")) {
mComposer = value.trim();
} else if (mProcessGenres &&
(name.equalsIgnoreCase("genre") || name.startsWith("genre;"))) {
mGenre = getGenreName(value);
} else if (name.equalsIgnoreCase("year") || name.startsWith("year;")) {
mYear = parseSubstring(value, 0, 0);
} else if (name.equalsIgnoreCase("tracknumber") || name.startsWith("tracknumber;")) {
// track number might be of the form "2/12"
// we just read the number before the slash
int num = parseSubstring(value, 0, 0);
mTrack = (mTrack / 1000) * 1000 + num;
} else if (name.equalsIgnoreCase("discnumber") ||
name.equals("set") || name.startsWith("set;")) {
// set number might be of the form "1/3"
// we just read the number before the slash
int num = parseSubstring(value, 0, 0);
mTrack = (num * 1000) + (mTrack % 1000);
} else if (name.equalsIgnoreCase("duration")) {
mDuration = parseSubstring(value, 0, 0);
} else if (name.equalsIgnoreCase("writer") || name.startsWith("writer;")) {
mWriter = value.trim();
} else if (name.equalsIgnoreCase("compilation")) {
mCompilation = parseSubstring(value, 0, 0);
} else if (name.equalsIgnoreCase("isdrm")) {
mIsDrm = (parseSubstring(value, 0, 0) == 1);
} else if (name.equalsIgnoreCase("width")) {
mWidth = parseSubstring(value, 0, 0);
} else if (name.equalsIgnoreCase("height")) {
mHeight = parseSubstring(value, 0, 0);
} else {
//Log.v(TAG, "unknown tag: " + name + " (" + mProcessGenres + ")");
}
}
private boolean convertGenreCode(String input, String expected) {
String output = getGenreName(input);
if (output.equals(expected)) {
return true;
} else {
Log.d(TAG, "'" + input + "' -> '" + output + "', expected '" + expected + "'");
return false;
}
}
private void testGenreNameConverter() {
convertGenreCode("2", "Country");
convertGenreCode("(2)", "Country");
convertGenreCode("(2", "(2");
convertGenreCode("2 Foo", "Country");
convertGenreCode("(2) Foo", "Country");
convertGenreCode("(2 Foo", "(2 Foo");
convertGenreCode("2Foo", "2Foo");
convertGenreCode("(2)Foo", "Country");
convertGenreCode("200 Foo", "Foo");
convertGenreCode("(200) Foo", "Foo");
convertGenreCode("200Foo", "200Foo");
convertGenreCode("(200)Foo", "Foo");
convertGenreCode("200)Foo", "200)Foo");
convertGenreCode("200) Foo", "200) Foo");
}
public String getGenreName(String genreTagValue) {
if (genreTagValue == null) {
return null;
}
final int length = genreTagValue.length();
if (length > 0) {
boolean parenthesized = false;
StringBuffer number = new StringBuffer();
int i = 0;
for (; i < length; ++i) {
char c = genreTagValue.charAt(i);
if (i == 0 && c == '(') {
parenthesized = true;
} else if (Character.isDigit(c)) {
number.append(c);
} else {
break;
}
}
char charAfterNumber = i < length ? genreTagValue.charAt(i) : ' ';
if ((parenthesized && charAfterNumber == ')')
|| !parenthesized && Character.isWhitespace(charAfterNumber)) {
try {
short genreIndex = Short.parseShort(number.toString());
if (genreIndex >= 0) {
if (genreIndex < ID3_GENRES.length && ID3_GENRES[genreIndex] != null) {
return ID3_GENRES[genreIndex];
} else if (genreIndex == 0xFF) {
return null;
} else if (genreIndex < 0xFF && (i + 1) < length) {
// genre is valid but unknown,
// if there is a string after the value we take it
if (parenthesized && charAfterNumber == ')') {
i++;
}
String ret = genreTagValue.substring(i).trim();
if (ret.length() != 0) {
return ret;
}
} else {
// else return the number, without parentheses
return number.toString();
}
}
} catch (NumberFormatException e) {
}
}
}
return genreTagValue;
}
private void processImageFile(String path) {
try {
mBitmapOptions.outWidth = 0;
mBitmapOptions.outHeight = 0;
BitmapFactory.decodeFile(path, mBitmapOptions);
mWidth = mBitmapOptions.outWidth;
mHeight = mBitmapOptions.outHeight;
} catch (Throwable th) {
// ignore;
}
}
public void setMimeType(String mimeType) {
if ("audio/mp4".equals(mMimeType) &&
mimeType.startsWith("video")) {
// for feature parity with Donut, we force m4a files to keep the
// audio/mp4 mimetype, even if they are really "enhanced podcasts"
// with a video track
return;
}
mMimeType = mimeType;
mFileType = MediaFile.getFileTypeForMimeType(mimeType);
}
/**
* Formats the data into a values array suitable for use with the Media
* Content Provider.
*
* @return a map of values
*/
private ContentValues toValues() {
ContentValues map = new ContentValues();
map.put(MediaStore.MediaColumns.DATA, mPath);
map.put(MediaStore.MediaColumns.TITLE, mTitle);
map.put(MediaStore.MediaColumns.DATE_MODIFIED, mLastModified);
map.put(MediaStore.MediaColumns.SIZE, mFileSize);
map.put(MediaStore.MediaColumns.MIME_TYPE, mMimeType);
map.put(MediaStore.MediaColumns.IS_DRM, mIsDrm);
String resolution = null;
if (mWidth > 0 && mHeight > 0) {
map.put(MediaStore.MediaColumns.WIDTH, mWidth);
map.put(MediaStore.MediaColumns.HEIGHT, mHeight);
resolution = mWidth + "x" + mHeight;
}
if (!mNoMedia) {
if (MediaFile.isVideoFileType(mFileType)) {
map.put(Video.Media.ARTIST, (mArtist != null && mArtist.length() > 0
? mArtist : MediaStore.UNKNOWN_STRING));
map.put(Video.Media.ALBUM, (mAlbum != null && mAlbum.length() > 0
? mAlbum : MediaStore.UNKNOWN_STRING));
map.put(Video.Media.DURATION, mDuration);
if (resolution != null) {
map.put(Video.Media.RESOLUTION, resolution);
}
} else if (MediaFile.isImageFileType(mFileType)) {
// FIXME - add DESCRIPTION
} else if (MediaFile.isAudioFileType(mFileType)) {
map.put(Audio.Media.ARTIST, (mArtist != null && mArtist.length() > 0) ?
mArtist : MediaStore.UNKNOWN_STRING);
map.put(Audio.Media.ALBUM_ARTIST, (mAlbumArtist != null &&
mAlbumArtist.length() > 0) ? mAlbumArtist : null);
map.put(Audio.Media.ALBUM, (mAlbum != null && mAlbum.length() > 0) ?
mAlbum : MediaStore.UNKNOWN_STRING);
map.put(Audio.Media.COMPOSER, mComposer);
map.put(Audio.Media.GENRE, mGenre);
if (mYear != 0) {
map.put(Audio.Media.YEAR, mYear);
}
map.put(Audio.Media.TRACK, mTrack);
map.put(Audio.Media.DURATION, mDuration);
map.put(Audio.Media.COMPILATION, mCompilation);
}
}
return map;
}
private Uri endFile(FileEntry entry, boolean ringtones, boolean notifications,
boolean alarms, boolean music, boolean podcasts)
throws RemoteException {
// update database
// use album artist if artist is missing
if (mArtist == null || mArtist.length() == 0) {
mArtist = mAlbumArtist;
}
ContentValues values = toValues();
String title = values.getAsString(MediaStore.MediaColumns.TITLE);
if (title == null || TextUtils.isEmpty(title.trim())) {
title = MediaFile.getFileTitle(values.getAsString(MediaStore.MediaColumns.DATA));
values.put(MediaStore.MediaColumns.TITLE, title);
}
String album = values.getAsString(Audio.Media.ALBUM);
if (MediaStore.UNKNOWN_STRING.equals(album)) {
album = values.getAsString(MediaStore.MediaColumns.DATA);
// extract last path segment before file name
int lastSlash = album.lastIndexOf('/');
if (lastSlash >= 0) {
int previousSlash = 0;
while (true) {
int idx = album.indexOf('/', previousSlash + 1);
if (idx < 0 || idx >= lastSlash) {
break;
}
previousSlash = idx;
}
if (previousSlash != 0) {
album = album.substring(previousSlash + 1, lastSlash);
values.put(Audio.Media.ALBUM, album);
}
}
}
long rowId = entry.mRowId;
if (MediaFile.isAudioFileType(mFileType) && (rowId == 0 || mMtpObjectHandle != 0)) {
// Only set these for new entries. For existing entries, they
// may have been modified later, and we want to keep the current
// values so that custom ringtones still show up in the ringtone
// picker.
values.put(Audio.Media.IS_RINGTONE, ringtones);
values.put(Audio.Media.IS_NOTIFICATION, notifications);
values.put(Audio.Media.IS_ALARM, alarms);
values.put(Audio.Media.IS_MUSIC, music);
values.put(Audio.Media.IS_PODCAST, podcasts);
} else if (mFileType == MediaFile.FILE_TYPE_JPEG && !mNoMedia) {
ExifInterface exif = null;
try {
exif = new ExifInterface(entry.mPath);
} catch (IOException ex) {
// exif is null
}
if (exif != null) {
float[] latlng = new float[2];
if (exif.getLatLong(latlng)) {
values.put(Images.Media.LATITUDE, latlng[0]);
values.put(Images.Media.LONGITUDE, latlng[1]);
}
long time = exif.getGpsDateTime();
if (time != -1) {
values.put(Images.Media.DATE_TAKEN, time);
} else {
// If no time zone information is available, we should consider using
// EXIF local time as taken time if the difference between file time
// and EXIF local time is not less than 1 Day, otherwise MediaProvider
// will use file time as taken time.
time = exif.getDateTime();
if (time != -1 && Math.abs(mLastModified * 1000 - time) >= 86400000) {
values.put(Images.Media.DATE_TAKEN, time);
}
}
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, -1);
if (orientation != -1) {
// We only recognize a subset of orientation tag values.
int degree;
switch(orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
default:
degree = 0;
break;
}
values.put(Images.Media.ORIENTATION, degree);
}
}
}
Uri tableUri = mFilesUri;
MediaInserter inserter = mMediaInserter;
if (!mNoMedia) {
if (MediaFile.isVideoFileType(mFileType)) {
tableUri = mVideoUri;
} else if (MediaFile.isImageFileType(mFileType)) {
tableUri = mImagesUri;
} else if (MediaFile.isAudioFileType(mFileType)) {
tableUri = mAudioUri;
}
}
Uri result = null;
boolean needToSetSettings = false;
if (rowId == 0) {
if (mMtpObjectHandle != 0) {
values.put(MediaStore.MediaColumns.MEDIA_SCANNER_NEW_OBJECT_ID, mMtpObjectHandle);
}
if (tableUri == mFilesUri) {
int format = entry.mFormat;
if (format == 0) {
format = MediaFile.getFormatCode(entry.mPath, mMimeType);
}
values.put(Files.FileColumns.FORMAT, format);
}
// Setting a flag in order not to use bulk insert for the file related with
// notifications, ringtones, and alarms, because the rowId of the inserted file is
// needed.
if (mWasEmptyPriorToScan) {
if (notifications && !mDefaultNotificationSet) {
if (TextUtils.isEmpty(mDefaultNotificationFilename) ||
doesPathHaveFilename(entry.mPath, mDefaultNotificationFilename)) {
needToSetSettings = true;
}
} else if (ringtones && !mDefaultRingtoneSet) {
if (TextUtils.isEmpty(mDefaultRingtoneFilename) ||
doesPathHaveFilename(entry.mPath, mDefaultRingtoneFilename)) {
needToSetSettings = true;
}
} else if (alarms && !mDefaultAlarmSet) {
if (TextUtils.isEmpty(mDefaultAlarmAlertFilename) ||
doesPathHaveFilename(entry.mPath, mDefaultAlarmAlertFilename)) {
needToSetSettings = true;
}
}
}
// New file, insert it.
// Directories need to be inserted before the files they contain, so they
// get priority when bulk inserting.
// If the rowId of the inserted file is needed, it gets inserted immediately,
// bypassing the bulk inserter.
if (inserter == null || needToSetSettings) {
if (inserter != null) {
inserter.flushAll();
}
result = mMediaProvider.insert(mPackageName, tableUri, values);
} else if (entry.mFormat == MtpConstants.FORMAT_ASSOCIATION) {
inserter.insertwithPriority(tableUri, values);
} else {
inserter.insert(tableUri, values);
}
if (result != null) {
rowId = ContentUris.parseId(result);
entry.mRowId = rowId;
}
} else {
// updated file
result = ContentUris.withAppendedId(tableUri, rowId);
// path should never change, and we want to avoid replacing mixed cased paths
// with squashed lower case paths
values.remove(MediaStore.MediaColumns.DATA);
int mediaType = 0;
if (!MediaScanner.isNoMediaPath(entry.mPath)) {
int fileType = MediaFile.getFileTypeForMimeType(mMimeType);
if (MediaFile.isAudioFileType(fileType)) {
mediaType = FileColumns.MEDIA_TYPE_AUDIO;
} else if (MediaFile.isVideoFileType(fileType)) {
mediaType = FileColumns.MEDIA_TYPE_VIDEO;
} else if (MediaFile.isImageFileType(fileType)) {
mediaType = FileColumns.MEDIA_TYPE_IMAGE;
} else if (MediaFile.isPlayListFileType(fileType)) {
mediaType = FileColumns.MEDIA_TYPE_PLAYLIST;
}
values.put(FileColumns.MEDIA_TYPE, mediaType);
}
mMediaProvider.update(mPackageName, result, values, null, null);
}
if(needToSetSettings) {
if (notifications) {
setSettingIfNotSet(Settings.System.NOTIFICATION_SOUND, tableUri, rowId);
mDefaultNotificationSet = true;
} else if (ringtones) {
setSettingIfNotSet(Settings.System.RINGTONE, tableUri, rowId);
mDefaultRingtoneSet = true;
} else if (alarms) {
setSettingIfNotSet(Settings.System.ALARM_ALERT, tableUri, rowId);
mDefaultAlarmSet = true;
}
}
return result;
}
private boolean doesPathHaveFilename(String path, String filename) {
int pathFilenameStart = path.lastIndexOf(File.separatorChar) + 1;
int filenameLength = filename.length();
return path.regionMatches(pathFilenameStart, filename, 0, filenameLength) &&
pathFilenameStart + filenameLength == path.length();
}
private void setSettingIfNotSet(String settingName, Uri uri, long rowId) {
String existingSettingValue = Settings.System.getString(mContext.getContentResolver(),
settingName);
if (TextUtils.isEmpty(existingSettingValue)) {
// Set the setting to the given URI
Settings.System.putString(mContext.getContentResolver(), settingName,
ContentUris.withAppendedId(uri, rowId).toString());
}
}
private int getFileTypeFromDrm(String path) {
if (!isDrmEnabled()) {
return 0;
}
int resultFileType = 0;
if (mDrmManagerClient == null) {
mDrmManagerClient = new DrmManagerClient(mContext);
}
if (mDrmManagerClient.canHandle(path, null)) {
mIsDrm = true;
String drmMimetype = mDrmManagerClient.getOriginalMimeType(path);
if (drmMimetype != null) {
mMimeType = drmMimetype;
resultFileType = MediaFile.getFileTypeForMimeType(drmMimetype);
}
}
return resultFileType;
}
}; // end of anonymous MediaScannerClient instance
private void prescan(String filePath, boolean prescanFiles) throws RemoteException {
Cursor c = null;
String where = null;
String[] selectionArgs = null;
if (mPlayLists == null) {
mPlayLists = new ArrayList<FileEntry>();
} else {
mPlayLists.clear();
}
if (filePath != null) {
// query for only one file
where = MediaStore.Files.FileColumns._ID + ">?" +
" AND " + Files.FileColumns.DATA + "=?";
selectionArgs = new String[] { "", filePath };
} else {
where = MediaStore.Files.FileColumns._ID + ">?";
selectionArgs = new String[] { "" };
}
// Tell the provider to not delete the file.
// If the file is truly gone the delete is unnecessary, and we want to avoid
// accidentally deleting files that are really there (this may happen if the
// filesystem is mounted and unmounted while the scanner is running).
Uri.Builder builder = mFilesUri.buildUpon();
builder.appendQueryParameter(MediaStore.PARAM_DELETE_DATA, "false");
MediaBulkDeleter deleter = new MediaBulkDeleter(mMediaProvider, mPackageName,
builder.build());
// Build the list of files from the content provider
try {
if (prescanFiles) {
// First read existing files from the files table.
// Because we'll be deleting entries for missing files as we go,
// we need to query the database in small batches, to avoid problems
// with CursorWindow positioning.
long lastId = Long.MIN_VALUE;
Uri limitUri = mFilesUri.buildUpon().appendQueryParameter("limit", "1000").build();
mWasEmptyPriorToScan = true;
while (true) {
selectionArgs[0] = "" + lastId;
if (c != null) {
c.close();
c = null;
}
c = mMediaProvider.query(mPackageName, limitUri, FILES_PRESCAN_PROJECTION,
where, selectionArgs, MediaStore.Files.FileColumns._ID, null);
if (c == null) {
break;
}
int num = c.getCount();
if (num == 0) {
break;
}
mWasEmptyPriorToScan = false;
while (c.moveToNext()) {
long rowId = c.getLong(FILES_PRESCAN_ID_COLUMN_INDEX);
String path = c.getString(FILES_PRESCAN_PATH_COLUMN_INDEX);
int format = c.getInt(FILES_PRESCAN_FORMAT_COLUMN_INDEX);
long lastModified = c.getLong(FILES_PRESCAN_DATE_MODIFIED_COLUMN_INDEX);
lastId = rowId;
// Only consider entries with absolute path names.
// This allows storing URIs in the database without the
// media scanner removing them.
if (path != null && path.startsWith("/")) {
boolean exists = false;
try {
exists = Libcore.os.access(path, libcore.io.OsConstants.F_OK);
} catch (ErrnoException e1) {
}
if (!exists && !MtpConstants.isAbstractObject(format)) {
// do not delete missing playlists, since they may have been
// modified by the user.
// The user can delete them in the media player instead.
// instead, clear the path and lastModified fields in the row
MediaFile.MediaFileType mediaFileType = MediaFile.getFileType(path);
int fileType = (mediaFileType == null ? 0 : mediaFileType.fileType);
if (!MediaFile.isPlayListFileType(fileType)) {
deleter.delete(rowId);
if (path.toLowerCase(Locale.US).endsWith("/.nomedia")) {
deleter.flush();
String parent = new File(path).getParent();
mMediaProvider.call(mPackageName, MediaStore.UNHIDE_CALL,
parent, null);
}
}
}
}
}
}
}
}
finally {
if (c != null) {
c.close();
}
deleter.flush();
}
// compute original size of images
mOriginalCount = 0;
c = mMediaProvider.query(mPackageName, mImagesUri, ID_PROJECTION, null, null, null, null);
if (c != null) {
mOriginalCount = c.getCount();
c.close();
}
}
private boolean inScanDirectory(String path, String[] directories) {
for (int i = 0; i < directories.length; i++) {
String directory = directories[i];
if (path.startsWith(directory)) {
return true;
}
}
return false;
}
private void pruneDeadThumbnailFiles() {
HashSet<String> existingFiles = new HashSet<String>();
String directory = "/sdcard/DCIM/.thumbnails";
String [] files = (new File(directory)).list();
if (files == null)
files = new String[0];
for (int i = 0; i < files.length; i++) {
String fullPathString = directory + "/" + files[i];
existingFiles.add(fullPathString);
}
try {
Cursor c = mMediaProvider.query(
mPackageName,
mThumbsUri,
new String [] { "_data" },
null,
null,
null, null);
Log.v(TAG, "pruneDeadThumbnailFiles... " + c);
if (c != null && c.moveToFirst()) {
do {
String fullPathString = c.getString(0);
existingFiles.remove(fullPathString);
} while (c.moveToNext());
}
for (String fileToDelete : existingFiles) {
if (false)
Log.v(TAG, "fileToDelete is " + fileToDelete);
try {
(new File(fileToDelete)).delete();
} catch (SecurityException ex) {
}
}
Log.v(TAG, "/pruneDeadThumbnailFiles... " + c);
if (c != null) {
c.close();
}
} catch (RemoteException e) {
// We will soon be killed...
}
}
static class MediaBulkDeleter {
StringBuilder whereClause = new StringBuilder();
ArrayList<String> whereArgs = new ArrayList<String>(100);
final IContentProvider mProvider;
final String mPackageName;
final Uri mBaseUri;
public MediaBulkDeleter(IContentProvider provider, String packageName, Uri baseUri) {
mProvider = provider;
mPackageName = packageName;
mBaseUri = baseUri;
}
public void delete(long id) throws RemoteException {
if (whereClause.length() != 0) {
whereClause.append(",");
}
whereClause.append("?");
whereArgs.add("" + id);
if (whereArgs.size() > 100) {
flush();
}
}
public void flush() throws RemoteException {
int size = whereArgs.size();
if (size > 0) {
String [] foo = new String [size];
foo = whereArgs.toArray(foo);
int numrows = mProvider.delete(mPackageName, mBaseUri,
MediaStore.MediaColumns._ID + " IN (" +
whereClause.toString() + ")", foo);
//Log.i("@@@@@@@@@", "rows deleted: " + numrows);
whereClause.setLength(0);
whereArgs.clear();
}
}
}
private void postscan(String[] directories) throws RemoteException {
// handle playlists last, after we know what media files are on the storage.
if (mProcessPlaylists) {
processPlayLists();
}
if (mOriginalCount == 0 && mImagesUri.equals(Images.Media.getContentUri("external")))
pruneDeadThumbnailFiles();
// allow GC to clean up
mPlayLists = null;
mMediaProvider = null;
}
private void initialize(String volumeName) {
mMediaProvider = mContext.getContentResolver().acquireProvider("media");
mAudioUri = Audio.Media.getContentUri(volumeName);
mVideoUri = Video.Media.getContentUri(volumeName);
mImagesUri = Images.Media.getContentUri(volumeName);
mThumbsUri = Images.Thumbnails.getContentUri(volumeName);
mFilesUri = Files.getContentUri(volumeName);
mFilesUriNoNotify = mFilesUri.buildUpon().appendQueryParameter("nonotify", "1").build();
if (!volumeName.equals("internal")) {
// we only support playlists on external media
mProcessPlaylists = true;
mProcessGenres = true;
mPlaylistsUri = Playlists.getContentUri(volumeName);
mCaseInsensitivePaths = true;
}
}
public void scanDirectories(String[] directories, String volumeName) {
try {
long start = System.currentTimeMillis();
initialize(volumeName);
prescan(null, true);
long prescan = System.currentTimeMillis();
if (ENABLE_BULK_INSERTS) {
// create MediaInserter for bulk inserts
mMediaInserter = new MediaInserter(mMediaProvider, mPackageName, 500);
}
for (int i = 0; i < directories.length; i++) {
processDirectory(directories[i], mClient);
}
if (ENABLE_BULK_INSERTS) {
// flush remaining inserts
mMediaInserter.flushAll();
mMediaInserter = null;
}
long scan = System.currentTimeMillis();
postscan(directories);
long end = System.currentTimeMillis();
if (false) {
Log.d(TAG, " prescan time: " + (prescan - start) + "ms\n");
Log.d(TAG, " scan time: " + (scan - prescan) + "ms\n");
Log.d(TAG, "postscan time: " + (end - scan) + "ms\n");
Log.d(TAG, " total time: " + (end - start) + "ms\n");
}
} catch (SQLException e) {
// this might happen if the SD card is removed while the media scanner is running
Log.e(TAG, "SQLException in MediaScanner.scan()", e);
} catch (UnsupportedOperationException e) {
// this might happen if the SD card is removed while the media scanner is running
Log.e(TAG, "UnsupportedOperationException in MediaScanner.scan()", e);
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in MediaScanner.scan()", e);
}
}
// this function is used to scan a single file
public Uri scanSingleFile(String path, String volumeName, String mimeType) {
try {
initialize(volumeName);
prescan(path, true);
File file = new File(path);
if (!file.exists()) {
return null;
}
// lastModified is in milliseconds on Files.
long lastModifiedSeconds = file.lastModified() / 1000;
// always scan the file, so we can return the content://media Uri for existing files
return mClient.doScanFile(path, mimeType, lastModifiedSeconds, file.length(),
false, true, MediaScanner.isNoMediaPath(path));
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in MediaScanner.scanFile()", e);
return null;
}
}
private static boolean isNoMediaFile(String path) {
File file = new File(path);
if (file.isDirectory()) return false;
// special case certain file names
// I use regionMatches() instead of substring() below
// to avoid memory allocation
int lastSlash = path.lastIndexOf('/');
if (lastSlash >= 0 && lastSlash + 2 < path.length()) {
// ignore those ._* files created by MacOS
if (path.regionMatches(lastSlash + 1, "._", 0, 2)) {
return true;
}
// ignore album art files created by Windows Media Player:
// Folder.jpg, AlbumArtSmall.jpg, AlbumArt_{...}_Large.jpg
// and AlbumArt_{...}_Small.jpg
if (path.regionMatches(true, path.length() - 4, ".jpg", 0, 4)) {
if (path.regionMatches(true, lastSlash + 1, "AlbumArt_{", 0, 10) ||
path.regionMatches(true, lastSlash + 1, "AlbumArt.", 0, 9)) {
return true;
}
int length = path.length() - lastSlash - 1;
if ((length == 17 && path.regionMatches(
true, lastSlash + 1, "AlbumArtSmall", 0, 13)) ||
(length == 10
&& path.regionMatches(true, lastSlash + 1, "Folder", 0, 6))) {
return true;
}
}
}
return false;
}
public static boolean isNoMediaPath(String path) {
if (path == null) return false;
// return true if file or any parent directory has name starting with a dot
if (path.indexOf("/.") >= 0) return true;
// now check to see if any parent directories have a ".nomedia" file
// start from 1 so we don't bother checking in the root directory
int offset = 1;
while (offset >= 0) {
int slashIndex = path.indexOf('/', offset);
if (slashIndex > offset) {
slashIndex++; // move past slash
File file = new File(path.substring(0, slashIndex) + ".nomedia");
if (file.exists()) {
// we have a .nomedia in one of the parent directories
return true;
}
}
offset = slashIndex;
}
return isNoMediaFile(path);
}
public void scanMtpFile(String path, String volumeName, int objectHandle, int format) {
initialize(volumeName);
MediaFile.MediaFileType mediaFileType = MediaFile.getFileType(path);
int fileType = (mediaFileType == null ? 0 : mediaFileType.fileType);
File file = new File(path);
long lastModifiedSeconds = file.lastModified() / 1000;
if (!MediaFile.isAudioFileType(fileType) && !MediaFile.isVideoFileType(fileType) &&
!MediaFile.isImageFileType(fileType) && !MediaFile.isPlayListFileType(fileType) &&
!MediaFile.isDrmFileType(fileType)) {
// no need to use the media scanner, but we need to update last modified and file size
ContentValues values = new ContentValues();
values.put(Files.FileColumns.SIZE, file.length());
values.put(Files.FileColumns.DATE_MODIFIED, lastModifiedSeconds);
try {
String[] whereArgs = new String[] { Integer.toString(objectHandle) };
mMediaProvider.update(mPackageName, Files.getMtpObjectsUri(volumeName), values,
"_id=?", whereArgs);
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in scanMtpFile", e);
}
return;
}
mMtpObjectHandle = objectHandle;
Cursor fileList = null;
try {
if (MediaFile.isPlayListFileType(fileType)) {
// build file cache so we can look up tracks in the playlist
prescan(null, true);
FileEntry entry = makeEntryFor(path);
if (entry != null) {
fileList = mMediaProvider.query(mPackageName, mFilesUri,
FILES_PRESCAN_PROJECTION, null, null, null, null);
processPlayList(entry, fileList);
}
} else {
// MTP will create a file entry for us so we don't want to do it in prescan
prescan(path, false);
// always scan the file, so we can return the content://media Uri for existing files
mClient.doScanFile(path, mediaFileType.mimeType, lastModifiedSeconds, file.length(),
(format == MtpConstants.FORMAT_ASSOCIATION), true, isNoMediaPath(path));
}
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in MediaScanner.scanFile()", e);
} finally {
mMtpObjectHandle = 0;
if (fileList != null) {
fileList.close();
}
}
}
FileEntry makeEntryFor(String path) {
String where;
String[] selectionArgs;
Cursor c = null;
try {
where = Files.FileColumns.DATA + "=?";
selectionArgs = new String[] { path };
c = mMediaProvider.query(mPackageName, mFilesUriNoNotify, FILES_PRESCAN_PROJECTION,
where, selectionArgs, null, null);
if (c.moveToFirst()) {
long rowId = c.getLong(FILES_PRESCAN_ID_COLUMN_INDEX);
int format = c.getInt(FILES_PRESCAN_FORMAT_COLUMN_INDEX);
long lastModified = c.getLong(FILES_PRESCAN_DATE_MODIFIED_COLUMN_INDEX);
return new FileEntry(rowId, path, lastModified, format);
}
} catch (RemoteException e) {
} finally {
if (c != null) {
c.close();
}
}
return null;
}
// returns the number of matching file/directory names, starting from the right
private int matchPaths(String path1, String path2) {
int result = 0;
int end1 = path1.length();
int end2 = path2.length();
while (end1 > 0 && end2 > 0) {
int slash1 = path1.lastIndexOf('/', end1 - 1);
int slash2 = path2.lastIndexOf('/', end2 - 1);
int backSlash1 = path1.lastIndexOf('\\', end1 - 1);
int backSlash2 = path2.lastIndexOf('\\', end2 - 1);
int start1 = (slash1 > backSlash1 ? slash1 : backSlash1);
int start2 = (slash2 > backSlash2 ? slash2 : backSlash2);
if (start1 < 0) start1 = 0; else start1++;
if (start2 < 0) start2 = 0; else start2++;
int length = end1 - start1;
if (end2 - start2 != length) break;
if (path1.regionMatches(true, start1, path2, start2, length)) {
result++;
end1 = start1 - 1;
end2 = start2 - 1;
} else break;
}
return result;
}
private boolean matchEntries(long rowId, String data) {
int len = mPlaylistEntries.size();
boolean done = true;
for (int i = 0; i < len; i++) {
PlaylistEntry entry = mPlaylistEntries.get(i);
if (entry.bestmatchlevel == Integer.MAX_VALUE) {
continue; // this entry has been matched already
}
done = false;
if (data.equalsIgnoreCase(entry.path)) {
entry.bestmatchid = rowId;
entry.bestmatchlevel = Integer.MAX_VALUE;
continue; // no need for path matching
}
int matchLength = matchPaths(data, entry.path);
if (matchLength > entry.bestmatchlevel) {
entry.bestmatchid = rowId;
entry.bestmatchlevel = matchLength;
}
}
return done;
}
private void cachePlaylistEntry(String line, String playListDirectory) {
PlaylistEntry entry = new PlaylistEntry();
// watch for trailing whitespace
int entryLength = line.length();
while (entryLength > 0 && Character.isWhitespace(line.charAt(entryLength - 1))) entryLength--;
// path should be longer than 3 characters.
// avoid index out of bounds errors below by returning here.
if (entryLength < 3) return;
if (entryLength < line.length()) line = line.substring(0, entryLength);
// does entry appear to be an absolute path?
// look for Unix or DOS absolute paths
char ch1 = line.charAt(0);
boolean fullPath = (ch1 == '/' ||
(Character.isLetter(ch1) && line.charAt(1) == ':' && line.charAt(2) == '\\'));
// if we have a relative path, combine entry with playListDirectory
if (!fullPath)
line = playListDirectory + line;
entry.path = line;
//FIXME - should we look for "../" within the path?
mPlaylistEntries.add(entry);
}
private void processCachedPlaylist(Cursor fileList, ContentValues values, Uri playlistUri) {
fileList.moveToPosition(-1);
while (fileList.moveToNext()) {
long rowId = fileList.getLong(FILES_PRESCAN_ID_COLUMN_INDEX);
String data = fileList.getString(FILES_PRESCAN_PATH_COLUMN_INDEX);
if (matchEntries(rowId, data)) {
break;
}
}
int len = mPlaylistEntries.size();
int index = 0;
for (int i = 0; i < len; i++) {
PlaylistEntry entry = mPlaylistEntries.get(i);
if (entry.bestmatchlevel > 0) {
try {
values.clear();
values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, Integer.valueOf(index));
values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, Long.valueOf(entry.bestmatchid));
mMediaProvider.insert(mPackageName, playlistUri, values);
index++;
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in MediaScanner.processCachedPlaylist()", e);
return;
}
}
}
mPlaylistEntries.clear();
}
private void processM3uPlayList(String path, String playListDirectory, Uri uri,
ContentValues values, Cursor fileList) {
BufferedReader reader = null;
try {
File f = new File(path);
if (f.exists()) {
reader = new BufferedReader(
new InputStreamReader(new FileInputStream(f)), 8192);
String line = reader.readLine();
mPlaylistEntries.clear();
while (line != null) {
// ignore comment lines, which begin with '#'
if (line.length() > 0 && line.charAt(0) != '#') {
cachePlaylistEntry(line, playListDirectory);
}
line = reader.readLine();
}
processCachedPlaylist(fileList, values, uri);
}
} catch (IOException e) {
Log.e(TAG, "IOException in MediaScanner.processM3uPlayList()", e);
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
Log.e(TAG, "IOException in MediaScanner.processM3uPlayList()", e);
}
}
}
private void processPlsPlayList(String path, String playListDirectory, Uri uri,
ContentValues values, Cursor fileList) {
BufferedReader reader = null;
try {
File f = new File(path);
if (f.exists()) {
reader = new BufferedReader(
new InputStreamReader(new FileInputStream(f)), 8192);
String line = reader.readLine();
mPlaylistEntries.clear();
while (line != null) {
// ignore comment lines, which begin with '#'
if (line.startsWith("File")) {
int equals = line.indexOf('=');
if (equals > 0) {
cachePlaylistEntry(line.substring(equals + 1), playListDirectory);
}
}
line = reader.readLine();
}
processCachedPlaylist(fileList, values, uri);
}
} catch (IOException e) {
Log.e(TAG, "IOException in MediaScanner.processPlsPlayList()", e);
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
Log.e(TAG, "IOException in MediaScanner.processPlsPlayList()", e);
}
}
}
class WplHandler implements ElementListener {
final ContentHandler handler;
String playListDirectory;
public WplHandler(String playListDirectory, Uri uri, Cursor fileList) {
this.playListDirectory = playListDirectory;
RootElement root = new RootElement("smil");
Element body = root.getChild("body");
Element seq = body.getChild("seq");
Element media = seq.getChild("media");
media.setElementListener(this);
this.handler = root.getContentHandler();
}
@Override
public void start(Attributes attributes) {
String path = attributes.getValue("", "src");
if (path != null) {
cachePlaylistEntry(path, playListDirectory);
}
}
@Override
public void end() {
}
ContentHandler getContentHandler() {
return handler;
}
}
private void processWplPlayList(String path, String playListDirectory, Uri uri,
ContentValues values, Cursor fileList) {
FileInputStream fis = null;
try {
File f = new File(path);
if (f.exists()) {
fis = new FileInputStream(f);
mPlaylistEntries.clear();
Xml.parse(fis, Xml.findEncodingByName("UTF-8"),
new WplHandler(playListDirectory, uri, fileList).getContentHandler());
processCachedPlaylist(fileList, values, uri);
}
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
Log.e(TAG, "IOException in MediaScanner.processWplPlayList()", e);
}
}
}
private void processPlayList(FileEntry entry, Cursor fileList) throws RemoteException {
String path = entry.mPath;
ContentValues values = new ContentValues();
int lastSlash = path.lastIndexOf('/');
if (lastSlash < 0) throw new IllegalArgumentException("bad path " + path);
Uri uri, membersUri;
long rowId = entry.mRowId;
// make sure we have a name
String name = values.getAsString(MediaStore.Audio.Playlists.NAME);
if (name == null) {
name = values.getAsString(MediaStore.MediaColumns.TITLE);
if (name == null) {
// extract name from file name
int lastDot = path.lastIndexOf('.');
name = (lastDot < 0 ? path.substring(lastSlash + 1)
: path.substring(lastSlash + 1, lastDot));
}
}
values.put(MediaStore.Audio.Playlists.NAME, name);
values.put(MediaStore.Audio.Playlists.DATE_MODIFIED, entry.mLastModified);
if (rowId == 0) {
values.put(MediaStore.Audio.Playlists.DATA, path);
uri = mMediaProvider.insert(mPackageName, mPlaylistsUri, values);
rowId = ContentUris.parseId(uri);
membersUri = Uri.withAppendedPath(uri, Playlists.Members.CONTENT_DIRECTORY);
} else {
uri = ContentUris.withAppendedId(mPlaylistsUri, rowId);
mMediaProvider.update(mPackageName, uri, values, null, null);
// delete members of existing playlist
membersUri = Uri.withAppendedPath(uri, Playlists.Members.CONTENT_DIRECTORY);
mMediaProvider.delete(mPackageName, membersUri, null, null);
}
String playListDirectory = path.substring(0, lastSlash + 1);
MediaFile.MediaFileType mediaFileType = MediaFile.getFileType(path);
int fileType = (mediaFileType == null ? 0 : mediaFileType.fileType);
if (fileType == MediaFile.FILE_TYPE_M3U) {
processM3uPlayList(path, playListDirectory, membersUri, values, fileList);
} else if (fileType == MediaFile.FILE_TYPE_PLS) {
processPlsPlayList(path, playListDirectory, membersUri, values, fileList);
} else if (fileType == MediaFile.FILE_TYPE_WPL) {
processWplPlayList(path, playListDirectory, membersUri, values, fileList);
}
}
private void processPlayLists() throws RemoteException {
Iterator<FileEntry> iterator = mPlayLists.iterator();
Cursor fileList = null;
try {
// use the files uri and projection because we need the format column,
// but restrict the query to just audio files
fileList = mMediaProvider.query(mPackageName, mFilesUri, FILES_PRESCAN_PROJECTION,
"media_type=2", null, null, null);
while (iterator.hasNext()) {
FileEntry entry = iterator.next();
// only process playlist files if they are new or have been modified since the last scan
if (entry.mLastModifiedChanged) {
processPlayList(entry, fileList);
}
}
} catch (RemoteException e1) {
} finally {
if (fileList != null) {
fileList.close();
}
}
}
private native void processDirectory(String path, MediaScannerClient client);
private native void processFile(String path, String mimeType, MediaScannerClient client);
public native void setLocale(String locale);
public native byte[] extractAlbumArt(FileDescriptor fd);
private static native final void native_init();
private native final void native_setup();
private native final void native_finalize();
/**
* Releases resources associated with this MediaScanner object.
* It is considered good practice to call this method when
* one is done using the MediaScanner object. After this method
* is called, the MediaScanner object can no longer be used.
*/
public void release() {
native_finalize();
}
@Override
protected void finalize() {
mContext.getContentResolver().releaseProvider(mMediaProvider);
native_finalize();
}
}
| apache-2.0 |
hudiehule/G-Storm | storm-core/src/jvm/org/apache/storm/security/auth/IHttpCredentialsPlugin.java | 1644 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.storm.security.auth;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
/**
* Interface for handling credentials in an HttpServletRequest
*/
public interface IHttpCredentialsPlugin {
/**
* Invoked once immediately after construction
* @param storm_conf Storm configuration
*/
void prepare(Map storm_conf);
/**
* Gets the user name from the request.
* @param req the servlet request
* @return the authenticated user, or null if none is authenticated.
*/
String getUserName(HttpServletRequest req);
/**
* Populates a given context with credentials information from an HTTP
* request.
* @param req the servlet request
* @return the context
*/
ReqContext populateContext(ReqContext context, HttpServletRequest req);
}
| apache-2.0 |
Ryman/rust | src/test/auxiliary/cci_class_cast.rs | 1527 | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub mod kitty {
use std::fmt;
pub struct cat {
meows : uint,
pub how_hungry : int,
pub name : ~str,
}
impl fmt::Show for cat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "{}", self.name)
}
}
impl cat {
fn meow(&mut self) {
println!("Meow");
self.meows += 1u;
if self.meows % 5u == 0u {
self.how_hungry += 1;
}
}
}
impl cat {
pub fn speak(&mut self) { self.meow(); }
pub fn eat(&mut self) -> bool {
if self.how_hungry > 0 {
println!("OM NOM NOM");
self.how_hungry -= 2;
return true;
}
else {
println!("Not hungry!");
return false;
}
}
}
pub fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
}
| apache-2.0 |
dbmanul/dbmanul | liquibase-integration-tests/src/test/java/liquibase/dbtest/oracle/OracleIntegrationTest.java | 4726 | package liquibase.dbtest.oracle;
import liquibase.Liquibase;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.dbtest.AbstractIntegrationTest;
import liquibase.exception.LiquibaseException;
import liquibase.exception.ValidationFailedException;
import org.junit.Test;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeNotNull;
/**
* Integration test for Oracle Database, Version 11gR2 and above.
*/
public class OracleIntegrationTest extends AbstractIntegrationTest {
String indexOnSchemaChangeLog;
String viewOnSchemaChangeLog;
public OracleIntegrationTest() throws Exception {
super("oracle", DatabaseFactory.getInstance().getDatabase("oracle"));
indexOnSchemaChangeLog = "changelogs/oracle/complete/indexOnSchema.xml";
viewOnSchemaChangeLog = "changelogs/oracle/complete/viewOnSchema.xml";
// Respect a user-defined location for sqlnet.ora, tnsnames.ora etc. stored in the environment
// variable TNS_ADMIN. This allowes the use of TNSNAMES.
if (System.getenv("TNS_ADMIN") != null)
System.setProperty("oracle.net.tns_admin",System.getenv("TNS_ADMIN"));
}
@Override
protected boolean isDatabaseProvidedByTravisCI() {
// Seems unlikely to ever be provided by Travis, as it's not free
return false;
}
@Override
@Test
public void testRunChangeLog() throws Exception {
super.testRunChangeLog(); //To change body of overridden methods use File | Settings | File Templates.
}
@Test
public void indexCreatedOnCorrectSchema() throws Exception {
assumeNotNull(this.getDatabase());
Liquibase liquibase = createLiquibase(this.indexOnSchemaChangeLog);
clearDatabase();
try {
liquibase.update(this.contexts);
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
throw e;
}
Statement queryIndex = ((JdbcConnection) this.getDatabase().getConnection()).getUnderlyingConnection().createStatement();
ResultSet indexOwner = queryIndex.executeQuery("SELECT owner FROM ALL_INDEXES WHERE index_name = 'IDX_BOOK_ID'");
assertTrue(indexOwner.next());
String owner = indexOwner.getString("owner");
assertEquals("LBCAT2", owner);
// check that the automatically rollback now works too
try {
liquibase.rollback( new Date(0),this.contexts);
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
throw e;
}
}
@Test
public void viewCreatedOnCorrectSchema() throws Exception {
assumeNotNull(this.getDatabase());
Liquibase liquibase = createLiquibase(this.viewOnSchemaChangeLog);
clearDatabase();
try {
liquibase.update(this.contexts);
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
throw e;
}
Statement queryIndex = ((JdbcConnection) this.getDatabase().getConnection()).getUnderlyingConnection().createStatement();
ResultSet indexOwner = queryIndex.executeQuery("SELECT owner FROM ALL_VIEWS WHERE view_name = 'V_BOOK2'");
assertTrue(indexOwner.next());
String owner = indexOwner.getString("owner");
assertEquals("LBCAT2", owner);
// check that the automatically rollback now works too
try {
liquibase.rollback( new Date(0),this.contexts);
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
throw e;
}
}
@Test
public void smartDataLoad() throws Exception {
assumeNotNull(this.getDatabase());
Liquibase liquibase = createLiquibase("changelogs/common/smartDataLoad.changelog.xml");
clearDatabase();
try {
liquibase.update(this.contexts);
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
throw e;
}
// check that the automatically rollback now works too
try {
liquibase.rollback( new Date(0),this.contexts);
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
throw e;
}
}
@Override
@Test
public void testDiffExternalForeignKeys() throws Exception {
//cross-schema security for oracle is a bother, ignoring test for now
}
} | apache-2.0 |
geeag/kafka | clients/src/main/java/org/apache/kafka/common/protocol/Errors.java | 14092 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.common.protocol;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.common.errors.ApiException;
import org.apache.kafka.common.errors.BrokerNotAvailableException;
import org.apache.kafka.common.errors.ClusterAuthorizationException;
import org.apache.kafka.common.errors.ControllerMovedException;
import org.apache.kafka.common.errors.CorruptRecordException;
import org.apache.kafka.common.errors.GroupAuthorizationException;
import org.apache.kafka.common.errors.GroupCoordinatorNotAvailableException;
import org.apache.kafka.common.errors.GroupLoadInProgressException;
import org.apache.kafka.common.errors.IllegalGenerationException;
import org.apache.kafka.common.errors.IllegalSaslStateException;
import org.apache.kafka.common.errors.InconsistentGroupProtocolException;
import org.apache.kafka.common.errors.InvalidCommitOffsetSizeException;
import org.apache.kafka.common.errors.InvalidConfigurationException;
import org.apache.kafka.common.errors.InvalidFetchSizeException;
import org.apache.kafka.common.errors.InvalidGroupIdException;
import org.apache.kafka.common.errors.InvalidPartitionsException;
import org.apache.kafka.common.errors.InvalidReplicaAssignmentException;
import org.apache.kafka.common.errors.InvalidReplicationFactorException;
import org.apache.kafka.common.errors.InvalidRequestException;
import org.apache.kafka.common.errors.InvalidRequiredAcksException;
import org.apache.kafka.common.errors.InvalidSessionTimeoutException;
import org.apache.kafka.common.errors.InvalidTimestampException;
import org.apache.kafka.common.errors.InvalidTopicException;
import org.apache.kafka.common.errors.LeaderNotAvailableException;
import org.apache.kafka.common.errors.UnsupportedForMessageFormatException;
import org.apache.kafka.common.errors.NetworkException;
import org.apache.kafka.common.errors.NotControllerException;
import org.apache.kafka.common.errors.NotCoordinatorForGroupException;
import org.apache.kafka.common.errors.NotEnoughReplicasAfterAppendException;
import org.apache.kafka.common.errors.NotEnoughReplicasException;
import org.apache.kafka.common.errors.NotLeaderForPartitionException;
import org.apache.kafka.common.errors.OffsetMetadataTooLarge;
import org.apache.kafka.common.errors.OffsetOutOfRangeException;
import org.apache.kafka.common.errors.RebalanceInProgressException;
import org.apache.kafka.common.errors.RecordBatchTooLargeException;
import org.apache.kafka.common.errors.RecordTooLargeException;
import org.apache.kafka.common.errors.ReplicaNotAvailableException;
import org.apache.kafka.common.errors.RetriableException;
import org.apache.kafka.common.errors.TopicExistsException;
import org.apache.kafka.common.errors.UnsupportedSaslMechanismException;
import org.apache.kafka.common.errors.TimeoutException;
import org.apache.kafka.common.errors.TopicAuthorizationException;
import org.apache.kafka.common.errors.UnsupportedVersionException;
import org.apache.kafka.common.errors.UnknownMemberIdException;
import org.apache.kafka.common.errors.UnknownServerException;
import org.apache.kafka.common.errors.UnknownTopicOrPartitionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class contains all the client-server errors--those errors that must be sent from the server to the client. These
* are thus part of the protocol. The names can be changed but the error code cannot.
*
* Do not add exceptions that occur only on the client or only on the server here.
*/
public enum Errors {
UNKNOWN(-1, new UnknownServerException("The server experienced an unexpected error when processing the request")),
NONE(0, null),
OFFSET_OUT_OF_RANGE(1,
new OffsetOutOfRangeException("The requested offset is not within the range of offsets maintained by the server.")),
CORRUPT_MESSAGE(2,
new CorruptRecordException("This message has failed its CRC checksum, exceeds the valid size, or is otherwise corrupt.")),
UNKNOWN_TOPIC_OR_PARTITION(3,
new UnknownTopicOrPartitionException("This server does not host this topic-partition.")),
INVALID_FETCH_SIZE(4,
new InvalidFetchSizeException("The requested fetch size is invalid.")),
LEADER_NOT_AVAILABLE(5,
new LeaderNotAvailableException("There is no leader for this topic-partition as we are in the middle of a leadership election.")),
NOT_LEADER_FOR_PARTITION(6,
new NotLeaderForPartitionException("This server is not the leader for that topic-partition.")),
REQUEST_TIMED_OUT(7,
new TimeoutException("The request timed out.")),
BROKER_NOT_AVAILABLE(8,
new BrokerNotAvailableException("The broker is not available.")),
REPLICA_NOT_AVAILABLE(9,
new ReplicaNotAvailableException("The replica is not available for the requested topic-partition")),
MESSAGE_TOO_LARGE(10,
new RecordTooLargeException("The request included a message larger than the max message size the server will accept.")),
STALE_CONTROLLER_EPOCH(11,
new ControllerMovedException("The controller moved to another broker.")),
OFFSET_METADATA_TOO_LARGE(12,
new OffsetMetadataTooLarge("The metadata field of the offset request was too large.")),
NETWORK_EXCEPTION(13,
new NetworkException("The server disconnected before a response was received.")),
GROUP_LOAD_IN_PROGRESS(14,
new GroupLoadInProgressException("The coordinator is loading and hence can't process requests for this group.")),
GROUP_COORDINATOR_NOT_AVAILABLE(15,
new GroupCoordinatorNotAvailableException("The group coordinator is not available.")),
NOT_COORDINATOR_FOR_GROUP(16,
new NotCoordinatorForGroupException("This is not the correct coordinator for this group.")),
INVALID_TOPIC_EXCEPTION(17,
new InvalidTopicException("The request attempted to perform an operation on an invalid topic.")),
RECORD_LIST_TOO_LARGE(18,
new RecordBatchTooLargeException("The request included message batch larger than the configured segment size on the server.")),
NOT_ENOUGH_REPLICAS(19,
new NotEnoughReplicasException("Messages are rejected since there are fewer in-sync replicas than required.")),
NOT_ENOUGH_REPLICAS_AFTER_APPEND(20,
new NotEnoughReplicasAfterAppendException("Messages are written to the log, but to fewer in-sync replicas than required.")),
INVALID_REQUIRED_ACKS(21,
new InvalidRequiredAcksException("Produce request specified an invalid value for required acks.")),
ILLEGAL_GENERATION(22,
new IllegalGenerationException("Specified group generation id is not valid.")),
INCONSISTENT_GROUP_PROTOCOL(23,
new InconsistentGroupProtocolException("The group member's supported protocols are incompatible with those of existing members.")),
INVALID_GROUP_ID(24,
new InvalidGroupIdException("The configured groupId is invalid")),
UNKNOWN_MEMBER_ID(25,
new UnknownMemberIdException("The coordinator is not aware of this member.")),
INVALID_SESSION_TIMEOUT(26,
new InvalidSessionTimeoutException("The session timeout is not within the range allowed by the broker " +
"(as configured by group.min.session.timeout.ms and group.max.session.timeout.ms).")),
REBALANCE_IN_PROGRESS(27,
new RebalanceInProgressException("The group is rebalancing, so a rejoin is needed.")),
INVALID_COMMIT_OFFSET_SIZE(28,
new InvalidCommitOffsetSizeException("The committing offset data size is not valid")),
TOPIC_AUTHORIZATION_FAILED(29,
new TopicAuthorizationException("Topic authorization failed.")),
GROUP_AUTHORIZATION_FAILED(30,
new GroupAuthorizationException("Group authorization failed.")),
CLUSTER_AUTHORIZATION_FAILED(31,
new ClusterAuthorizationException("Cluster authorization failed.")),
INVALID_TIMESTAMP(32,
new InvalidTimestampException("The timestamp of the message is out of acceptable range.")),
UNSUPPORTED_SASL_MECHANISM(33,
new UnsupportedSaslMechanismException("The broker does not support the requested SASL mechanism.")),
ILLEGAL_SASL_STATE(34,
new IllegalSaslStateException("Request is not valid given the current SASL state.")),
UNSUPPORTED_VERSION(35,
new UnsupportedVersionException("The version of API is not supported.")),
TOPIC_ALREADY_EXISTS(36,
new TopicExistsException("Topic with this name already exists.")),
INVALID_PARTITIONS(37,
new InvalidPartitionsException("Number of partitions is invalid.")),
INVALID_REPLICATION_FACTOR(38,
new InvalidReplicationFactorException("Replication-factor is invalid.")),
INVALID_REPLICA_ASSIGNMENT(39,
new InvalidReplicaAssignmentException("Replica assignment is invalid.")),
INVALID_CONFIG(40,
new InvalidConfigurationException("Configuration is invalid.")),
NOT_CONTROLLER(41,
new NotControllerException("This is not the correct controller for this cluster.")),
INVALID_REQUEST(42,
new InvalidRequestException("This most likely occurs because of a request being malformed by the client library or" +
" the message was sent to an incompatible broker. See the broker logs for more details.")),
UNSUPPORTED_FOR_MESSAGE_FORMAT(43,
new UnsupportedForMessageFormatException("The message format version on the broker does not support the request."));
private static final Logger log = LoggerFactory.getLogger(Errors.class);
private static Map<Class<?>, Errors> classToError = new HashMap<Class<?>, Errors>();
private static Map<Short, Errors> codeToError = new HashMap<Short, Errors>();
static {
for (Errors error : Errors.values()) {
codeToError.put(error.code(), error);
if (error.exception != null)
classToError.put(error.exception.getClass(), error);
}
}
private final short code;
private final ApiException exception;
private Errors(int code, ApiException exception) {
this.code = (short) code;
this.exception = exception;
}
/**
* An instance of the exception
*/
public ApiException exception() {
return this.exception;
}
/**
* Returns the class name of the exception or null if this is {@code Errors.NONE}.
*/
public String exceptionName() {
return exception == null ? null : exception.getClass().getName();
}
/**
* The error code for the exception
*/
public short code() {
return this.code;
}
/**
* Throw the exception corresponding to this error if there is one
*/
public void maybeThrow() {
if (exception != null) {
throw this.exception;
}
}
/**
* Get a friendly description of the error (if one is available).
* @return the error message
*/
public String message() {
if (exception != null)
return exception.getMessage();
return toString();
}
/**
* Throw the exception if there is one
*/
public static Errors forCode(short code) {
Errors error = codeToError.get(code);
if (error != null) {
return error;
} else {
log.warn("Unexpected error code: {}.", code);
return UNKNOWN;
}
}
/**
* Return the error instance associated with this exception or any of its superclasses (or UNKNOWN if there is none).
* If there are multiple matches in the class hierarchy, the first match starting from the bottom is used.
*/
public static Errors forException(Throwable t) {
Class<?> clazz = t.getClass();
while (clazz != null) {
Errors error = classToError.get(clazz);
if (error != null)
return error;
clazz = clazz.getSuperclass();
}
return UNKNOWN;
}
private static String toHtml() {
final StringBuilder b = new StringBuilder();
b.append("<table class=\"data-table\"><tbody>\n");
b.append("<tr>");
b.append("<th>Error</th>\n");
b.append("<th>Code</th>\n");
b.append("<th>Retriable</th>\n");
b.append("<th>Description</th>\n");
b.append("</tr>\n");
for (Errors error : Errors.values()) {
b.append("<tr>");
b.append("<td>");
b.append(error.name());
b.append("</td>");
b.append("<td>");
b.append(error.code());
b.append("</td>");
b.append("<td>");
b.append(error.exception() != null && error.exception() instanceof RetriableException ? "True" : "False");
b.append("</td>");
b.append("<td>");
b.append(error.exception() != null ? error.exception().getMessage() : "");
b.append("</td>");
b.append("</tr>\n");
}
b.append("</table>\n");
return b.toString();
}
public static void main(String[] args) {
System.out.println(toHtml());
}
}
| apache-2.0 |
rhcarvalho/origin | pkg/network/apis/network/v1/zz_generated.conversion.go | 15941 | // +build !ignore_autogenerated_openshift
// This file was autogenerated by conversion-gen. Do not edit it manually!
package v1
import (
network "github.com/openshift/origin/pkg/network/apis/network"
conversion "k8s.io/apimachinery/pkg/conversion"
runtime "k8s.io/apimachinery/pkg/runtime"
unsafe "unsafe"
)
func init() {
SchemeBuilder.Register(RegisterConversions)
}
// RegisterConversions adds conversion functions to the given scheme.
// Public to allow building arbitrary schemes.
func RegisterConversions(scheme *runtime.Scheme) error {
return scheme.AddGeneratedConversionFuncs(
Convert_v1_ClusterNetwork_To_network_ClusterNetwork,
Convert_network_ClusterNetwork_To_v1_ClusterNetwork,
Convert_v1_ClusterNetworkList_To_network_ClusterNetworkList,
Convert_network_ClusterNetworkList_To_v1_ClusterNetworkList,
Convert_v1_EgressNetworkPolicy_To_network_EgressNetworkPolicy,
Convert_network_EgressNetworkPolicy_To_v1_EgressNetworkPolicy,
Convert_v1_EgressNetworkPolicyList_To_network_EgressNetworkPolicyList,
Convert_network_EgressNetworkPolicyList_To_v1_EgressNetworkPolicyList,
Convert_v1_EgressNetworkPolicyPeer_To_network_EgressNetworkPolicyPeer,
Convert_network_EgressNetworkPolicyPeer_To_v1_EgressNetworkPolicyPeer,
Convert_v1_EgressNetworkPolicyRule_To_network_EgressNetworkPolicyRule,
Convert_network_EgressNetworkPolicyRule_To_v1_EgressNetworkPolicyRule,
Convert_v1_EgressNetworkPolicySpec_To_network_EgressNetworkPolicySpec,
Convert_network_EgressNetworkPolicySpec_To_v1_EgressNetworkPolicySpec,
Convert_v1_HostSubnet_To_network_HostSubnet,
Convert_network_HostSubnet_To_v1_HostSubnet,
Convert_v1_HostSubnetList_To_network_HostSubnetList,
Convert_network_HostSubnetList_To_v1_HostSubnetList,
Convert_v1_NetNamespace_To_network_NetNamespace,
Convert_network_NetNamespace_To_v1_NetNamespace,
Convert_v1_NetNamespaceList_To_network_NetNamespaceList,
Convert_network_NetNamespaceList_To_v1_NetNamespaceList,
)
}
func autoConvert_v1_ClusterNetwork_To_network_ClusterNetwork(in *ClusterNetwork, out *network.ClusterNetwork, s conversion.Scope) error {
out.ObjectMeta = in.ObjectMeta
out.Network = in.Network
out.HostSubnetLength = in.HostSubnetLength
out.ServiceNetwork = in.ServiceNetwork
out.PluginName = in.PluginName
return nil
}
// Convert_v1_ClusterNetwork_To_network_ClusterNetwork is an autogenerated conversion function.
func Convert_v1_ClusterNetwork_To_network_ClusterNetwork(in *ClusterNetwork, out *network.ClusterNetwork, s conversion.Scope) error {
return autoConvert_v1_ClusterNetwork_To_network_ClusterNetwork(in, out, s)
}
func autoConvert_network_ClusterNetwork_To_v1_ClusterNetwork(in *network.ClusterNetwork, out *ClusterNetwork, s conversion.Scope) error {
out.ObjectMeta = in.ObjectMeta
out.Network = in.Network
out.HostSubnetLength = in.HostSubnetLength
out.ServiceNetwork = in.ServiceNetwork
out.PluginName = in.PluginName
return nil
}
// Convert_network_ClusterNetwork_To_v1_ClusterNetwork is an autogenerated conversion function.
func Convert_network_ClusterNetwork_To_v1_ClusterNetwork(in *network.ClusterNetwork, out *ClusterNetwork, s conversion.Scope) error {
return autoConvert_network_ClusterNetwork_To_v1_ClusterNetwork(in, out, s)
}
func autoConvert_v1_ClusterNetworkList_To_network_ClusterNetworkList(in *ClusterNetworkList, out *network.ClusterNetworkList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
out.Items = *(*[]network.ClusterNetwork)(unsafe.Pointer(&in.Items))
return nil
}
// Convert_v1_ClusterNetworkList_To_network_ClusterNetworkList is an autogenerated conversion function.
func Convert_v1_ClusterNetworkList_To_network_ClusterNetworkList(in *ClusterNetworkList, out *network.ClusterNetworkList, s conversion.Scope) error {
return autoConvert_v1_ClusterNetworkList_To_network_ClusterNetworkList(in, out, s)
}
func autoConvert_network_ClusterNetworkList_To_v1_ClusterNetworkList(in *network.ClusterNetworkList, out *ClusterNetworkList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
if in.Items == nil {
out.Items = make([]ClusterNetwork, 0)
} else {
out.Items = *(*[]ClusterNetwork)(unsafe.Pointer(&in.Items))
}
return nil
}
// Convert_network_ClusterNetworkList_To_v1_ClusterNetworkList is an autogenerated conversion function.
func Convert_network_ClusterNetworkList_To_v1_ClusterNetworkList(in *network.ClusterNetworkList, out *ClusterNetworkList, s conversion.Scope) error {
return autoConvert_network_ClusterNetworkList_To_v1_ClusterNetworkList(in, out, s)
}
func autoConvert_v1_EgressNetworkPolicy_To_network_EgressNetworkPolicy(in *EgressNetworkPolicy, out *network.EgressNetworkPolicy, s conversion.Scope) error {
out.ObjectMeta = in.ObjectMeta
if err := Convert_v1_EgressNetworkPolicySpec_To_network_EgressNetworkPolicySpec(&in.Spec, &out.Spec, s); err != nil {
return err
}
return nil
}
// Convert_v1_EgressNetworkPolicy_To_network_EgressNetworkPolicy is an autogenerated conversion function.
func Convert_v1_EgressNetworkPolicy_To_network_EgressNetworkPolicy(in *EgressNetworkPolicy, out *network.EgressNetworkPolicy, s conversion.Scope) error {
return autoConvert_v1_EgressNetworkPolicy_To_network_EgressNetworkPolicy(in, out, s)
}
func autoConvert_network_EgressNetworkPolicy_To_v1_EgressNetworkPolicy(in *network.EgressNetworkPolicy, out *EgressNetworkPolicy, s conversion.Scope) error {
out.ObjectMeta = in.ObjectMeta
if err := Convert_network_EgressNetworkPolicySpec_To_v1_EgressNetworkPolicySpec(&in.Spec, &out.Spec, s); err != nil {
return err
}
return nil
}
// Convert_network_EgressNetworkPolicy_To_v1_EgressNetworkPolicy is an autogenerated conversion function.
func Convert_network_EgressNetworkPolicy_To_v1_EgressNetworkPolicy(in *network.EgressNetworkPolicy, out *EgressNetworkPolicy, s conversion.Scope) error {
return autoConvert_network_EgressNetworkPolicy_To_v1_EgressNetworkPolicy(in, out, s)
}
func autoConvert_v1_EgressNetworkPolicyList_To_network_EgressNetworkPolicyList(in *EgressNetworkPolicyList, out *network.EgressNetworkPolicyList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
out.Items = *(*[]network.EgressNetworkPolicy)(unsafe.Pointer(&in.Items))
return nil
}
// Convert_v1_EgressNetworkPolicyList_To_network_EgressNetworkPolicyList is an autogenerated conversion function.
func Convert_v1_EgressNetworkPolicyList_To_network_EgressNetworkPolicyList(in *EgressNetworkPolicyList, out *network.EgressNetworkPolicyList, s conversion.Scope) error {
return autoConvert_v1_EgressNetworkPolicyList_To_network_EgressNetworkPolicyList(in, out, s)
}
func autoConvert_network_EgressNetworkPolicyList_To_v1_EgressNetworkPolicyList(in *network.EgressNetworkPolicyList, out *EgressNetworkPolicyList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
if in.Items == nil {
out.Items = make([]EgressNetworkPolicy, 0)
} else {
out.Items = *(*[]EgressNetworkPolicy)(unsafe.Pointer(&in.Items))
}
return nil
}
// Convert_network_EgressNetworkPolicyList_To_v1_EgressNetworkPolicyList is an autogenerated conversion function.
func Convert_network_EgressNetworkPolicyList_To_v1_EgressNetworkPolicyList(in *network.EgressNetworkPolicyList, out *EgressNetworkPolicyList, s conversion.Scope) error {
return autoConvert_network_EgressNetworkPolicyList_To_v1_EgressNetworkPolicyList(in, out, s)
}
func autoConvert_v1_EgressNetworkPolicyPeer_To_network_EgressNetworkPolicyPeer(in *EgressNetworkPolicyPeer, out *network.EgressNetworkPolicyPeer, s conversion.Scope) error {
out.CIDRSelector = in.CIDRSelector
out.DNSName = in.DNSName
return nil
}
// Convert_v1_EgressNetworkPolicyPeer_To_network_EgressNetworkPolicyPeer is an autogenerated conversion function.
func Convert_v1_EgressNetworkPolicyPeer_To_network_EgressNetworkPolicyPeer(in *EgressNetworkPolicyPeer, out *network.EgressNetworkPolicyPeer, s conversion.Scope) error {
return autoConvert_v1_EgressNetworkPolicyPeer_To_network_EgressNetworkPolicyPeer(in, out, s)
}
func autoConvert_network_EgressNetworkPolicyPeer_To_v1_EgressNetworkPolicyPeer(in *network.EgressNetworkPolicyPeer, out *EgressNetworkPolicyPeer, s conversion.Scope) error {
out.CIDRSelector = in.CIDRSelector
out.DNSName = in.DNSName
return nil
}
// Convert_network_EgressNetworkPolicyPeer_To_v1_EgressNetworkPolicyPeer is an autogenerated conversion function.
func Convert_network_EgressNetworkPolicyPeer_To_v1_EgressNetworkPolicyPeer(in *network.EgressNetworkPolicyPeer, out *EgressNetworkPolicyPeer, s conversion.Scope) error {
return autoConvert_network_EgressNetworkPolicyPeer_To_v1_EgressNetworkPolicyPeer(in, out, s)
}
func autoConvert_v1_EgressNetworkPolicyRule_To_network_EgressNetworkPolicyRule(in *EgressNetworkPolicyRule, out *network.EgressNetworkPolicyRule, s conversion.Scope) error {
out.Type = network.EgressNetworkPolicyRuleType(in.Type)
if err := Convert_v1_EgressNetworkPolicyPeer_To_network_EgressNetworkPolicyPeer(&in.To, &out.To, s); err != nil {
return err
}
return nil
}
// Convert_v1_EgressNetworkPolicyRule_To_network_EgressNetworkPolicyRule is an autogenerated conversion function.
func Convert_v1_EgressNetworkPolicyRule_To_network_EgressNetworkPolicyRule(in *EgressNetworkPolicyRule, out *network.EgressNetworkPolicyRule, s conversion.Scope) error {
return autoConvert_v1_EgressNetworkPolicyRule_To_network_EgressNetworkPolicyRule(in, out, s)
}
func autoConvert_network_EgressNetworkPolicyRule_To_v1_EgressNetworkPolicyRule(in *network.EgressNetworkPolicyRule, out *EgressNetworkPolicyRule, s conversion.Scope) error {
out.Type = EgressNetworkPolicyRuleType(in.Type)
if err := Convert_network_EgressNetworkPolicyPeer_To_v1_EgressNetworkPolicyPeer(&in.To, &out.To, s); err != nil {
return err
}
return nil
}
// Convert_network_EgressNetworkPolicyRule_To_v1_EgressNetworkPolicyRule is an autogenerated conversion function.
func Convert_network_EgressNetworkPolicyRule_To_v1_EgressNetworkPolicyRule(in *network.EgressNetworkPolicyRule, out *EgressNetworkPolicyRule, s conversion.Scope) error {
return autoConvert_network_EgressNetworkPolicyRule_To_v1_EgressNetworkPolicyRule(in, out, s)
}
func autoConvert_v1_EgressNetworkPolicySpec_To_network_EgressNetworkPolicySpec(in *EgressNetworkPolicySpec, out *network.EgressNetworkPolicySpec, s conversion.Scope) error {
out.Egress = *(*[]network.EgressNetworkPolicyRule)(unsafe.Pointer(&in.Egress))
return nil
}
// Convert_v1_EgressNetworkPolicySpec_To_network_EgressNetworkPolicySpec is an autogenerated conversion function.
func Convert_v1_EgressNetworkPolicySpec_To_network_EgressNetworkPolicySpec(in *EgressNetworkPolicySpec, out *network.EgressNetworkPolicySpec, s conversion.Scope) error {
return autoConvert_v1_EgressNetworkPolicySpec_To_network_EgressNetworkPolicySpec(in, out, s)
}
func autoConvert_network_EgressNetworkPolicySpec_To_v1_EgressNetworkPolicySpec(in *network.EgressNetworkPolicySpec, out *EgressNetworkPolicySpec, s conversion.Scope) error {
if in.Egress == nil {
out.Egress = make([]EgressNetworkPolicyRule, 0)
} else {
out.Egress = *(*[]EgressNetworkPolicyRule)(unsafe.Pointer(&in.Egress))
}
return nil
}
// Convert_network_EgressNetworkPolicySpec_To_v1_EgressNetworkPolicySpec is an autogenerated conversion function.
func Convert_network_EgressNetworkPolicySpec_To_v1_EgressNetworkPolicySpec(in *network.EgressNetworkPolicySpec, out *EgressNetworkPolicySpec, s conversion.Scope) error {
return autoConvert_network_EgressNetworkPolicySpec_To_v1_EgressNetworkPolicySpec(in, out, s)
}
func autoConvert_v1_HostSubnet_To_network_HostSubnet(in *HostSubnet, out *network.HostSubnet, s conversion.Scope) error {
out.ObjectMeta = in.ObjectMeta
out.Host = in.Host
out.HostIP = in.HostIP
out.Subnet = in.Subnet
return nil
}
// Convert_v1_HostSubnet_To_network_HostSubnet is an autogenerated conversion function.
func Convert_v1_HostSubnet_To_network_HostSubnet(in *HostSubnet, out *network.HostSubnet, s conversion.Scope) error {
return autoConvert_v1_HostSubnet_To_network_HostSubnet(in, out, s)
}
func autoConvert_network_HostSubnet_To_v1_HostSubnet(in *network.HostSubnet, out *HostSubnet, s conversion.Scope) error {
out.ObjectMeta = in.ObjectMeta
out.Host = in.Host
out.HostIP = in.HostIP
out.Subnet = in.Subnet
return nil
}
// Convert_network_HostSubnet_To_v1_HostSubnet is an autogenerated conversion function.
func Convert_network_HostSubnet_To_v1_HostSubnet(in *network.HostSubnet, out *HostSubnet, s conversion.Scope) error {
return autoConvert_network_HostSubnet_To_v1_HostSubnet(in, out, s)
}
func autoConvert_v1_HostSubnetList_To_network_HostSubnetList(in *HostSubnetList, out *network.HostSubnetList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
out.Items = *(*[]network.HostSubnet)(unsafe.Pointer(&in.Items))
return nil
}
// Convert_v1_HostSubnetList_To_network_HostSubnetList is an autogenerated conversion function.
func Convert_v1_HostSubnetList_To_network_HostSubnetList(in *HostSubnetList, out *network.HostSubnetList, s conversion.Scope) error {
return autoConvert_v1_HostSubnetList_To_network_HostSubnetList(in, out, s)
}
func autoConvert_network_HostSubnetList_To_v1_HostSubnetList(in *network.HostSubnetList, out *HostSubnetList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
if in.Items == nil {
out.Items = make([]HostSubnet, 0)
} else {
out.Items = *(*[]HostSubnet)(unsafe.Pointer(&in.Items))
}
return nil
}
// Convert_network_HostSubnetList_To_v1_HostSubnetList is an autogenerated conversion function.
func Convert_network_HostSubnetList_To_v1_HostSubnetList(in *network.HostSubnetList, out *HostSubnetList, s conversion.Scope) error {
return autoConvert_network_HostSubnetList_To_v1_HostSubnetList(in, out, s)
}
func autoConvert_v1_NetNamespace_To_network_NetNamespace(in *NetNamespace, out *network.NetNamespace, s conversion.Scope) error {
out.ObjectMeta = in.ObjectMeta
out.NetName = in.NetName
out.NetID = in.NetID
return nil
}
// Convert_v1_NetNamespace_To_network_NetNamespace is an autogenerated conversion function.
func Convert_v1_NetNamespace_To_network_NetNamespace(in *NetNamespace, out *network.NetNamespace, s conversion.Scope) error {
return autoConvert_v1_NetNamespace_To_network_NetNamespace(in, out, s)
}
func autoConvert_network_NetNamespace_To_v1_NetNamespace(in *network.NetNamespace, out *NetNamespace, s conversion.Scope) error {
out.ObjectMeta = in.ObjectMeta
out.NetName = in.NetName
out.NetID = in.NetID
return nil
}
// Convert_network_NetNamespace_To_v1_NetNamespace is an autogenerated conversion function.
func Convert_network_NetNamespace_To_v1_NetNamespace(in *network.NetNamespace, out *NetNamespace, s conversion.Scope) error {
return autoConvert_network_NetNamespace_To_v1_NetNamespace(in, out, s)
}
func autoConvert_v1_NetNamespaceList_To_network_NetNamespaceList(in *NetNamespaceList, out *network.NetNamespaceList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
out.Items = *(*[]network.NetNamespace)(unsafe.Pointer(&in.Items))
return nil
}
// Convert_v1_NetNamespaceList_To_network_NetNamespaceList is an autogenerated conversion function.
func Convert_v1_NetNamespaceList_To_network_NetNamespaceList(in *NetNamespaceList, out *network.NetNamespaceList, s conversion.Scope) error {
return autoConvert_v1_NetNamespaceList_To_network_NetNamespaceList(in, out, s)
}
func autoConvert_network_NetNamespaceList_To_v1_NetNamespaceList(in *network.NetNamespaceList, out *NetNamespaceList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
if in.Items == nil {
out.Items = make([]NetNamespace, 0)
} else {
out.Items = *(*[]NetNamespace)(unsafe.Pointer(&in.Items))
}
return nil
}
// Convert_network_NetNamespaceList_To_v1_NetNamespaceList is an autogenerated conversion function.
func Convert_network_NetNamespaceList_To_v1_NetNamespaceList(in *network.NetNamespaceList, out *NetNamespaceList, s conversion.Scope) error {
return autoConvert_network_NetNamespaceList_To_v1_NetNamespaceList(in, out, s)
}
| apache-2.0 |
stackroute/samarthyaPlatform | webclient/candidate/e2e/app.e2e-spec.ts | 355 | import { SamarthyaPlacementPage } from './app.po';
describe('samarthya-placement App', function() {
let page: SamarthyaPlacementPage;
beforeEach(() => {
page = new SamarthyaPlacementPage();
});
it('should display message saying app works', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('app works!');
});
});
| apache-2.0 |
bshaffer/google-api-php-client-services | src/Google/Service/ServiceDirectory/Binding.php | 1443 | <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_ServiceDirectory_Binding extends Google_Collection
{
protected $collection_key = 'members';
protected $conditionType = 'Google_Service_ServiceDirectory_Expr';
protected $conditionDataType = '';
public $members;
public $role;
/**
* @param Google_Service_ServiceDirectory_Expr
*/
public function setCondition(Google_Service_ServiceDirectory_Expr $condition)
{
$this->condition = $condition;
}
/**
* @return Google_Service_ServiceDirectory_Expr
*/
public function getCondition()
{
return $this->condition;
}
public function setMembers($members)
{
$this->members = $members;
}
public function getMembers()
{
return $this->members;
}
public function setRole($role)
{
$this->role = $role;
}
public function getRole()
{
return $this->role;
}
}
| apache-2.0 |
oza/supersonic | supersonic/utils/atomic/locking.cc | 267 | // Copyright 2010 Google Inc. All Rights Reserved.
#include "supersonic/utils/macros.h"
#include "supersonic/utils/mutex.h"
namespace concurrent {
namespace detail {
Mutex seq_cst_mutex(base::LINKER_INITIALIZED);
} // namespace detail
} // namespace concurrent
| apache-2.0 |
gigakiller/zebra | src/ui.tree.js | 61022 | (function(pkg, Class, ui) {
/**
* Tree UI components and all related to the component classes and interfaces.
* Tree components are graphical representation of a tree model that allows a user
* to navigate over the model item, customize the items rendering and
* organize customizable editing of the items.
// create tree component instance to visualize the given tree model
var tree = new zebra.ui.tree.Tree({
value: "Root",
kids : [
"Item 1",
"Item 2",
"Item 3"
]
});
// make all tree items editable with text field component
tree.setEditorProvider(new zebra.ui.tree.DefEditors());
* One more tree component implementation - "CompTree" - allows developers
* to create tree whose nodes are other UI components
// create tree component instance to visualize the given tree model
var tree = new zebra.ui.tree.CompTree({
value: new zebra.ui.Label("Root label item"),
kids : [
new zebra.ui.Checkbox("Checkbox Item"),
new zebra.ui.Button("Button Item"),
new zebra.ui.TextField("Text field item")
]
});
* @module ui.tree
* @main
*/
// tree node metrics:
// |
// |-- <-gapx-> {icon} -- <-gapx-> {view}
//
//
var KE = ui.KeyEvent;
/**
* Simple private structure to keep a tree model item metrical characteristics
* @constructor
* @param {Boolean} b a state of an appropriate tree component node of the given
* tree model item. The state is sensible for item that has children items and
* the state indicates if the given tree node is collapsed (false) or expanded
* (true)
* @private
* @class zebra.ui.tree.$IM
*/
pkg.$IM = function(b) {
/**
* The whole width of tree node that includes a rendered item preferred
* width, all icons and gaps widths
* @attribute width
* @type {Integer}
* @readOnly
*/
/**
* The whole height of tree node that includes a rendered item preferred
* height, all icons and gaps heights
* @attribute height
* @type {Integer}
* @readOnly
*/
/**
* Width of an area of rendered tree model item. It excludes icons, toggle
* and gaps widths
* @attribute viewWidth
* @type {Integer}
* @readOnly
*/
/**
* Height of an area of rendered tree model item. It excludes icons, toggle
* and gaps heights
* @attribute viewHeight
* @type {Integer}
* @readOnly
*/
/**
* Indicates whether a node is in expanded or collapsed state
* @attribute isOpen
* @type {Boolean}
* @readOnly
*/
this.width = this.height = this.x = this.y = this.viewHeight = 0;
this.viewWidth = -1;
this.isOpen = b;
};
pkg.TreeListeners = zebra.util.ListenersClass("toggled", "selected");
/**
* Abstract tree component that can used as basement for building own tree components.
* The component is responsible for rendering tree, calculating tree nodes metrics,
* computing visible area, organizing basic user interaction. Classes that inherit it
* has to provide the following important things:
* **A tree model item metric** Developers have to implement "getItemPreferredSize(item)"
method to say which size the given tree item wants to have.
* **Tree node item rendering** If necessary developers have to implement the way
a tree item has to be visualized by implementing "this.paintItem(...)" method
*
* @class zebra.ui.tree.BaseTree
* @constructor
* @param {zebra.data.TreeModel|Object} a tree model. It can be an instance of tree model
* class or an object that described tree model. An example of such object is shown below:
{
value : "Root",
kids : [
{
value: "Child 1",
kids :[
"Sub child 1"
]
},
"Child 2",
"Child 3"
]
}
* @param {Boolean} [nodeState] a default tree nodes state (expanded or collapsed)
* @extends {zebra.ui.Panel}
*/
/**
* Fired when a tree item has been toggled
tree.bind(function toggled(src, item) {
...
});
* @event toggled
* @param {zebra.ui.tree.BaseTree} src an tree component that triggers the event
* @param {zebra.data.Item} item an tree item that has been toggled
*/
/**
* Fired when a tree item has been selected
tree.bind(function selected(src, item) {
...
});
* @event selected
* @param {zebra.ui.tree.BaseTree} src an tree component that triggers the event
* @param {zebra.data.Item} item an tree item that has been toggled
*/
pkg.BaseTree = Class(ui.Panel, [
function $prototype() {
/**
* Horizontal gap between a node elements: toggle, icons and tree item view
* @attribute gapx
* @readOnly
* @default 2
* @type {Integer}
*/
/**
* Vertical gap between a node elements: toggle, icons and tree item view
* @attribute gapy
* @readOnly
* @default 2
* @type {Integer}
*/
this.gapx = this.gapy = 2;
this.canHaveFocus = true;
/**
* Test if the given tree component item is opened
* @param {zebra.data.Item} i a tree model item
* @return {Boolean} true if the given tree component item is opened
* @method isOpen
*/
this.isOpen = function(i){
this.validate();
return this.isOpen_(i);
};
/**
* Get calculated for the given tree model item metrics
* @param {zebra.data.Item} i a tree item
* @return {Object} an tree model item metrics. Th
* @method getItemMetrics
*/
this.getItemMetrics = function(i){
this.validate();
return this.getIM(i);
};
this.togglePressed = function(root) {
this.toggle(root);
};
this.itemPressed = function(root, e) {
this.select(root);
};
this.mousePressed = function(e){
if (this.firstVisible != null && e.isActionMask()) {
var x = e.x,
y = e.y,
root = this.getItemAt(this.firstVisible, x, y);
if (root != null) {
x -= this.scrollManager.getSX();
y -= this.scrollManager.getSY();
var r = this.getToggleBounds(root);
if (x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height){
this.togglePressed(root);
}
else {
if (x > r.x + r.width) this.itemPressed(root, e);
}
}
}
};
this.vVisibility = function (){
if (this.model == null) this.firstVisible = null;
else {
var nva = ui.$cvp(this, {});
if (nva == null) this.firstVisible = null;
else {
if (this._isVal === false ||
(this.visibleArea == null ||
this.visibleArea.x != nva.x ||
this.visibleArea.y != nva.y ||
this.visibleArea.width != nva.width ||
this.visibleArea.height != nva.height ))
{
this.visibleArea = nva;
if (this.firstVisible != null) {
this.firstVisible = this.findOpened(this.firstVisible);
this.firstVisible = this.isOverVisibleArea(this.firstVisible) ? this.nextVisible(this.firstVisible)
: this.prevVisible(this.firstVisible);
}
else {
this.firstVisible = (-this.scrollManager.getSY() > ~~(this.maxh / 2)) ? this.prevVisible(this.findLast(this.model.root))
: this.nextVisible(this.model.root);
}
}
}
}
this._isVal = true;
};
this.recalc = function(){
this.maxh = this.maxw = 0;
if (this.model != null && this.model.root != null) {
this.recalc_(this.getLeft(), this.getTop(), null, this.model.root, true);
this.maxw -= this.getLeft();
this.maxh -= this.gapy;
}
};
/**
* Get tree model item metrical bounds (location and size).
* @param {zebra.data.Item} root an tree model item
* @return {Object} a structure that keeps an item view location
* and size:
{
x: {Integer},
y: {Integer},
width: {Integer},
height: {Integer}
}
* @method getItemBounds
* @protected
*/
this.getItemBounds = function(root){
var metrics = this.getIM(root),
toggle = this.getToggleBounds(root),
image = this.getIconBounds(root);
toggle.x = image.x + image.width + (image.width > 0 || toggle.width > 0 ? this.gapx : 0);
toggle.y = metrics.y + ~~((metrics.height - metrics.viewHeight) / 2);
toggle.width = metrics.viewWidth;
toggle.height = metrics.viewHeight;
return toggle;
};
/**
* Get toggle element bounds for the given tree model item.
* @param {zebra.data.Item} root an tree model item
* @return {Object} a structure that keeps an item toggle location
* and size:
{
x: {Integer},
y: {Integer},
width: {Integer},
height: {Integer}
}
* @method getToggleBounds
* @protected
*/
this.getToggleBounds = function(root){
var node = this.getIM(root), d = this.getToggleSize(root);
return { x:node.x, y:node.y + ~~((node.height - d.height) / 2), width:d.width, height:d.height };
};
/**
* Get current toggle element view. The view depends on the state of tree item.
* @param {zebra.data.Item} i a tree model item
* @protected
* @return {zebra.ui.View} a toggle element view
* @method getToogleView
*/
this.getToggleView = function(i){
return i.kids.length > 0 ? (this.getIM(i).isOpen ? this.views.on
: this.views.off) : null;
};
/**
* An abstract method that a concrete tree component implementations have to
* override. The method has to return a preferred size the given tree model
* item wants to have.
* @param {zebra.data.Item} root an tree model item
* @return {Object} a structure that keeps an item preferred size:
{
width: {Integer},
height: {Integer}
}
* @method getItemPreferredSize
* @protected
*/
this.getItemPreferredSize = function(root) {
throw new Error("Not implemented");
};
/**
* An abstract method that a concrete tree component implementations should
* override. The method has to render the given tree node of the specified
* tree model item at the given location
* @param {2DContext} g a graphical context
* @param {zebra.data.Item} root a tree model item to be rendered
* @param {zebra.ui.tree.$IM} node a tree node metrics
* @param {Ineteger} x a x location where the tree node has to be rendered
* @param {Ineteger} y a y location where the tree node has to be rendered
* @method paintItem
* @protected
*/
this.recalc_ = function (x,y,parent,root,isVis){
var node = this.getIM(root);
if (isVis === true) {
if (node.viewWidth < 0){
var viewSize = this.getItemPreferredSize(root);
node.viewWidth = viewSize.width === 0 ? 5 : viewSize.width;
node.viewHeight = viewSize.height;
}
var imageSize = this.getIconSize(root), toggleSize = this.getToggleSize(root);
if (parent != null){
var pImg = this.getIconBounds(parent);
x = pImg.x + ~~((pImg.width - toggleSize.width) / 2);
}
node.x = x;
node.y = y;
node.width = toggleSize.width + imageSize.width +
node.viewWidth + (toggleSize.width > 0 ? this.gapx : 0) + 10 +
(imageSize.width > 0 ? this.gapx : 0);
node.height = Math.max(((toggleSize.height > imageSize.height) ? toggleSize.height
: imageSize.height),
node.viewHeight);
if (node.x + node.width > this.maxw) {
this.maxw = node.x + node.width;
}
this.maxh += (node.height + this.gapy);
x = node.x + toggleSize.width + (toggleSize.width > 0 ? this.gapx : 0);
y += (node.height + this.gapy);
}
var b = node.isOpen && isVis === true;
if (b) {
var count = root.kids.length;
for(var i = 0; i < count; i++) {
y = this.recalc_(x, y, root, root.kids[i], b);
}
}
return y;
};
this.isOpen_ = function (i){
return i == null || (i.kids.length > 0 && this.getIM(i).isOpen && this.isOpen_(i.parent));
};
/**
* Get a tree node metrics by the given tree model item.
* @param {zebra.data.Item} i a tree model item
* @return {zebra.ui.tree.$IM} a tree node metrics
* @protected
* @method getIM
*/
this.getIM = function (i){
var node = this.nodes[i];
if (typeof node === 'undefined'){
node = new pkg.$IM(this.isOpenVal);
this.nodes[i] = node;
}
return node;
};
/**
* Get a tree item that is located at the given location.
* @param {zebra.data.Item} [root] a starting tree node
* @param {Integer} x a x coordinate
* @param {Integer} y a y coordinate
* @return {zebra.data.Item} a tree model item
* @method getItemAt
*/
this.getItemAt = function(root, x, y){
this.validate();
if (arguments.length < 3) {
x = arguments[0];
y = arguments[1];
root = this.model.root;
}
if (this.firstVisible != null && y >= this.visibleArea.y && y < this.visibleArea.y + this.visibleArea.height){
var dx = this.scrollManager.getSX(),
dy = this.scrollManager.getSY(),
found = this.getItemAtInBranch(root, x - dx, y - dy);
if (found != null) return found;
var parent = root.parent;
while (parent != null) {
var count = parent.kids.length;
for(var i = parent.kids.indexOf(root) + 1;i < count; i ++ ){
found = this.getItemAtInBranch(parent.kids[i], x - dx, y - dy);
if (found != null) return found;
}
root = parent;
parent = root.parent;
}
}
return null;
};
this.getItemAtInBranch = function(root,x,y){
if (root != null){
var node = this.getIM(root);
if (x >= node.x && y >= node.y && x < node.x + node.width && y < node.y + node.height + this.gapy) {
return root;
}
if (this.isOpen_(root)){
for(var i = 0;i < root.kids.length; i++) {
var res = this.getItemAtInBranch(root.kids[i], x, y);
if (res != null) return res;
}
}
}
return null;
};
this.getIconView = function (i){
return i.kids.length > 0 ? (this.getIM(i).isOpen ? this.views.open
: this.views.close)
: this.views.leaf;
};
this.getIconSize = function (i) {
var v = i.kids.length > 0 ? (this.getIM(i).isOpen ? this.viewSizes.open
: this.viewSizes.close)
: this.viewSizes.leaf;
return v ? v : { width:0, height:0 };
};
/**
* Get icon element bounds for the given tree model item.
* @param {zebra.data.Item} root an tree model item
* @return {Object} a structure that keeps an item icon location
* and size:
{
x: {Integer},
y: {Integer},
width: {Integer},
height: {Integer}
}
* @method getToggleBounds
* @protected
*/
this.getIconBounds = function (root){
var node = this.getIM(root),
id = this.getIconSize(root),
td = this.getToggleSize(root);
return { x:node.x + td.width + (td.width > 0 ? this.gapx : 0),
y:node.y + ~~((node.height - id.height) / 2),
width:id.width, height:id.height };
};
this.getToggleSize = function (i){
return this.isOpen_(i) ? this.viewSizes.on : this.viewSizes.off;
};
this.isOverVisibleArea = function (i){
var node = this.getIM(i);
return node.y + node.height + this.scrollManager.getSY() < this.visibleArea.y;
};
this.findOpened = function (item){
var parent = item.parent;
return (parent == null || this.isOpen_(parent)) ? item : this.findOpened(parent);
};
this.findNext = function (item){
if (item != null){
if (item.kids.length > 0 && this.isOpen_(item)){
return item.kids[0];
}
var parent = null;
while ((parent = item.parent) != null){
var index = parent.kids.indexOf(item);
if (index + 1 < parent.kids.length) return parent.kids[index + 1];
item = parent;
}
}
return null;
};
this.findPrev = function (item){
if (item != null) {
var parent = item.parent;
if (parent != null) {
var index = parent.kids.indexOf(item);
return (index - 1 >= 0) ? this.findLast(parent.kids[index - 1]) : parent;
}
}
return null;
};
this.findLast = function (item){
return this.isOpen_(item) && item.kids.length > 0 ? this.findLast(item.kids[item.kids.length - 1])
: item;
};
this.prevVisible = function (item){
if (item == null || this.isOverVisibleArea(item)) return this.nextVisible(item);
var parent = null;
while((parent = item.parent) != null){
for(var i = parent.kids.indexOf(item) - 1;i >= 0; i-- ){
var child = parent.kids[i];
if (this.isOverVisibleArea(child)) return this.nextVisible(child);
}
item = parent;
}
return item;
};
this.isVerVisible = function (item){
if (this.visibleArea == null) return false;
var node = this.getIM(item),
yy1 = node.y + this.scrollManager.getSY(),
yy2 = yy1 + node.height - 1,
by = this.visibleArea.y + this.visibleArea.height;
return ((this.visibleArea.y <= yy1 && yy1 < by) ||
(this.visibleArea.y <= yy2 && yy2 < by) ||
(this.visibleArea.y > yy1 && yy2 >= by) );
};
this.nextVisible = function(item){
if (item == null || this.isVerVisible(item)) return item;
var res = this.nextVisibleInBranch(item), parent = null;
if (res != null) return res;
while((parent = item.parent) != null){
var count = parent.kids.length;
for(var i = parent.kids.indexOf(item) + 1;i < count; i++){
res = this.nextVisibleInBranch(parent.kids[i]);
if (res != null) return res;
}
item = parent;
}
return null;
};
this.nextVisibleInBranch = function (item){
if (this.isVerVisible(item)) return item;
if (this.isOpen_(item)){
for(var i = 0;i < item.kids.length; i++){
var res = this.nextVisibleInBranch(item.kids[i]);
if (res != null) return res;
}
}
return null;
};
this.paintSelectedItem = function(g, root, node, x, y) {
var v = this.hasFocus() ? this.views.aselect : this.views.iselect;
if (v != null) {
v.paint(g, x, y, node.viewWidth, node.viewHeight, this);
}
};
this.paintTree = function (g,item){
this.paintBranch(g, item);
var parent = null;
while((parent = item.parent) != null){
this.paintChild(g, parent, parent.kids.indexOf(item) + 1);
item = parent;
}
};
this.paintBranch = function (g, root){
if (root == null) return false;
var node = this.getIM(root),
dx = this.scrollManager.getSX(),
dy = this.scrollManager.getSY();
if (zebra.util.isIntersect(node.x + dx, node.y + dy,
node.width, node.height,
this.visibleArea.x, this.visibleArea.y,
this.visibleArea.width, this.visibleArea.height))
{
var toggle = this.getToggleBounds(root),
toggleView = this.getToggleView(root),
image = this.getIconBounds(root),
vx = image.x + image.width + this.gapx,
vy = node.y + ~~((node.height - node.viewHeight) / 2);
if (toggleView != null) {
toggleView.paint(g, toggle.x, toggle.y, toggle.width, toggle.height, this);
}
if (image.width > 0) {
this.getIconView(root).paint(g, image.x, image.y,
image.width, image.height, this);
}
if (this.selected == root){
this.paintSelectedItem(g, root, node, vx, vy);
}
if (this.paintItem != null) {
this.paintItem(g, root, node, vx, vy);
}
if (this.lnColor != null){
g.setColor(this.lnColor);
var yy = toggle.y + ~~(toggle.height / 2) + 0.5;
g.beginPath();
g.moveTo(toggle.x + (toggleView == null ? ~~(toggle.width / 2) : toggle.width - 1), yy);
g.lineTo(image.x, yy);
g.stroke();
}
}
else {
if (node.y + dy > this.visibleArea.y + this.visibleArea.height ||
node.x + dx > this.visibleArea.x + this.visibleArea.width )
{
return false;
}
}
return this.paintChild(g, root, 0);
};
this.y_ = function (item, isStart){
var node = this.getIM(item),
th = this.getToggleSize(item).height,
ty = node.y + ~~((node.height - th) / 2),
dy = this.scrollManager.getSY(),
y = (item.kids.length > 0) ? (isStart ? ty + th : ty - 1) : ty + ~~(th / 2);
return (y + dy < 0) ? -dy - 1
: ((y + dy > this.height) ? this.height - dy : y);
};
/**
* Paint children items of the given root tree item.
* @param {2DContext} g a graphical context
* @param {zebra.data.Item} root a root tree item
* @param {Integer} index an index
* @return {Boolean}
* @protected
* @method paintChild
*/
this.paintChild = function (g, root, index){
var b = this.isOpen_(root);
if (root == this.firstVisible && this.lnColor != null){
g.setColor(this.lnColor);
var xx = this.getIM(root).x + ~~((b ? this.viewSizes.on.width
: this.viewSizes.off.width) / 2);
g.beginPath();
g.moveTo(xx + 0.5, this.getTop());
g.lineTo(xx + 0.5, this.y_(root, false));
g.stroke();
}
if (b && root.kids.length > 0){
var firstChild = root.kids[0];
if (firstChild == null) return true;
var x = this.getIM(firstChild).x + ~~((this.isOpen_(firstChild) ? this.viewSizes.on.width
: this.viewSizes.off.width) / 2),
count = root.kids.length;
if (index < count) {
var node = this.getIM(root),
y = (index > 0) ? this.y_(root.kids[index - 1], true)
: node.y + ~~((node.height + this.getIconSize(root).height) / 2);
for(var i = index;i < count; i ++ ){
var child = root.kids[i];
if (this.lnColor != null){
g.setColor(this.lnColor);
g.beginPath();
g.moveTo(x + 0.5, y);
g.lineTo(x + 0.5, this.y_(child, false));
g.stroke();
y = this.y_(child, true);
}
if (this.paintBranch(g, child) === false){
if (this.lnColor != null && i + 1 != count){
g.setColor(this.lnColor);
g.beginPath();
g.moveTo(x + 0.5, y);
g.lineTo(x + 0.5, this.height - this.scrollManager.getSY());
g.stroke();
}
return false;
}
}
}
}
return true;
};
this.nextPage = function (item,dir){
var sum = 0, prev = item;
while(item != null && sum < this.visibleArea.height){
sum += (this.getIM(item).height + this.gapy);
prev = item;
item = dir < 0 ? this.findPrev(item) : this.findNext(item);
}
return prev;
};
this.paint = function(g){
if (this.model != null){
this.vVisibility();
if (this.firstVisible != null){
var sx = this.scrollManager.getSX(), sy = this.scrollManager.getSY();
try{
g.translate(sx, sy);
this.paintTree(g, this.firstVisible);
g.translate(-sx, -sy);
}
catch(e) {
g.translate(-sx, -sy);
throw e;
}
}
}
};
/**
* Select the given item.
* @param {zebra.data.Item} an item to be selected. Use null value to clear any selection
* @method select
*/
this.select = function(item){
if (this.isSelectable === true && item != this.selected){
var old = this.selected;
this.selected = item;
if (this.selected != null) {
this.makeVisible(this.selected);
}
this._.selected(this, this.selected);
if (old != null && this.isVerVisible(old)){
var m = this.getItemMetrics(old);
this.repaint(m.x + this.scrollManager.getSX(),
m.y + this.scrollManager.getSY(),
m.width, m.height);
}
if (this.selected != null && this.isVerVisible(this.selected)){
var m = this.getItemMetrics(this.selected);
this.repaint(m.x + this.scrollManager.getSX(),
m.y + this.scrollManager.getSY(),
m.width, m.height);
}
}
};
/**
* Make the given tree item visible. Tree component rendered content can takes more space than
* the UI component size is. In this case the content can be scrolled to make visible required
* tree item.
* @param {zebra.data.Item} item an item to be visible
* @method makeVisible
*/
this.makeVisible = function(item){
this.validate();
var r = this.getItemBounds(item);
this.scrollManager.makeVisible(r.x, r.y, r.width, r.height);
};
/**
* Toggle off or on recursively all items of the given item
* @param {zebra.data.Item} root a starting item to toggle
* @param {Boolean} b true if all items have to be in opened
* state and false otherwise
* @method toggleAll
*/
this.toggleAll = function (root,b){
var model = this.model;
if (root.kids.length > 0){
if (this.getItemMetrics(root).isOpen != b) this.toggle(root);
for(var i = 0;i < root.kids.length; i++ ){
this.toggleAll(root.kids[i], b);
}
}
};
/**
* Toggle the given tree item
* @param {zebra.data.Item} item an item to be toggled
* @method toggle
*/
this.toggle = function(item){
if (item.kids.length > 0){
this.validate();
var node = this.getIM(item);
node.isOpen = (node.isOpen ? false : true);
this.invalidate();
this._.toggled(this, item);
if( !node.isOpen && this.selected != null){
var parent = this.selected;
do {
parent = parent.parent;
}
while(parent != item && parent != null);
if(parent == item) this.select(item);
}
this.repaint();
}
};
this.itemInserted = function (target,item){
this.vrp();
};
this.itemRemoved = function (target,item){
if (item == this.firstVisible) this.firstVisible = null;
if (item == this.selected) this.select(null);
delete this.nodes[item];
this.vrp();
};
this.itemModified = function (target,item){
var node = this.getIM(item);
if (node != null) node.viewWidth = -1;
this.vrp();
};
this.calcPreferredSize = function (target){
return this.model == null ? { width:0, height:0 }
: { width:this.maxw, height:this.maxh };
};
},
function () { this.$this(null); },
function (d){ this.$this(d, true);},
function (d,b){
/**
* Selected tree model item
* @attribute selected
* @type {zebra.data.Item}
* @default null
* @readOnly
*/
this.selected = this.firstVisible = null;
this.maxw = this.maxh = 0;
/**
* Tree component line color
* @attribute lnColor
* @type {String}
* @readOnly
*/
this.visibleArea = this.lnColor = null;
this.views = {};
this.viewSizes = {};
this._isVal = false;
this.nodes = {};
this._ = new pkg.TreeListeners();
this.setLineColor("gray");
this.isOpenVal = b;
this.setSelectable(true);
this.$super();
this.setModel(d);
this.scrollManager = new ui.ScrollManager(this);
},
function focused(){
this.$super();
if (this.selected != null) {
var m = this.getItemMetrics(this.selected);
this.repaint(m.x + this.scrollManager.getSX(),
m.y + this.scrollManager.getSY(), m.width, m.height);
}
},
/**
* Say if items of the tree component should be selectable
* @param {Boolean} b true is tree component items can be selected
* @method setSelectable
*/
function setSelectable(b){
if (this.isSelectable != b){
if (b === false && this.selected != null) this.select(null);
this.isSelectable = b;
this.repaint();
}
},
/**
* Set tree component connector lines color
* @param {String} c a color
* @method setLineColor
*/
function setLineColor(c){
this.lnColor = c;
this.repaint();
},
/**
* Set the given horizontal gaps between tree node graphical elements:
* toggle, icon, item view
* @param {Integer} gx horizontal gap
* @param {Integer} gy vertical gap
* @method setGaps
*/
function setGaps(gx,gy){
if (gx != this.gapx || gy != this.gapy){
this.gapx = gx;
this.gapy = gy;
this.vrp();
}
},
/**
* Set the number of views to customize rendering of different visual elements of the tree
* UI component. The following decorative elements can be customized:
- **"close" ** - closed tree item icon view
- **"open" ** - opened tree item icon view
- **"leaf" ** - leaf tree item icon view
- **"on" ** - toggle on view
- **"off" ** - toggle off view
- **"iselect" ** - a view to express an item selection when tree component doesn't hold focus
- **"aselect" ** - a view to express an item selection when tree component holds focus
* For instance:
// build tree UI component
var tree = new zebra.ui.tree.Tree({
value: "Root",
kids: [
"Item 1",
"Item 2"
]
});
// set " [x] " text render for toggle on and
// " [o] " text render for toggle off tree elements
tree.setViews({
"on": new zebra.ui.TextRender(" [x] "),
"off": new zebra.ui.TextRender(" [o] ")
});
* @param {Object} v dictionary of tree component decorative elements views
* @method setViews
*/
function setViews(v){
for(var k in v) {
if (v.hasOwnProperty(k)) {
var vv = ui.$view(v[k]);
this.views[k] = vv;
if (k != "aselect" && k != "iselect"){
this.viewSizes[k] = vv ? vv.getPreferredSize() : null;
this.vrp();
}
}
}
},
/**
* Set the given tree model to be visualized with the UI component.
* @param {zebra.data.TreeModel|Object} d a tree model
* @method setModel
*/
function setModel(d){
if (this.model != d) {
if (zebra.instanceOf(d, zebra.data.TreeModel) === false) {
d = new zebra.data.TreeModel(d);
}
this.select(null);
if (this.model != null && this.model._) this.model.bind(this);
this.model = d;
if (this.model != null && this.model._) this.model.bind(this);
this.firstVisible = null;
delete this.nodes;
this.nodes = {};
this.vrp();
}
},
function invalidate(){
if (this.isValid === true){
this._isVal = false;
this.$super();
}
}
]);
/**
* Default tree editor provider
* @class zebra.ui.tree.DefEditors
*/
pkg.DefEditors = Class([
function (){
/**
* Internal component that are designed as default editor component
* @private
* @readOnly
* @attribute tf
* @type {zebra.ui.TextField}
*/
this.tf = new ui.TextField(new zebra.data.SingleLineTxt(""));
this.tf.setBackground("white");
this.tf.setBorder(null);
this.tf.setPadding(0);
},
function $prototype() {
/**
* Get an UI component to edit the given tree model element
* @param {zebra.ui.tree.Tree} src a tree component
* @param {zebra.data.Item} item an data model item
* @return {zebra.ui.Panel} an editor UI component
* @method getEditor
*/
this.getEditor = function(src,item){
var o = item.value;
this.tf.setValue((o == null) ? "" : o.toString());
return this.tf;
};
/**
* Fetch a model item from the given UI editor component
* @param {zebra.ui.tree.Tree} src a tree UI component
* @param {zebra.ui.Panel} editor an editor that has been used to edit the tree model element
* @return {Object} an new tree model element value fetched from the given UI editor component
* @method fetchEditedValue
*/
this.fetchEditedValue = function(src, editor){
return editor.view.target.getValue();
};
/**
* The method is called to ask if the given input event should trigger an tree component item
* @param {zebra.ui.tree.Tree} src a tree UI component
* @param {zebra.ui.MouseEvent|zebra.ui.KeyEvent} e an input event: mouse or key event
* @return {Boolean} true if the event should trigger edition of a tree component item
* @method @shouldStartEdit
*/
this.shouldStartEdit = function(src,e){
return (e.ID == ui.MouseEvent.CLICKED && e.clicks > 1) ||
(e.ID == KE.PRESSED && e.code == KE.ENTER);
};
}
]);
/**
* Default tree editor view provider
* @class zebra.ui.tree.DefViews
* @constructor
* @param {String} [color] the tree item text color
* @param {String} [font] the tree item text font
*/
pkg.DefViews = Class([
function $prototype() {
/**
* Get a view for the given model item of the UI tree component
* @param {zebra.ui.tree.Tree} tree a tree component
* @param {zebra.data.Item} item a tree model element
* @return {zebra.ui.View} a view to visualize the given tree data model element
* @method getView
*/
this.getView = function (tree, item){
if (item.value && item.value.paint != null) {
return item.value;
}
this.render.setValue(item.value == null ? "<null>" : item.value);
return this.render;
};
/**
* Set the default view provider text render font
* @param {zebra.ui.Font} f a font
* @method setFont
*/
this.setFont = function(f) {
this.render.setFont(f);
};
/**
* Set the default view provider text render color
* @param {String} c a color
* @method setColor
*/
this.setColor = function(c) {
this.render.setColor(c);
};
this[''] = function(color, font) {
/**
* Default tree item render
* @attribute render
* @readOnly
* @type {zebra.ui.StringRender}
*/
this.render = new ui.StringRender("");
zebra.properties(this, this.$clazz);
if (color != null) this.setColor(color);
if (font != null) this.setFont(font);
};
}
]);
/**
* Tree UI component that visualizes a tree data model. The model itself can be passed as JavaScript
* structure or as a instance of zebra.data.TreeModel. Internally tree component keeps the model always
* as zebra.data.TreeModel class instance:
var tree = new zebra.ui.tree.Tree({
value: "Root",
kids : [ "Item 1", "Item 2"]
});
* or
var model = new zebra.data.TreeModel("Root");
model.add(model.root, "Item 1");
model.add(model.root, "Item 2");
var tree = new zebra.ui.tree.Tree(model);
* Tree model rendering is fully customizable by defining an own views provider. Default views
* provider renders tree model item as text. The tree node can be made editable by defining an
* editor provider. By default tree modes are not editable.
* @class zebra.ui.tree.Tree
* @constructor
* @extends zebra.ui.tree.BaseTree
* @param {Object|zebra.data.TreeModel} [model] a tree data model passed as JavaScript
* structure or as an instance
* @param {Boolean} [b] the tree component items toggle state. true to have all items
* in opened state.
*/
pkg.Tree = Class(pkg.BaseTree, [
function $prototype() {
this.itemGapY = 2;
this.itemGapX = 4;
this.childInputEvent = function(e){
if (e.ID == KE.PRESSED){
if (e.code == KE.ESCAPE) {
this.stopEditing(false);
}
else {
if (e.code == KE.ENTER) {
if ((zebra.instanceOf(e.source, ui.TextField) === false) ||
(zebra.instanceOf(e.source.view.target, zebra.data.SingleLineTxt)))
{
this.stopEditing(true);
}
}
}
}
};
this.catchScrolled = function (psx, psy){
if (this.kids.length > 0) this.stopEditing(false);
if (this.firstVisible == null) this.firstVisible = this.model.root;
this.firstVisible = (this.y < psy) ? this.nextVisible(this.firstVisible)
: this.prevVisible(this.firstVisible);
this.repaint();
};
this.laidout = function() {
this.vVisibility();
};
this.getItemPreferredSize = function(root) {
var ps = this.provider.getView(this, root).getPreferredSize();
ps.width += this.itemGapX * 2;
ps.height += this.itemGapY * 2;
return ps;
};
this.paintItem = function(g, root, node, x, y) {
if (root != this.editedItem){
var v = this.provider.getView(this, root);
v.paint(g, x + this.itemGapX, y + this.itemGapY,
node.viewWidth, node.viewHeight, this);
}
};
/**
* Initiate the given item editing if the specified event matches condition
* @param {zebra.data.Item} item an item to be edited
* @param {zebra.ui.InputEvent} e an even that may trigger the item editing
* @return {Boolean} return true if an item editing process has been started,
* false otherwise
* @method se
* @private
*/
this.se = function (item,e ){
if (item != null){
this.stopEditing(true);
if (this.editors != null && this.editors.shouldStartEdit(item, e)){
this.startEditing(item);
return true;
}
}
return false;
};
this.mouseClicked = function(e){
if (this.se(this.pressedItem, e)) {
this.pressedItem = null;
}
else {
if (this.selected != null &&
e.clicks > 1 && e.isActionMask() &&
this.getItemAt(this.firstVisible, e.x, e.y) == this.selected)
{
this.toggle(this.selected);
}
}
};
this.mouseReleased = function(e){
if (this.se(this.pressedItem, e)) this.pressedItem = null;
};
this.keyTyped = function(e){
if (this.selected != null){
switch(e.ch) {
case '+': if (this.isOpen(this.selected) === false) {
this.toggle(this.selected);
} break;
case '-': if (this.isOpen(this.selected)) {
this.toggle(this.selected);
} break;
}
}
};
this.keyPressed = function(e){
var newSelection = null;
switch(e.code) {
case KE.DOWN :
case KE.RIGHT : newSelection = this.findNext(this.selected);break;
case KE.UP :
case KE.LEFT : newSelection = this.findPrev(this.selected);break;
case KE.HOME : if (e.isControlPressed()) this.select(this.model.root);break;
case KE.END : if (e.isControlPressed()) this.select(this.findLast(this.model.root));break;
case KE.PAGEDOWN: if (this.selected != null) this.select(this.nextPage(this.selected, 1));break;
case KE.PAGEUP : if (this.selected != null) this.select(this.nextPage(this.selected, -1));break;
//!!!!case KE.ENTER: if(this.selected != null) this.toggle(this.selected);break;
}
if (newSelection != null) this.select(newSelection);
this.se(this.selected, e);
};
/**
* Start editing the given if an editor for the item has been defined.
* @param {zebra.data.Item} item an item whose content has to be edited
* @method startEditing
* @protected
*/
this.startEditing = function (item){
this.stopEditing(true);
if (this.editors != null){
var editor = this.editors.getEditor(this, item);
if (editor != null){
this.editedItem = item;
var b = this.getItemBounds(this.editedItem),
ps = editor.getPreferredSize();
editor.setLocation(b.x + this.scrollManager.getSX() + this.itemGapX,
b.y - ~~((ps.height - b.height + 2 * this.itemGapY) / 2) +
this.scrollManager.getSY() + this.itemGapY);
editor.setSize(ps.width, ps.height);
this.add(editor);
ui.focusManager.requestFocus(editor);
}
}
};
/**
* Stop editing currently edited tree item and apply or discard the result of the
* editing to tree data model.
* @param {Boolean} true if the editing result has to be applied to tree data model
* @method stopEditing
* @protected
*/
this.stopEditing = function(applyData){
if (this.editors != null && this.editedItem != null){
try {
if (applyData) {
this.model.setValue(this.editedItem,
this.editors.fetchEditedValue(this.editedItem, this.kids[0]));
}
}
finally{
this.editedItem = null;
this.removeAt(0);
this.requestFocus();
}
}
};
},
function () { this.$this(null); },
function (d){ this.$this(d, true);},
function (d,b){
this.provider = this.editedItem = this.pressedItem = null;
/**
* A tree model items view provider
* @readOnly
* @attribute provider
* @default an instance of zebra.ui.tree.DefsViews
* @type {zebra.ui.tree.DefsViews}
*/
/**
* A tree model editor provider
* @readOnly
* @attribute editors
* @default null
* @type {zebra.ui.tree.DefEditors}
*/
this.editors = null;
this.setViewProvider(new pkg.DefViews());
this.$super(d, b);
},
function toggle() {
this.stopEditing(false);
this.$super();
},
function itemInserted(target,item){
this.stopEditing(false);
this.$super(target,item);
},
function itemRemoved(target,item){
this.stopEditing(false);
this.$super(target,item);
},
/**
* Set the given editor provider. The editor provider is a class that is used to decide which UI
* component has to be used as an item editor, how the editing should be triggered and how the
* edited value has to be fetched from an UI editor.
* @param {zebra.ui.tree.DefEditors} p an editor provider
* @method setEditorProvider
*/
function setEditorProvider(p){
if (p != this.editors){
this.stopEditing(false);
this.editors = p;
}
},
/**
* Set tree component items view provider. Provider says how tree model items
* have to be visualized.
* @param {zebra.ui.tree.DefViews} p a view provider
* @method setViewProvider
*/
function setViewProvider(p){
if (this.provider != p) {
this.stopEditing(false);
this.provider = p;
delete this.nodes;
this.nodes = {};
this.vrp();
}
},
/**
* Set the given tree model to be visualized with the UI component.
* @param {zebra.data.TreeModel|Object} d a tree model
* @method setModel
*/
function setModel(d){
this.stopEditing(false);
this.$super(d);
},
function paintSelectedItem(g, root, node, x, y) {
if (root != this.editedItem) {
this.$super(g, root, node, x, y);
}
},
function itemPressed(root, e) {
this.$super(root, e);
if (this.se(root, e) === false) this.pressedItem = root;
},
function mousePressed(e){
this.pressedItem = null;
this.stopEditing(true);
this.$super(e);
}
]);
/**
* Component tree component that expects other UI components to be a tree model values.
* In general the implementation lays out passed via tree model UI components as tree
* component nodes. For instance:
var tree = new zebra.ui.tree.Tree({
value: new zebra.ui.Label("Label root item"),
kids : [
new zebra.ui.Checkbox("Checkbox Item"),
new zebra.ui.Button("Button item"),
new zebra.ui.Combo(["Combo item 1", "Combo item 2"])
]
});
* But to prevent unexpected navigation it is better to use number of predefined
* with component tree UI components:
- zebra.ui.tree.CompTree.Label
- zebra.ui.tree.CompTree.Checkbox
- zebra.ui.tree.CompTree.Combo
* You can describe tree model keeping in mind special notation
var tree = new zebra.ui.tree.Tree({
value: "Label root item", // zebra.ui.tree.CompTree.Label
kids : [
"[ ] Checkbox Item 1", // unchecked zebra.ui.tree.CompTree.Checkbox
"[x] Checkbox Item 2", // checked zebra.ui.tree.CompTree.Checkbox
["Combo item 1", "Combo item 2"] // zebra.ui.tree.CompTree.Combo
]
});
*
* @class zebra.ui.tree.CompTree
* @constructor
* @extends zebra.ui.tree.BaseTree
* @param {Object|zebra.data.TreeModel} [model] a tree data model passed as JavaScript
* structure or as an instance
* @param {Boolean} [b] the tree component items toggle state. true to have all items
* in opened state.
*/
pkg.CompTree = Class(pkg.BaseTree, [
function $clazz() {
this.Label = Class(ui.Label, [
function $prototype() {
this.canHaveFocus = true;
}
]);
this.Checkbox = Class(ui.Checkbox, []);
this.Combo = Class(ui.Combo, [
function keyPressed(e) {
if (e.code != KE.UP && e.code != KE.DOWN) this.$super(e);
}
]);
},
function $prototype() {
this.canHaveFocus = false;
this.getItemPreferredSize = function(root) {
return root.value.getPreferredSize();
};
this.childInputEvent = function(e) {
if (this.isSelectable) {
if (e.ID == ui.InputEvent.FOCUS_LOST) {
this.select(null);
return;
}
if (e.ID == ui.InputEvent.FOCUS_GAINED || e.ID == ui.MouseEvent.PRESSED) {
var $this = this;
zebra.data.find(this.model.root, zebra.layout.getDirectChild(this, e.source), function(item) {
$this.select(item);
return true;
});
return;
}
if (e.ID == KE.PRESSED) {
var newSelection = (e.code == KE.DOWN) ? this.findNext(this.selected)
: (e.code == KE.UP) ? this.findPrev(this.selected): null;
if (newSelection != null) {
this.select(newSelection);
}
return;
}
}
if (e.ID == KE.TYPED) {
if (this.selected != null){
switch(e.ch) {
case '+': if (this.isOpen(this.selected) === false) {
this.toggle(this.selected);
} break;
case '-': if (this.isOpen(this.selected)) {
this.toggle(this.selected);
} break;
}
}
}
};
this.catchScrolled = function(psx, psy){
this.vrp();
};
this.doLayout = function() {
this.vVisibility();
// hide all components
for(var i=0; i < this.kids.length; i++) {
this.kids[i].isVisible = false;
}
if (this.firstVisible != null) {
var $this = this, fvNode = this.getIM(this.firstVisible), started = 0;
this.model.iterate(this.model.root, function(item) {
var node = $this.nodes[item]; // slightly improve performance (instead of calling $this.getIM(...))
if (started === 0 && item == $this.firstVisible) {
started = 1;
}
if (started === 1) {
var sy = $this.scrollManager.getSY();
if (node.y + sy < $this.height) {
var image = $this.getIconBounds(item);
item.value.x = image.x + image.width + (image.width > 0 || $this.getToggleSize().width > 0 ? $this.gapx : 0) + $this.scrollManager.getSX();
item.value.y = node.y + ~~((node.height - node.viewHeight) / 2) + sy;
item.value.isVisible = true;
item.value.width = node.viewWidth;
item.value.height = node.viewHeight;
}
else {
started = 2;
}
}
return (started === 2) ? 2 : (node.isOpen === false ? 1 : 0);
});
}
};
},
function itemInserted(target, item){
this.add(item.value);
},
function itemRemoved(target,item){
this.$super(target,item);
this.remove(item.value);
},
function setModel(d){
var old = this.model;
this.$super(d);
if (old != this.model) {
this.removeAll();
if (this.model != null) {
var $this = this;
this.model.iterate(this.model.root, function(item) {
if (item.value == null ||
zebra.isString(item.value))
{
if (item.value == null) item.value = "";
item.value = item.value.trim();
var m = item.value.match(/\[\s*(.*)\s*\](.*)/);
if (m != null) {
item.value = new $this.$clazz.Checkbox(m[2]);
item.value.setValue(m[1].trim().length > 0);
}
else {
item.value = new $this.$clazz.Label(item.value);
}
}
else {
if (Array.isArray(item.value)) {
item.value = new $this.$clazz.Combo(item.value);
}
}
$this.add(item.value);
});
}
}
},
function select(item) {
if (this.isSelectable && item != this.selected) {
var old = this.selected;
if (old != null && old.value.hasFocus()) {
ui.focusManager.requestFocus(null);
}
this.$super(item);
if (item != null) {
item.value.requestFocus();
}
}
},
function makeVisible(item) {
item.value.setVisible(true);
this.$super(item);
}
]);
/**
* Toggle view element class
* @class zebra.ui.tree.TreeSignView
* @extends {zebra.ui.View}
* @constructor
* @param {Boolean} plus indicates the sign type plus (true) or minus (false)
* @param {String} color a color
* @param {String} bg a background
*/
pkg.TreeSignView = Class(ui.View, [
function $prototype() {
this[''] = function(plus, color, bg) {
this.color = color == null ? "white" : color;
this.bg = bg == null ? "lightGray" : bg ;
this.plus = plus == null ? false : plus;
this.br = new ui.Border("rgb(65, 131, 215)", 1, 3);
this.width = this.height = 12;
};
this.paint = function(g, x, y, w, h, d) {
this.br.outline(g, x, y, w, h, d);
g.setColor(this.bg);
g.fill();
this.br.paint(g, x, y, w, h, d);
g.setColor(this.color);
g.lineWidth = 2;
x+=2;
w-=4;
h-=4;
y+=2;
g.beginPath();
g.moveTo(x, y + h/2);
g.lineTo(x + w, y + h/2);
if (this.plus) {
g.moveTo(x + w/2, y);
g.lineTo(x + w/2, y + h);
}
g.stroke();
g.lineWidth = 1;
};
this.getPreferredSize = function() {
return { width:this.width, height:this.height};
};
}
]);
/**
* @for
*/
})(zebra("ui.tree"), zebra.Class, zebra.ui); | apache-2.0 |
kuujo/onos | web/api/src/test/java/org/onosproject/rest/resources/FlowsResourceTest.java | 30576 | /*
* Copyright 2016-present Open Networking Foundation
*
* 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.onosproject.rest.resources;
import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.google.common.collect.ImmutableSet;
import org.hamcrest.Description;
import org.hamcrest.Matchers;
import org.hamcrest.TypeSafeMatcher;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onlab.osgi.ServiceDirectory;
import org.onlab.osgi.TestServiceDirectory;
import org.onlab.packet.MacAddress;
import org.onosproject.app.ApplicationService;
import org.onosproject.codec.CodecService;
import org.onosproject.codec.impl.CodecManager;
import org.onosproject.codec.impl.FlowRuleCodec;
import org.onosproject.core.CoreService;
import org.onosproject.core.GroupId;
import org.onosproject.net.DefaultDevice;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.NetTestTools;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.FlowEntry;
import org.onosproject.net.flow.FlowEntryAdapter;
import org.onosproject.net.flow.FlowId;
import org.onosproject.net.flow.FlowRule;
import org.onosproject.net.flow.FlowRuleService;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flow.criteria.Criterion;
import org.onosproject.net.flow.instructions.Instruction;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.anyShort;
import static org.easymock.EasyMock.anyString;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.onosproject.net.NetTestTools.APP_ID;
/**
* Unit tests for Flows REST APIs.
*/
public class FlowsResourceTest extends ResourceTest {
final FlowRuleService mockFlowService = createMock(FlowRuleService.class);
CoreService mockCoreService = createMock(CoreService.class);
final HashMap<DeviceId, Set<FlowEntry>> rules = new HashMap<>();
final DeviceService mockDeviceService = createMock(DeviceService.class);
final DeviceId deviceId1 = DeviceId.deviceId("1");
final DeviceId deviceId2 = DeviceId.deviceId("2");
final DeviceId deviceId3 = DeviceId.deviceId("3");
final Device device1 = new DefaultDevice(null, deviceId1, Device.Type.OTHER,
"", "", "", "", null);
final Device device2 = new DefaultDevice(null, deviceId2, Device.Type.OTHER,
"", "", "", "", null);
final ApplicationService mockApplicationService = createMock(ApplicationService.class);
final MockFlowEntry flow1 = new MockFlowEntry(deviceId1, 1);
final MockFlowEntry flow2 = new MockFlowEntry(deviceId1, 2);
final MockFlowEntry flow3 = new MockFlowEntry(deviceId2, 3);
final MockFlowEntry flow4 = new MockFlowEntry(deviceId2, 4);
final MockFlowEntry flow5 = new MockFlowEntry(deviceId2, 5);
final MockFlowEntry flow6 = new MockFlowEntry(deviceId2, 6);
final Set<FlowEntry> flowEntries = ImmutableSet.of(flow1, flow2, flow3, flow4, flow5, flow6);
/**
* Mock class for a flow entry.
*/
private static class MockFlowEntry extends FlowEntryAdapter {
final DeviceId deviceId;
final long baseValue;
TrafficTreatment treatment;
TrafficSelector selector;
public MockFlowEntry(DeviceId deviceId, long id) {
this.deviceId = deviceId;
this.baseValue = id * 100;
}
@Override
public FlowEntryState state() {
return FlowEntryState.ADDED;
}
@Override
public long life() {
return life(SECONDS);
}
@Override
public long life(TimeUnit timeUnit) {
return SECONDS.convert(baseValue + 11, timeUnit);
}
@Override
public FlowLiveType liveType() {
return FlowLiveType.IMMEDIATE;
}
@Override
public long packets() {
return baseValue + 22;
}
@Override
public long bytes() {
return baseValue + 33;
}
@Override
public long lastSeen() {
return baseValue + 44;
}
@Override
public FlowId id() {
final long id = baseValue + 55;
return FlowId.valueOf(id);
}
@Override
public GroupId groupId() {
return new GroupId(3);
}
@Override
public short appId() {
return 2;
}
@Override
public int priority() {
return (int) (baseValue + 66);
}
@Override
public DeviceId deviceId() {
return deviceId;
}
@Override
public TrafficSelector selector() {
return selector;
}
@Override
public TrafficTreatment treatment() {
return treatment;
}
@Override
public int timeout() {
return (int) (baseValue + 77);
}
@Override
public FlowRemoveReason reason() {
return FlowRemoveReason.NO_REASON;
}
}
/**
* Populates some flows used as testing data.
*/
private void setupMockFlows() {
flow2.treatment = DefaultTrafficTreatment.builder()
.setEthDst(MacAddress.BROADCAST)
.build();
flow2.selector = DefaultTrafficSelector.builder()
.matchEthType((short) 3)
.matchIPProtocol((byte) 9)
.build();
flow4.treatment = DefaultTrafficTreatment.builder()
.build();
final Set<FlowEntry> flows1 = new HashSet<>();
flows1.add(flow1);
flows1.add(flow2);
final Set<FlowEntry> flows2 = new HashSet<>();
flows2.add(flow3);
flows2.add(flow4);
rules.put(deviceId1, flows1);
rules.put(deviceId2, flows2);
expect(mockFlowService.getFlowEntries(deviceId1))
.andReturn(rules.get(deviceId1)).anyTimes();
expect(mockFlowService.getFlowEntries(deviceId2))
.andReturn(rules.get(deviceId2)).anyTimes();
}
/**
* Sets up the global values for all the tests.
*/
@Before
public void setUpTest() {
// Mock device service
expect(mockDeviceService.getDevice(deviceId1))
.andReturn(device1);
expect(mockDeviceService.getDevice(deviceId2))
.andReturn(device2);
expect(mockDeviceService.getDevices())
.andReturn(ImmutableSet.of(device1, device2));
// Mock Core Service
expect(mockCoreService.getAppId(anyShort()))
.andReturn(NetTestTools.APP_ID).anyTimes();
expect(mockCoreService.getAppId(anyString()))
.andReturn(NetTestTools.APP_ID).anyTimes();
expect(mockCoreService.registerApplication(FlowRuleCodec.REST_APP_ID))
.andReturn(APP_ID).anyTimes();
replay(mockCoreService);
// Register the services needed for the test
final CodecManager codecService = new CodecManager();
codecService.activate();
ServiceDirectory testDirectory =
new TestServiceDirectory()
.add(FlowRuleService.class, mockFlowService)
.add(DeviceService.class, mockDeviceService)
.add(CodecService.class, codecService)
.add(CoreService.class, mockCoreService)
.add(ApplicationService.class, mockApplicationService);
setServiceDirectory(testDirectory);
}
/**
* Cleans up and verifies the mocks.
*/
@After
public void tearDownTest() {
verify(mockFlowService);
verify(mockCoreService);
}
/**
* Hamcrest matcher to check that a flow representation in JSON matches
* the actual flow entry.
*/
public static class FlowEntryJsonMatcher extends TypeSafeMatcher<JsonObject> {
private final FlowEntry flow;
private final String expectedAppId;
private String reason = "";
public FlowEntryJsonMatcher(FlowEntry flowValue, String expectedAppIdValue) {
flow = flowValue;
expectedAppId = expectedAppIdValue;
}
@Override
public boolean matchesSafely(JsonObject jsonFlow) {
// check id
final String jsonId = jsonFlow.get("id").asString();
final String flowId = Long.toString(flow.id().value());
if (!jsonId.equals(flowId)) {
reason = "id " + flow.id().toString();
return false;
}
// check application id
final String jsonAppId = jsonFlow.get("appId").asString();
if (!jsonAppId.equals(expectedAppId)) {
reason = "appId " + Short.toString(flow.appId());
return false;
}
// check device id
final String jsonDeviceId = jsonFlow.get("deviceId").asString();
if (!jsonDeviceId.equals(flow.deviceId().toString())) {
reason = "deviceId " + flow.deviceId();
return false;
}
// check treatment and instructions array
if (flow.treatment() != null) {
final JsonObject jsonTreatment = jsonFlow.get("treatment").asObject();
final JsonArray jsonInstructions = jsonTreatment.get("instructions").asArray();
if (flow.treatment().immediate().size() != jsonInstructions.size()) {
reason = "instructions array size of " +
Integer.toString(flow.treatment().immediate().size());
return false;
}
for (final Instruction instruction : flow.treatment().immediate()) {
boolean instructionFound = false;
for (int instructionIndex = 0; instructionIndex < jsonInstructions.size(); instructionIndex++) {
final String jsonType =
jsonInstructions.get(instructionIndex)
.asObject().get("type").asString();
final String instructionType = instruction.type().name();
if (jsonType.equals(instructionType)) {
instructionFound = true;
}
}
if (!instructionFound) {
reason = "instruction " + instruction.toString();
return false;
}
}
}
// check selector and criteria array
if (flow.selector() != null) {
final JsonObject jsonTreatment = jsonFlow.get("selector").asObject();
final JsonArray jsonCriteria = jsonTreatment.get("criteria").asArray();
if (flow.selector().criteria().size() != jsonCriteria.size()) {
reason = "criteria array size of " +
Integer.toString(flow.selector().criteria().size());
return false;
}
for (final Criterion criterion : flow.selector().criteria()) {
boolean criterionFound = false;
for (int criterionIndex = 0; criterionIndex < jsonCriteria.size(); criterionIndex++) {
final String jsonType =
jsonCriteria.get(criterionIndex)
.asObject().get("type").asString();
final String criterionType = criterion.type().name();
if (jsonType.equals(criterionType)) {
criterionFound = true;
}
}
if (!criterionFound) {
reason = "criterion " + criterion.toString();
return false;
}
}
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText(reason);
}
}
/**
* Factory to allocate a flow matcher.
*
* @param flow flow object we are looking for
* @return matcher
*/
private static FlowEntryJsonMatcher matchesFlow(FlowEntry flow, String expectedAppName) {
return new FlowEntryJsonMatcher(flow, expectedAppName);
}
/**
* Hamcrest matcher to check that a flow is represented properly in a JSON
* array of flows.
*/
public static class FlowEntryJsonArrayMatcher extends TypeSafeMatcher<JsonArray> {
private final FlowEntry flow;
private String reason = "";
public FlowEntryJsonArrayMatcher(FlowEntry flowValue) {
flow = flowValue;
}
@Override
public boolean matchesSafely(JsonArray json) {
boolean flowFound = false;
for (int jsonFlowIndex = 0; jsonFlowIndex < json.size();
jsonFlowIndex++) {
final JsonObject jsonFlow = json.get(jsonFlowIndex).asObject();
final String flowId = Long.toString(flow.id().value());
final String jsonFlowId = jsonFlow.get("id").asString();
if (jsonFlowId.equals(flowId)) {
flowFound = true;
// We found the correct flow, check attribute values
assertThat(jsonFlow, matchesFlow(flow, APP_ID.name()));
}
}
if (!flowFound) {
reason = "Flow with id " + flow.id().toString() + " not found";
return false;
} else {
return true;
}
}
@Override
public void describeTo(Description description) {
description.appendText(reason);
}
}
/**
* Factory to allocate a flow array matcher.
*
* @param flow flow object we are looking for
* @return matcher
*/
private static FlowEntryJsonArrayMatcher hasFlow(FlowEntry flow) {
return new FlowEntryJsonArrayMatcher(flow);
}
/**
* Hamcrest matcher to check that a flow representation in JSON matches
* the actual flow rule.
*/
public static class FlowRuleJsonMatcher extends TypeSafeMatcher<JsonObject> {
private final FlowRule flow;
private final String expectedAppId;
private String reason = "";
public FlowRuleJsonMatcher(FlowRule flowValue, String expectedAppIdValue) {
flow = flowValue;
expectedAppId = expectedAppIdValue;
}
@Override
public boolean matchesSafely(JsonObject jsonFlow) {
// check id
final String jsonId = jsonFlow.get("id").asString();
final String flowId = Long.toString(flow.id().value());
if (!jsonId.equals(flowId)) {
reason = "id " + flow.id().toString();
return false;
}
// check application id
final String jsonAppId = jsonFlow.get("appId").asString();
if (!jsonAppId.equals(expectedAppId)) {
reason = "appId " + Short.toString(flow.appId());
return false;
}
// check device id
final String jsonDeviceId = jsonFlow.get("deviceId").asString();
if (!jsonDeviceId.equals(flow.deviceId().toString())) {
reason = "deviceId " + flow.deviceId();
return false;
}
// check treatment and instructions array
if (flow.treatment() != null) {
final JsonObject jsonTreatment = jsonFlow.get("treatment").asObject();
final JsonArray jsonInstructions = jsonTreatment.get("instructions").asArray();
if (flow.treatment().immediate().size() != jsonInstructions.size()) {
reason = "instructions array size of " +
Integer.toString(flow.treatment().immediate().size());
return false;
}
for (final Instruction instruction : flow.treatment().immediate()) {
boolean instructionFound = false;
for (int instructionIndex = 0; instructionIndex < jsonInstructions.size(); instructionIndex++) {
final String jsonType =
jsonInstructions.get(instructionIndex)
.asObject().get("type").asString();
final String instructionType = instruction.type().name();
if (jsonType.equals(instructionType)) {
instructionFound = true;
}
}
if (!instructionFound) {
reason = "instruction " + instruction.toString();
return false;
}
}
}
// check selector and criteria array
if (flow.selector() != null) {
final JsonObject jsonTreatment = jsonFlow.get("selector").asObject();
final JsonArray jsonCriteria = jsonTreatment.get("criteria").asArray();
if (flow.selector().criteria().size() != jsonCriteria.size()) {
reason = "criteria array size of " +
Integer.toString(flow.selector().criteria().size());
return false;
}
for (final Criterion criterion : flow.selector().criteria()) {
boolean criterionFound = false;
for (int criterionIndex = 0; criterionIndex < jsonCriteria.size(); criterionIndex++) {
final String jsonType =
jsonCriteria.get(criterionIndex)
.asObject().get("type").asString();
final String criterionType = criterion.type().name();
if (jsonType.equals(criterionType)) {
criterionFound = true;
}
}
if (!criterionFound) {
reason = "criterion " + criterion.toString();
return false;
}
}
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText(reason);
}
}
/**
* Factory to allocate a flow matcher.
*
* @param flow flow rule object we are looking for
* @return matcher
*/
private static FlowRuleJsonMatcher matchesFlowRule(FlowRule flow, String expectedAppName) {
return new FlowRuleJsonMatcher(flow, expectedAppName);
}
/**
* Hamcrest matcher to check that a flow is represented properly in a JSON
* array of flow rules.
*/
public static class FlowRuleJsonArrayMatcher extends TypeSafeMatcher<JsonArray> {
private final FlowRule flow;
private String reason = "";
public FlowRuleJsonArrayMatcher(FlowRule flowValue) {
flow = flowValue;
}
@Override
public boolean matchesSafely(JsonArray json) {
boolean flowFound = false;
for (int jsonFlowIndex = 0; jsonFlowIndex < json.size();
jsonFlowIndex++) {
final JsonObject jsonFlow = json.get(jsonFlowIndex).asObject();
final String flowId = Long.toString(flow.id().value());
final String jsonFlowId = jsonFlow.get("id").asString();
if (jsonFlowId.equals(flowId)) {
flowFound = true;
// We found the correct flow, check attribute values
assertThat(jsonFlow, matchesFlowRule(flow, APP_ID.name()));
}
}
if (!flowFound) {
reason = "Flow with id " + flow.id().toString() + " not found";
return false;
} else {
return true;
}
}
@Override
public void describeTo(Description description) {
description.appendText(reason);
}
}
/**
* Factory to allocate a flow array matcher.
*
* @param flow flow rule object we are looking for
* @return matcher
*/
private static FlowRuleJsonArrayMatcher hasFlowRule(FlowRule flow) {
return new FlowRuleJsonArrayMatcher(flow);
}
/**
* Tests the result of the rest api GET when there are no flows.
*/
@Test
public void testFlowsEmptyArray() {
expect(mockFlowService.getFlowEntries(deviceId1))
.andReturn(null).anyTimes();
expect(mockFlowService.getFlowEntries(deviceId2))
.andReturn(null).anyTimes();
replay(mockFlowService);
replay(mockDeviceService);
final WebTarget wt = target();
final String response = wt.path("flows").request().get(String.class);
assertThat(response, is("{\"flows\":[]}"));
}
/**
* Tests the result of the rest api GET when there are active flows.
*/
@Test
public void testFlowsPopulatedArray() {
setupMockFlows();
replay(mockFlowService);
replay(mockDeviceService);
final WebTarget wt = target();
final String response = wt.path("flows").request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("flows"));
final JsonArray jsonFlows = result.get("flows").asArray();
assertThat(jsonFlows, notNullValue());
assertThat(jsonFlows, hasFlow(flow1));
assertThat(jsonFlows, hasFlow(flow2));
assertThat(jsonFlows, hasFlow(flow3));
assertThat(jsonFlows, hasFlow(flow4));
}
/**
* Tests the result of a rest api GET for a device.
*/
@Test
public void testFlowsSingleDevice() {
setupMockFlows();
final Set<FlowEntry> flows = new HashSet<>();
flows.add(flow5);
flows.add(flow6);
expect(mockFlowService.getFlowEntries(anyObject()))
.andReturn(flows).anyTimes();
replay(mockFlowService);
replay(mockDeviceService);
final WebTarget wt = target();
final String response = wt.path("flows/" + deviceId3).request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("flows"));
final JsonArray jsonFlows = result.get("flows").asArray();
assertThat(jsonFlows, notNullValue());
assertThat(jsonFlows, hasFlow(flow5));
assertThat(jsonFlows, hasFlow(flow6));
}
/**
* Tests the result of a rest api GET for a device.
*/
@Test
public void testFlowsSingleDeviceWithFlowId() {
setupMockFlows();
final Set<FlowEntry> flows = new HashSet<>();
flows.add(flow5);
flows.add(flow6);
expect(mockFlowService.getFlowEntries(anyObject()))
.andReturn(flows).anyTimes();
replay(mockFlowService);
replay(mockDeviceService);
final WebTarget wt = target();
final String response = wt.path("flows/" + deviceId3 + "/"
+ Long.toString(flow5.id().value())).request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("flows"));
final JsonArray jsonFlows = result.get("flows").asArray();
assertThat(jsonFlows, notNullValue());
assertThat(jsonFlows, hasFlow(flow5));
assertThat(jsonFlows, not(hasFlow(flow6)));
}
/**
* Tests that a fetch of a non-existent device object throws an exception.
*/
@Test
public void testBadGet() {
expect(mockFlowService.getFlowEntries(anyObject()))
.andReturn(null).anyTimes();
replay(mockFlowService);
replay(mockDeviceService);
WebTarget wt = target();
try {
wt.path("flows/0").request().get(String.class);
fail("Fetch of non-existent device did not throw an exception");
} catch (NotFoundException ex) {
assertThat(ex.getMessage(),
containsString("HTTP 404 Not Found"));
}
}
/**
* Tests creating a flow with POST.
*/
@Test
public void testPostWithoutAppId() {
mockFlowService.applyFlowRules(anyObject());
expectLastCall();
replay(mockFlowService);
WebTarget wt = target();
InputStream jsonStream = FlowsResourceTest.class
.getResourceAsStream("post-flow.json");
Response response = wt.path("flows/of:0000000000000001")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.json(jsonStream));
assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED));
String location = response.getLocation().getPath();
assertThat(location, Matchers.startsWith("/flows/of:0000000000000001/"));
}
/**
* Tests creating a flow with POST while specifying application identifier.
*/
@Test
public void testPostWithAppId() {
mockFlowService.applyFlowRules(anyObject());
expectLastCall();
replay(mockFlowService);
WebTarget wt = target();
InputStream jsonStream = FlowsResourceTest.class
.getResourceAsStream("post-flow.json");
Response response = wt.path("flows/of:0000000000000001")
.queryParam("appId", "org.onosproject.rest")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.json(jsonStream));
assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED));
String location = response.getLocation().getPath();
assertThat(location, Matchers.startsWith("/flows/of:0000000000000001/"));
}
/**
* Tests deleting a flow.
*/
@Test
public void testDelete() {
setupMockFlows();
mockFlowService.removeFlowRules(anyObject());
expectLastCall();
replay(mockFlowService);
WebTarget wt = target();
String location = "/flows/1/155";
Response deleteResponse = wt.path(location)
.request(MediaType.APPLICATION_JSON_TYPE)
.delete();
assertThat(deleteResponse.getStatus(),
is(HttpURLConnection.HTTP_NO_CONTENT));
}
/**
* Tests the result of a rest api GET for an application.
*/
@Test
public void testGetFlowByAppId() {
setupMockFlows();
expect(mockApplicationService.getId(anyObject())).andReturn(APP_ID).anyTimes();
replay(mockApplicationService);
expect(mockFlowService.getFlowEntriesById(APP_ID)).andReturn(flowEntries).anyTimes();
replay(mockFlowService);
final WebTarget wt = target();
final String response = wt.path("/flows/application/1").request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("flows"));
final JsonArray jsonFlows = result.get("flows").asArray();
assertThat(jsonFlows, notNullValue());
assertThat(jsonFlows, hasFlowRule(flow1));
assertThat(jsonFlows, hasFlowRule(flow2));
assertThat(jsonFlows, hasFlowRule(flow3));
assertThat(jsonFlows, hasFlowRule(flow4));
}
/**
* Tests the result of a rest api DELETE for an application.
*/
@Test
public void testRemoveFlowByAppId() {
expect(mockApplicationService.getId(anyObject())).andReturn(APP_ID).anyTimes();
replay(mockApplicationService);
mockFlowService.removeFlowRulesById(APP_ID);
expectLastCall();
replay(mockFlowService);
WebTarget wt = target();
String location = "/flows/application/1";
Response deleteResponse = wt.path(location)
.request()
.delete();
assertThat(deleteResponse.getStatus(),
is(HttpURLConnection.HTTP_NO_CONTENT));
}
}
| apache-2.0 |
bazubii/t4ts | T4TS.Example/Models/InheritanceTest2.cs | 219 | namespace T4TS.Example.Models
{
[TypeScriptInterface]
public class InheritanceTest2 : InheritanceTest1
{
public string SomeString2 { get; set; }
public Foobar Recursive2 { get; set; }
}
} | apache-2.0 |
shroman/ignite | modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheGroupData.java | 5385 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.lang.IgniteUuid;
import org.jetbrains.annotations.Nullable;
/**
*
*/
public class CacheGroupData implements Serializable {
/** */
private static final long serialVersionUID = 0L;
/** */
private final int grpId;
/** */
private final String grpName;
/** */
private final AffinityTopologyVersion startTopVer;
/** */
private final UUID rcvdFrom;
/** */
private final IgniteUuid deploymentId;
/** */
private final CacheConfiguration<?, ?> cacheCfg;
/** */
@GridToStringInclude
private final Map<String, Integer> caches;
/** */
private long flags;
/** Persistence enabled flag. */
private final boolean persistenceEnabled;
/** WAL state. */
private final boolean walEnabled;
/** WAL change requests. */
private final List<WalStateProposeMessage> walChangeReqs;
/** Cache configuration enrichment. */
private final CacheConfigurationEnrichment cacheCfgEnrichment;
/**
* @param cacheCfg Cache configuration.
* @param grpName Group name.
* @param grpId Group ID.
* @param rcvdFrom Node ID cache group received from.
* @param startTopVer Start version for dynamically started group.
* @param deploymentId Deployment ID.
* @param caches Cache group caches.
* @param persistenceEnabled Persistence enabled flag.
* @param walEnabled WAL state.
* @param walChangeReqs WAL change requests.
*/
CacheGroupData(
CacheConfiguration cacheCfg,
@Nullable String grpName,
int grpId,
UUID rcvdFrom,
@Nullable AffinityTopologyVersion startTopVer,
IgniteUuid deploymentId,
Map<String, Integer> caches,
long flags,
boolean persistenceEnabled,
boolean walEnabled,
List<WalStateProposeMessage> walChangeReqs,
CacheConfigurationEnrichment cacheCfgEnrichment
) {
assert cacheCfg != null;
assert grpId != 0 : cacheCfg.getName();
assert deploymentId != null : cacheCfg.getName();
this.cacheCfg = cacheCfg;
this.grpName = grpName;
this.grpId = grpId;
this.rcvdFrom = rcvdFrom;
this.startTopVer = startTopVer;
this.deploymentId = deploymentId;
this.caches = caches;
this.flags = flags;
this.persistenceEnabled = persistenceEnabled;
this.walEnabled = walEnabled;
this.walChangeReqs = walChangeReqs;
this.cacheCfgEnrichment = cacheCfgEnrichment;
}
/**
* @return Start version for dynamically started group.
*/
@Nullable public AffinityTopologyVersion startTopologyVersion() {
return startTopVer;
}
/**
* @return Node ID group was received from.
*/
public UUID receivedFrom() {
return rcvdFrom;
}
/**
* @return Group name.
*/
@Nullable public String groupName() {
return grpName;
}
/**
* @return Group ID.
*/
public int groupId() {
return grpId;
}
/**
* @return Deployment ID.
*/
public IgniteUuid deploymentId() {
return deploymentId;
}
/**
* @return Configuration.
*/
public CacheConfiguration<?, ?> config() {
return cacheCfg;
}
/**
* @return Group caches.
*/
Map<String, Integer> caches() {
return caches;
}
/**
* @return Persistence enabled flag.
*/
public boolean persistenceEnabled() {
return persistenceEnabled;
}
/**
* @return {@code True} if WAL is enabled.
*/
public boolean walEnabled() {
return walEnabled;
}
/**
* @return WAL mode change requests.
*/
public List<WalStateProposeMessage> walChangeRequests() {
return walChangeReqs;
}
/**
* @return Cache configuration enrichment.
*/
public CacheConfigurationEnrichment cacheConfigurationEnrichment() {
return cacheCfgEnrichment;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(CacheGroupData.class, this);
}
}
| apache-2.0 |
KasperJanssens/intellij-haskforce | tests/com/haskforce/codeInsight/HaskellFindUsagesTest.java | 1549 | /*
* Copyright 2012-2014 Sergey Ignatov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.haskforce.codeInsight;
import com.haskforce.HaskellLightPlatformCodeInsightFixtureTestCase;
/**
* Typed handler test driver. Add new typed handler testcases here.
*/
public class HaskellFindUsagesTest extends HaskellLightPlatformCodeInsightFixtureTestCase {
public HaskellFindUsagesTest() {
super("codeInsight", "codeInsight");
}
public void testFunctionUsagesInSingleFile00001() { doTest(3); }
public void testFunctionUsagesInMultipleFiles00001() { doTest(3, "FunctionUsagesInSingleFile00001.hs");}
public void testFunctionUsagesInSingleFile00002() { doTest(2); }
private void doTest(int expectedResult, String ... extraFiles) {
String[] files = new String[1 + extraFiles.length];
files[0] = getTestName(false) + ".hs";
System.arraycopy(extraFiles, 0, files, 1, extraFiles.length);
assertEquals(expectedResult, myFixture.testFindUsages(files).size());
}
}
| apache-2.0 |
sll8192/adstar | app/src/main/java/com/cloudTop/starshare/ui/wangyi/session/extension/CustomAttachment.java | 769 | package com.cloudTop.starshare.ui.wangyi.session.extension;
import com.alibaba.fastjson.JSONObject;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
/**
* Created by zhoujianghua on 2015/4/9.
*/
public abstract class CustomAttachment implements MsgAttachment {
protected int type;
CustomAttachment(int type) {
this.type = type;
}
public void fromJson(JSONObject data) {
if (data != null) {
parseData(data);
}
}
@Override
public String toJson(boolean send) {
return CustomAttachParser.packData(type, packData());
}
public int getType() {
return type;
}
protected abstract void parseData(JSONObject data);
protected abstract JSONObject packData();
}
| apache-2.0 |
tombujok/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/util/hashslot/package-info.java | 956 | /*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* 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.
*/
/**
* Contains a family of interfaces that provide a common base for various
* kinds of open-addressed hashtable implementations. The APIs are designed
* to interact with a {@link com.hazelcast.internal.memory.MemoryManager MemoryManager}
* for memory allocation and access.
*/
package com.hazelcast.internal.util.hashslot;
| apache-2.0 |
karthik-sethuraman/ONFOpenTransport | RI/flask_server/tapi_server/models/tapi_notification_notification_type.py | 1291 | # coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from tapi_server.models.base_model_ import Model
from tapi_server import util
class TapiNotificationNotificationType(Model):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
"""
"""
allowed enum values
"""
OBJECT_CREATION = "OBJECT_CREATION"
OBJECT_DELETION = "OBJECT_DELETION"
ATTRIBUTE_VALUE_CHANGE = "ATTRIBUTE_VALUE_CHANGE"
ALARM_EVENT = "ALARM_EVENT"
THRESHOLD_CROSSING_ALERT = "THRESHOLD_CROSSING_ALERT"
def __init__(self): # noqa: E501
"""TapiNotificationNotificationType - a model defined in OpenAPI
"""
self.openapi_types = {
}
self.attribute_map = {
}
@classmethod
def from_dict(cls, dikt) -> 'TapiNotificationNotificationType':
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The tapi.notification.NotificationType of this TapiNotificationNotificationType. # noqa: E501
:rtype: TapiNotificationNotificationType
"""
return util.deserialize_model(dikt, cls)
| apache-2.0 |
opentrv/opentrv | Arduino/snapshots/20140407-r2756-V0p2-Arduino-REV2-beta18-CLI-timing/V0p2_Main/FHT8V_Wireless_Rad_Valve.cpp | 51281 | /*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2013--2014
Mike Stirling 2013
*/
/*
FTH8V wireless radiator valve support.
For details of protocol including sync between this and FHT8V see https://sourceforge.net/p/opentrv/wiki/FHT%20Protocol/
*/
#include <util/atomic.h>
#include <util/parity.h>
#include "FHT8V_Wireless_Rad_Valve.h"
#include "Control.h"
#include "EEPROM_Utils.h"
#include "RFM22_Radio.h"
#include "Serial_IO.h"
#include "Power_Management.h"
#include "UI_Minimal.h"
// Minimum valve percentage open to be considered actually open; [1,100].
// Setting this above 0 delays calling for heat from a central boiler until water is likely able to flow.
// (It may however be possible to scavenge some heat if a particular valve opens below this and the circulation pump is already running, for example.)
// DHD20130522: FHT8V + valve heads I have been using are not typically open until around 6%.
// Use the global value for now.
#define FHT8V_MIN_VALVE_PC_REALLY_OPEN DEFAULT_MIN_VALVE_PC_REALLY_OPEN
#if defined(USE_MODULE_RFM22RADIOSIMPLE)
// Provide RFM22/RFM23 register settings for use with FHT8V in Flash memory.
// Consists of a sequence of (reg#,value) pairs terminated with a 0xff register number. The reg#s are <128, ie top bit clear.
// Magic numbers c/o Mike Stirling!
const uint8_t FHT8V_RFM22_Reg_Values[][2] PROGMEM =
{
{6,0}, // Disable default chiprdy and por interrupts.
{8,0}, // RFM22REG_OP_CTRL2: ANTDIVxxx, RXMPK, AUTOTX, ENLDM
#ifndef RFM22_IS_ACTUALLY_RFM23
// For RFM22 with RXANT tied to GPIO0, and TXANT tied to GPIO1...
{0xb,0x15}, {0xc,0x12}, // Can be omitted FOR RFM23.
#endif
// 0x30 = 0x00 - turn off packet handling
// 0x33 = 0x06 - set 4 byte sync
// 0x34 = 0x08 - set 4 byte preamble
// 0x35 = 0x10 - set preamble threshold (RX) 2 nybbles / 1 bytes of preamble.
// 0x36-0x39 = 0xaacccccc - set sync word, using end of RFM22-pre-preamble and start of FHT8V preamble.
{0x30,0}, {0x33,6}, {0x34,8}, {0x35,0x10}, {0x36,0xaa}, {0x37,0xcc}, {0x38,0xcc}, {0x39,0xcc},
// From AN440: The output power is configurable from +13 dBm to -8 dBm (Si4430/31), and from +20 dBM to -1 dBM (Si4432) in ~3 dB steps. txpow[2:0]=000 corresponds to min output power, while txpow[2:0]=111 corresponds to max output power.
// The maximum legal ERP (not TX output power) on 868.35 MHz is 25 mW with a 1% duty cycle (see IR2030/1/16).
//EEPROM ($6d,%00001111) ; RFM22REG_TX_POWER: Maximum TX power: 100mW for RFM22; not legal in UK/EU on RFM22 for this band.
//EEPROM ($6d,%00001000) ; RFM22REG_TX_POWER: Minimum TX power (-1dBm).
#ifndef RFM22_IS_ACTUALLY_RFM23
#ifndef RFM22_GOOD_RF_ENV
{0x6d,0xd}, // RFM22REG_TX_POWER: RFM22 +14dBm ~25mW ERP with 1/4-wave antenna.
#else // Tone down for good RF backplane, etc.
{0x6d,0x9},
#endif
#else
#ifndef RFM22_GOOD_RF_ENV
{0x6d,0xf}, // RFM22REG_TX_POWER: RFM23 max power (+13dBm) for ERP ~25mW with 1/4-wave antenna.
#else // Tone down for good RF backplane, etc.
{0x6d,0xb},
#endif
#endif
{0x6e,40}, {0x6f,245}, // 5000bps, ie 200us/bit for FHT (6 for 1, 4 for 0). 10485 split across the registers, MSB first.
{0x70,0x20}, // MOD CTRL 1: low bit rate (<30kbps), no Manchester encoding, no whitening.
{0x71,0x21}, // MOD CTRL 2: OOK modulation.
{0x72,0x20}, // Deviation GFSK. ; WAS EEPROM ($72,8) ; Deviation 5 kHz GFSK.
{0x73,0}, {0x74,0}, // Frequency offset
// Channel 0 frequency = 868 MHz, 10 kHz channel steps, high band.
{0x75,0x73}, {0x76,100}, {0x77,0}, // BAND_SELECT,FB(hz), CARRIER_FREQ0&CARRIER_FREQ1,FC(hz) where hz=868MHz
{0x79,35}, // 868.35 MHz - FHT
{0x7a,1}, // One 10kHz channel step.
// RX-only
#ifdef USE_MODULE_FHT8VSIMPLE_RX // RX-specific settings, again c/o Mike S.
{0x1c,0xc1}, {0x1d,0x40}, {0x1e,0xa}, {0x1f,3}, {0x20,0x96}, {0x21,0}, {0x22,0xda}, {0x23,0x74}, {0x24,0}, {0x25,0xdc},
{0x2a,0x24},
{0x2c,0x28}, {0x2d,0xfa}, {0x2e,0x29},
{0x69,0x60}, // AGC enable: SGIN | AGCEN
#endif
{ 0xff, 0xff } // End of settings.
};
#endif // defined(USE_MODULE_RFM22RADIOSIMPLE)
#if 0 // DHD20130226 dump
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
00 : 08 06 20 20 00 00 00 00 00 7F 06 15 12 00 00 00
01 : 00 00 20 00 03 00 01 00 00 01 14 00 C1 40 0A 03
02 : 96 00 DA 74 00 DC 00 1E 00 00 24 00 28 FA 29 08
03 : 00 00 0C 06 08 10 AA CC CC CC 00 00 00 00 00 00
04 : 00 00 00 FF FF FF FF 00 00 00 00 FF 08 08 08 10
05 : 00 00 DF 52 20 64 00 01 87 00 01 00 0E 00 00 00
06 : A0 00 24 00 00 81 02 1F 03 60 9D 00 01 0B 28 F5
07 : 20 21 20 00 00 73 64 00 19 23 01 03 37 04 37
#endif
// Appends encoded 200us-bit representation of logical bit (true for 1, false for 0).
// If the most significant bit is 0 this appends 1100 else this appends 111000
// msb-first to the byte stream being created by FHT8VCreate200usBitStreamBptr.
// bptr must be pointing at the current byte to update on entry which must start off as 0xff;
// this will write the byte and increment bptr (and write 0xff to the new location) if one is filled up.
// Partial byte can only have even number of bits present, ie be in one of 4 states.
// Two least significant bits used to indicate how many bit pairs are still to be filled,
// so initial 0xff value (which is never a valid complete filled byte) indicates 'empty'.
static uint8_t *_FHT8VCreate200usAppendEncBit(uint8_t *bptr, const bool is1)
{
const uint8_t bitPairsLeft = (*bptr) & 3; // Find out how many bit pairs are left to fill in the current byte.
if(!is1) // Appending 1100.
{
switch(bitPairsLeft)
{
case 3: // Empty target byte (should be 0xff currently).
*bptr = 0xcd; // %11001101 Write back partial byte (msbits now 1100 and two bit pairs remain free).
break;
case 2: // Top bit pair already filled.
*bptr = (*bptr & 0xc0) | 0x30; // Preserve existing ms bit-pair, set middle four bits 1100, one bit pair remains free.
break;
case 1: // Top two bit pairs already filled.
*bptr = (*bptr & 0xf0) | 0xc; // Preserve existing ms (2) bit-pairs, set bottom four bits 1100, write back full byte.
*++bptr = (uint8_t) ~0U; // Initialise next byte for next incremental update.
break;
default: // Top three bit pairs already filled.
*bptr |= 3; // Preserve existing ms (3) bit-pairs, OR in leading 11 bits, write back full byte.
*++bptr = 0x3e; // Write trailing 00 bits to next byte and indicate 3 bit-pairs free for next incremental update.
break;
}
}
else // Appending 111000.
{
switch(bitPairsLeft)
{
case 3: // Empty target byte (should be 0xff currently).
*bptr = 0xe0; // %11100000 Write back partial byte (msbits now 111000 and one bit pair remains free).
break;
case 2: // Top bit pair already filled.
*bptr = (*bptr & 0xc0) | 0x38; // Preserve existing ms bit-pair, set lsbits to 111000, write back full byte.
*++bptr = (uint8_t) ~0U; // Initialise next byte for next incremental update.
break;
case 1: // Top two bit pairs already filled.
*bptr = (*bptr & 0xf0) | 0xe; // Preserve existing (2) ms bit-pairs, set bottom four bits to 1110, write back full byte.
*++bptr = 0x3e; // %00111110 Write trailing 00 bits to next byte and indicate 3 bit-pairs free for next incremental update.
break;
default: // Top three bit pairs already filled.
*bptr |= 3; // Preserve existing ms (3) bit-pairs, OR in leading 11 bits, write back full byte.
*++bptr = 0x8d; // Write trailing 1000 bits to next byte and indicate 2 bit-pairs free for next incremental update.
break;
}
}
return(bptr);
}
// Appends encoded byte in b msbit first plus trailing even parity bit (9 bits total)
// to the byte stream being created by FHT8VCreate200usBitStreamBptr.
static uint8_t *_FHT8VCreate200usAppendByteEP(uint8_t *bptr, const uint8_t b)
{
for(uint8_t mask = 0x80; mask != 0; mask >>= 1)
{ bptr = _FHT8VCreate200usAppendEncBit(bptr, 0 != (b & mask)); }
return(_FHT8VCreate200usAppendEncBit(bptr, (bool) parity_even_bit(b))); // Append even parity bit.
}
// Create stream of bytes to be transmitted to FHT80V at 200us per bit, msbit of each byte first.
// Byte stream is terminated by 0xff byte which is not a possible valid encoded byte.
// On entry the populated FHT8V command struct is passed by pointer.
// On exit, the memory block starting at buffer contains the low-byte, msbit-first bit, 0xff-terminated TX sequence.
// The maximum and minimum possible encoded message sizes are 35 (all zero bytes) and 45 (all 0xff bytes) bytes long.
// Note that a buffer space of at least 46 bytes is needed to accommodate the longest-possible encoded message and terminator.
// Returns pointer to the terminating 0xff on exit.
uint8_t *FHT8VCreate200usBitStreamBptr(uint8_t *bptr, const fht8v_msg_t *command)
{
// Generate FHT8V preamble.
// First 12 x 0 bits of preamble, pre-encoded as 6 x 0xcc bytes.
*bptr++ = 0xcc;
*bptr++ = 0xcc;
*bptr++ = 0xcc;
*bptr++ = 0xcc;
*bptr++ = 0xcc;
*bptr++ = 0xcc;
*bptr = (uint8_t) ~0U; // Initialise for _FHT8VCreate200usAppendEncBit routine.
// Push remaining 1 of preamble.
bptr = _FHT8VCreate200usAppendEncBit(bptr, true); // Encode 1.
// Generate body.
bptr = _FHT8VCreate200usAppendByteEP(bptr, command->hc1);
bptr = _FHT8VCreate200usAppendByteEP(bptr, command->hc2);
#ifdef FHT8V_ADR_USED
bptr = _FHT8VCreate200usAppendByteEP(bptr, command->address);
#else
bptr = _FHT8VCreate200usAppendByteEP(bptr, 0); // Default/broadcast. TODO: could possibly be further optimised to send 0 value more efficiently.
#endif
bptr = _FHT8VCreate200usAppendByteEP(bptr, command->command);
bptr = _FHT8VCreate200usAppendByteEP(bptr, command->extension);
// Generate checksum.
#ifdef FHT8V_ADR_USED
const uint8_t checksum = 0xc + command->hc1 + command->hc2 + command->address + command->command + command->extension;
#else
const uint8_t checksum = 0xc + command->hc1 + command->hc2 + command->command + command->extension;
#endif
bptr = _FHT8VCreate200usAppendByteEP(bptr, checksum);
// Generate trailer.
// Append 0 bit for trailer.
bptr = _FHT8VCreate200usAppendEncBit(bptr, false);
// Append extra 0 bit to ensure that final required bits are flushed out.
bptr = _FHT8VCreate200usAppendEncBit(bptr, false);
*bptr = (uint8_t)0xff; // Terminate TX bytes.
return(bptr);
}
// Create FHT8V TRV outgoing valve-setting command frame (terminated with 0xff) at bptr.
// The TRVPercentOpen value is used to generate the frame.
// On entry hc1, hc2 (and addresss if used) must be set correctly; this sets command and extension.
// The generated command frame can be resent indefinitely.
// The command buffer used must be (at least) FHT8V_200US_BIT_STREAM_FRAME_BUF_SIZE bytes.
// Returns pointer to the terminating 0xff on exit.
uint8_t *FHT8VCreateValveSetCmdFrame_r(uint8_t *bptr, fht8v_msg_t *command, const uint8_t TRVPercentOpen)
{
command->command = 0x26;
command->extension = (TRVPercentOpen * 255) / 100;
#ifdef RFM22_SYNC_BCFH
// Huge cheat: only add RFM22-friendly pre-preamble if calling for heat from the boiler (TRV actually open).
// NOTE: this requires more buffer space.
// NOTE: the percentage-open threshold to call for heat from the boiler is set to allow the valve to open significantly, etc.
if(TRVPercentOpen >= getMinValvePcReallyOpen())
{
*bptr++ = 0xaa;
*bptr++ = 0xaa;
*bptr++ = 0xaa;
*bptr++ = 0xaa;
}
#endif
return(FHT8VCreate200usBitStreamBptr(bptr, command));
}
// Clear both housecode parts (and thus disable local valve).
void FHT8VClearHC()
{
eeprom_smart_erase_byte((uint8_t*)EE_START_FHT8V_HC1);
eeprom_smart_erase_byte((uint8_t*)EE_START_FHT8V_HC2);
}
// Set (non-volatile) HC1 and HC2 for single/primary FHT8V wireless valve under control.
void FHT8VSetHC1(uint8_t hc) { eeprom_smart_update_byte((uint8_t*)EE_START_FHT8V_HC1, hc); }
void FHT8VSetHC2(uint8_t hc) { eeprom_smart_update_byte((uint8_t*)EE_START_FHT8V_HC2, hc); }
// Get (non-volatile) HC1 and HC2 for single/primary FHT8V wireless valve under control (will be 0xff until set).
uint8_t FHT8VGetHC1() { return(eeprom_read_byte((uint8_t*)EE_START_FHT8V_HC1)); }
uint8_t FHT8VGetHC2() { return(eeprom_read_byte((uint8_t*)EE_START_FHT8V_HC2)); }
// Shared command buffer for TX to FHT8V.
static uint8_t FHT8VTXCommandArea[FHT8V_200US_BIT_STREAM_FRAME_BUF_SIZE];
// Create FHT8V TRV outgoing valve-setting command frame (terminated with 0xff) in the shared TX buffer.
// The getTRVPercentOpen() result is used to generate the frame.
// HC1 and HC2 are fetched with the FHT8VGetHC1() and FHT8VGetHC2() calls, and address is always 0.
// The generated command frame can be resent indefinitely.
void FHT8VCreateValveSetCmdFrame()
{
fht8v_msg_t command;
command.hc1 = FHT8VGetHC1();
command.hc2 = FHT8VGetHC2();
#ifdef FHT8V_ADR_USED
command.address = 0;
#endif
FHT8VCreateValveSetCmdFrame_r(FHT8VTXCommandArea, &command, getTRVPercentOpen());
}
// True once/while this node is synced with and controlling the target FHT8V valve; initially false.
static bool syncedWithFHT8V;
#ifndef IGNORE_FHT_SYNC
bool isSyncedWithFHT8V() { return(syncedWithFHT8V); }
#else
bool isSyncedWithFHT8V() { return(true); } // Lie and claim always synced.
#endif
// True if FHT8V valve is believed to be open under instruction from this system; false if not in sync.
static bool FHT8V_isValveOpen;
bool getFHT8V_isValveOpen() { return(syncedWithFHT8V && FHT8V_isValveOpen); }
// GLOBAL NOTION OF CONTROLLED VALVE STATE PROVIDED HERE
// True iff the valve(s) (if any) controlled by this unit are really open.
// This waits until, for example, an ACK where appropriate, or at least the command has been sent.
// This also implies open to DEFAULT_MIN_VALVE_PC_REALLY_OPEN or equivalent.
// Must be exectly one definition supplied at link time.
bool isControlledValveOpen() { return(getFHT8V_isValveOpen()); }
// Call just after TX of valve-setting command which is assumed to reflect current TRVPercentOpen state.
// This helps avoiding calling for heat from a central boiler until the valve is really open,
// eg to avoid excess load on (or power wasting in) the circulation pump.
static void setFHT8V_isValveOpen()
{ FHT8V_isValveOpen = (getTRVPercentOpen() >= getMinValvePcReallyOpen()); }
// Sync status and down counter for FHT8V, initially zero; value not important once in sync.
// If syncedWithFHT8V = 0 then resyncing, AND
// if syncStateFHT8V is zero then cycle is starting
// if syncStateFHT8V in range [241,3] (inclusive) then sending sync command 12 messages.
static uint8_t syncStateFHT8V;
// Count-down in half-second units until next transmission to FHT8V valve.
static uint8_t halfSecondsToNextFHT8VTX;
// Call to reset comms with FHT8V valve and force resync.
// Resets values to power-on state so need not be called in program preamble if variables not tinkered with.
// Requires globals defined that this maintains:
// syncedWithFHT8V (bit, true once synced)
// FHT8V_isValveOpen (bit, true if this node has last sent command to open valve)
// syncStateFHT8V (byte, internal)
// halfSecondsToNextFHT8VTX (byte).
void FHT8VSyncAndTXReset()
{
syncedWithFHT8V = false;
syncStateFHT8V = 0;
halfSecondsToNextFHT8VTX = 0;
FHT8V_isValveOpen = false;
}
#if 0
; Call once per second to manage initial sync and subsequent comms with FHT8V valve.
; Requires globals defined that this maintains:
; syncedWithFHT8V (bit, true once synced)
; syncStateFHT8V (byte, internal)
; halfSecondsToNextFHT8VTX (byte)
; Use globals maintained/set elsewhere / shared:
; TRVPercentOpen (byte, in range 0 to 100) valve open percentage to convey to FHT8V
; slowOpDone (bit) set to 1 if this routine takes significant time
; FHT8VTXCommandArea (byte block) for FHT8V outgoing commands
; Can be VERY CPU AND I/O INTENSIVE so running at high clock speed may be necessary.
; If on exit the first byte of the command buffer has been set to $ff
; then the command buffer should immediately (or within a few seconds)
; have a valid outgoing command put in it for the next scheduled transmission to the TRV.
; The command buffer can then be updated whenever required for subsequent async transmissions.
FHT8VPollSyncAndTX:
if syncedWithFHT8V = 0 then
; Give priority to getting in sync over all other tasks, though pass control to them afterwards...
; NOTE: startup state, or state to force resync is: syncedWithFHT8V = 0 AND syncStateFHT8V = 0
if syncStateFHT8V = 0 then
; Starting sync process.
syncStateFHT8V = 241
endif
if syncStateFHT8V >= 3 then
; Generate and send sync (command 12) message immediately.
FHT8V_CMD = $2c ; Command 12, extension byte present.
FHT8V_EXT = syncStateFHT8V
syncStateFHT8V = syncStateFHT8V - 2
bptr = FHT8VTXCommandArea
gosub FHT8VCreate200usBitStreamBptr
bptr = FHT8VTXCommandArea
gosub FHT8VTXFHTQueueAndTwiceSendCmd ; SEND SYNC
; On final tick set up time to sending of final sync command.
if syncStateFHT8V = 1 then
; Set up timer to sent sync final (0) command
; with formula: t = 0.5 * (HC2 & 7) + 4 seconds.
halfSecondsToNextFHT8VTX = FHT8V_HC2 & 7 + 8 ; Note units of half-seconds for this counter.
endif
slowOpDone = 1 ; Will have eaten up lots of time...
else ; < 3 so waiting to send sync final (0) command...
if halfSecondsToNextFHT8VTX >= 2 then
halfSecondsToNextFHT8VTX = halfSecondsToNextFHT8VTX - 2
endif
if halfSecondsToNextFHT8VTX < 2 then
; Set up correct delay to this TX and next TX dealing with half seconds if need be.
gosub FHT8VTXGapHalfSeconds
if halfSecondsToNextFHT8VTX = 1 then ; Need to pause an extra half-second.
pause 500
endif
halfSecondsToNextFHT8VTX = halfSecondsToNextFHT8VTX + tempB0
; Send sync final command.
FHT8V_CMD = $20 ; Command 0, extension byte present.
FHT8V_EXT = 0 ; DHD20130324: could set to TRVPercentOpen, but anything other than zero seems to lock up FHT8V-3 units.
bptr = FHT8VTXCommandArea
gosub FHT8VCreate200usBitStreamBptr
bptr = FHT8VTXCommandArea
gosub FHT8VTXFHTQueueAndTwiceSendCmd ; SEND SYNC FINAL
; Assume now in sync...
syncedWithFHT8V = 1
; Mark buffer as empty to get it filled with the real TRV valve-setting command immediately.
poke FHT8VTXCommandArea, $ff
slowOpDone = 1 ; Will have eaten up lots of time already...
endif
endif
else ; In sync: count down and send command as required.
if halfSecondsToNextFHT8VTX >= 2 then
halfSecondsToNextFHT8VTX = halfSecondsToNextFHT8VTX - 2
endif
if halfSecondsToNextFHT8VTX < 2 then
; Set up correct delay to this TX and next TX dealing with half seconds if need be.
gosub FHT8VTXGapHalfSeconds
if halfSecondsToNextFHT8VTX = 1 then ; Need to pause an extra half-second.
pause 500
endif
halfSecondsToNextFHT8VTX = halfSecondsToNextFHT8VTX + tempB0
; Send already-computed command to TRV.
; Queue and send the command.
bptr = FHT8VTXCommandArea
gosub FHT8VTXFHTQueueAndTwiceSendCmd
; Assume that command just sent reflects the current TRV inetrnal model state.
; If TRVPercentOpen is not zero assume that remote valve is now open(ing).
if TRVPercentOpen = 0 then : FHT8V_isValveOpen = 0 : else : FHT8V_isValveOpen = 1 : endif
slowOpDone = 1 ; Will have eaten up lots of time...
endif
endif
return
#endif
// Sends to FHT8V in FIFO mode command bitstream from buffer starting at bptr up until terminating 0xff,
// then reverts to low-power standby mode if not in hub mode, RX for OpenTRV FHT8V if in hub mode.
// The trailing 0xff is not sent.
// Returns immediately without transmitting if the command buffer starts with 0xff (ie is empty).
// (If doubleTX is true, sends the bitstream twice, with a short (~8ms) pause between transmissions, to help ensure reliable delivery.)
//
// Note: single transmission time is up to about 80ms, double up to about 170ms.
static void FHT8VTXFHTQueueAndSendCmd(uint8_t *bptr, const bool doubleTX)
{
if(((uint8_t)0xff) == *bptr) { return; }
#ifdef DEBUG
if(0 == *bptr) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("FHT8V frame not initialised"); panic(); }
#endif
#if defined(ENABLE_BOILER_HUB)
const bool hubMode = inHubMode();
// Do a final poll for any call for heat that just arrived before doing TX.
if(hubMode) { FHT8VCallForHeatPoll(); }
StopEavesdropOnFHT8V(); // Unconditional cleardown of eavesdrop.
#endif
RFM22QueueCmdToFF(bptr);
RFM22TXFIFO(); // Send it! Approx 1.6ms/byte and < 80ms max.
if(doubleTX)
{
// Should nominally pause about 8--9ms or similar before retransmission...
sleepLowPowerMs(8);
RFM22TXFIFO(); // Re-send it!
}
#if defined(ENABLE_BOILER_HUB)
if(hubMode)
{ SetupToEavesdropOnFHT8V(); } // Revert to hub listening...
else
#endif
{ RFM22ModeStandbyAndClearState(); } // Go to standby to conserve energy.
}
// Send current (assumed valve-setting) command and adjust FHT8V_isValveOpen as appropriate.
// Only appropriate when the command is going to be heard by the FHT8V valve itself, not just the hub.
static void valveSettingTX(const bool allowDoubleTX)
{
// Transmit correct valve-setting command that should already be in the buffer...
FHT8VTXFHTQueueAndSendCmd(FHT8VTXCommandArea, allowDoubleTX);
// Indicate state that valve should now actually be in (or physically moving to)...
setFHT8V_isValveOpen();
}
// Half second count within current minor cycle for FHT8VPollSyncAndTX_XXX().
static uint8_t halfSecondCount;
#if defined(TWO_S_TICK_RTC_SUPPORT)
#define MAX_HSC 3 // Max allowed value of halfSecondCount.
#else
#define MAX_HSC 1 // Max allowed value of halfSecondCount.
#endif
// Compute interval (in half seconds) between TXes for FHT8V given house code 2.
// (In seconds, the formula is t = 115 + 0.5 * (HC2 & 7) seconds, in range [115.0,118.5].)
static uint8_t FHT8VTXGapHalfSeconds(const uint8_t hc2) { return((hc2 & 7) + 230); }
// Compute interval (in half seconds) between TXes for FHT8V given house code 2
// given current halfSecondCountInMinorCycle assuming all remaining tick calls to _Next
// will be foregone in this minor cycle,
static uint8_t FHT8VTXGapHalfSeconds(const uint8_t hc2, const uint8_t halfSecondCountInMinorCycle)
{ return(FHT8VTXGapHalfSeconds(hc2) - (MAX_HSC - halfSecondCountInMinorCycle)); }
// Sleep in reasonably low-power mode until specified target subcycle time, optionally listening (RX) for calls-for-heat.
// Returns true if OK, false if specified time already passed or significantly missed (eg by more than one tick).
// May use a combination of techniques to hit the required time.
// Requesting a sleep until at or near the end of the cycle risks overrun and may be unwise.
// Using this to sleep less then 2 ticks may prove unreliable as the RTC rolls on underneath...
// This is NOT intended to be used to sleep over the end of a minor cycle.
static void sleepUntilSubCycleTimeOptionalRX(const uint8_t sleepUntil)
{
#if defined(ENABLE_BOILER_HUB)
const bool hubMode = inHubMode();
// Slowly poll for incoming RX while waiting for a particular time, eg to TX.
if(hubMode)
{
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINT_FLASHSTRING("TXwait");
#endif
// Only do nap+poll if lots of time left.
while(sleepUntil > fmax(getSubCycleTime() + (50/SUBCYCLE_TICK_MS_RD), GSCT_MAX))
{ nap30AndPoll(); } // Assumed ~30ms sleep max.
// Poll in remaining time without nap.
while(sleepUntil > getSubCycleTime())
{ pollIO(); }
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINT_FLASHSTRING("*");
#endif
}
#endif
// Sleep until exactly the right time.
sleepUntilSubCycleTime(sleepUntil);
#if defined(ENABLE_BOILER_HUB)
// Final quick poll for RX activity.
if(hubMode) { FHT8VCallForHeatPoll(); }
#endif
}
// Run the algorithm to get in sync with the receiver.
// Uses halfSecondCount.
// Iff this returns true then a(nother) call FHT8VPollSyncAndTX_Next() at or before each 0.5s from the cycle start should be made.
static bool doSync(const bool allowDoubleTX)
{
// Do not attempt sync at all (and thus do not attempt any other TX) if local FHT8V valve disabled.
if(!localFHT8VTRVEnabled())
{ syncedWithFHT8V = false; return(false); }
if(0 == syncStateFHT8V)
{
// Starting sync process.
syncStateFHT8V = 241;
#if 1 && defined(DEBUG)
DEBUG_SERIAL_TIMESTAMP();
DEBUG_SERIAL_PRINT(' ');
//DEBUG_SERIAL_PRINTLN_FLASHSTRING("FHT8V syncing...");
#endif
serialPrintlnAndFlush(F("FHT8V SYNC..."));
}
if(syncStateFHT8V >= 2)
{
// Generate and send sync (command 12) message immediately for odd-numbered ticks, ie once per second.
if(syncStateFHT8V & 1)
{
fht8v_msg_t command;
command.hc1 = FHT8VGetHC1();
command.hc2 = FHT8VGetHC2();
command.command = 0x2c; // Command 12, extension byte present.
command.extension = syncStateFHT8V;
FHT8VCreate200usBitStreamBptr(FHT8VTXCommandArea, &command);
if(halfSecondCount > 0)
{ sleepUntilSubCycleTimeOptionalRX((SUB_CYCLE_TICKS_PER_S/2) * halfSecondCount); }
FHT8VTXFHTQueueAndSendCmd(FHT8VTXCommandArea, allowDoubleTX); // SEND SYNC
// Note that FHT8VTXCommandArea now does not contain a valid valve-setting command...
#if 0 && defined(DEBUG)
DEBUG_SERIAL_TIMESTAMP();
DEBUG_SERIAL_PRINT_FLASHSTRING(" FHT8V SYNC ");
DEBUG_SERIAL_PRINT(syncStateFHT8V);
DEBUG_SERIAL_PRINTLN();
#endif
}
// After penultimate sync TX set up time to sending of final sync command.
if(1 == --syncStateFHT8V)
{
// Set up timer to sent sync final (0) command
// with formula: t = 0.5 * (HC2 & 7) + 4 seconds.
halfSecondsToNextFHT8VTX = (FHT8VGetHC2() & 7) + 8; // Note units of half-seconds for this counter.
halfSecondsToNextFHT8VTX -= (MAX_HSC - halfSecondCount);
return(false); // No more TX this minor cycle.
}
}
else // syncStateFHT8V == 1 so waiting to send sync final (0) command...
{
if(--halfSecondsToNextFHT8VTX == 0)
{
// Send sync final command.
fht8v_msg_t command;
command.hc1 = FHT8VGetHC1();
command.hc2 = FHT8VGetHC2();
command.command = 0x20; // Command 0, extension byte present.
command.extension = 0; // DHD20130324: could set to TRVPercentOpen, but anything other than zero seems to lock up FHT8V-3 units.
FHT8V_isValveOpen = false; // Note that valve will be closed (0%) upon receipt.
FHT8VCreate200usBitStreamBptr(FHT8VTXCommandArea, &command);
if(halfSecondCount > 0) { sleepUntilSubCycleTimeOptionalRX((SUB_CYCLE_TICKS_PER_S/2) * halfSecondCount); }
FHT8VTXFHTQueueAndSendCmd(FHT8VTXCommandArea, allowDoubleTX); // SEND SYNC FINAL
// Note that FHT8VTXCommandArea now does not contain a valid valve-setting command...
#if 1 && defined(DEBUG)
DEBUG_SERIAL_TIMESTAMP();
DEBUG_SERIAL_PRINT(' ');
//DEBUG_SERIAL_PRINTLN_FLASHSTRING(" FHT8V SYNC FINAL");
#endif
serialPrintlnAndFlush(F("FHT8V SYNC FINAL"));
// Assume now in sync...
syncedWithFHT8V = true;
// On PICAXE there was no time to recompute valve-setting command immediately after SYNC FINAL SEND...
// Mark buffer as empty to get it filled with the real TRV valve-setting command ASAP.
//*FHT8VTXCommandArea = 0xff;
// On ATmega there is plenty of CPU heft to fill command buffer immediately with valve-setting command.
FHT8VCreateValveSetCmdFrame();
// Set up correct delay to next TX; no more this minor cycle...
halfSecondsToNextFHT8VTX = FHT8VTXGapHalfSeconds(command.hc2, halfSecondCount);
return(false);
}
}
// For simplicity, insist on being called every half-second during sync.
// TODO: avoid forcing most of these calls to save some CPU/energy and improve responsiveness.
return(true);
}
// Call at start of minor cycle to manage initial sync and subsequent comms with FHT8V valve.
// Conveys this system's TRVPercentOpen value to the FHT8V value periodically,
// setting FHT8V_isValveOpen true when the valve will be open/opening provided it received the latest TX from this system.
//
// * allowDoubleTX if true then a double TX is allowed for better resilience, but at cost of extra time and energy
//
// Uses its static/internal transmission buffer, and always leaves it in valid date.
//
// ALSO MANAGES RX FROM OTHER NODES WHEN ENABLED IN HUB MODE.
//
// Iff this returns true then call FHT8VPollSyncAndTX_Next() at or before each 0.5s from the cycle start
// to allow for possible transmissions.
//
// See https://sourceforge.net/p/opentrv/wiki/FHT%20Protocol/ for the underlying protocol.
bool FHT8VPollSyncAndTX_First(const bool allowDoubleTX)
{
halfSecondCount = 0;
#ifdef IGNORE_FHT_SYNC // Will TX on 0 and 2 half second offsets.
// Transmit correct valve-setting command that should already be in the buffer...
valveSettingTX(allowDoubleTX);
return(true); // Will need anther TX in slot 2.
#else
// Give priority to getting in sync over all other tasks, though pass control to them afterwards...
// NOTE: startup state, or state to force resync is: syncedWithFHT8V = 0 AND syncStateFHT8V = 0
if(!syncedWithFHT8V) { return(doSync(allowDoubleTX)); }
#ifdef DEBUG
if(0 == halfSecondsToNextFHT8VTX) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("FHT8V hs count 0 too soon"); panic(); }
#endif
// If no TX required in this minor cycle then can return false quickly (having decremented ticks-to-next-TX value suitably).
if(halfSecondsToNextFHT8VTX > MAX_HSC+1)
{
halfSecondsToNextFHT8VTX -= (MAX_HSC+1);
return(false); // No TX this minor cycle.
}
// TX is due this (first) slot so do it (and no more will be needed this minor cycle).
if(0 == --halfSecondsToNextFHT8VTX)
{
valveSettingTX(allowDoubleTX); // Should be heard by valve.
#if 1 && defined(DEBUG)
DEBUG_SERIAL_TIMESTAMP();
DEBUG_SERIAL_PRINT(' ');
// DEBUG_SERIAL_PRINTLN_FLASHSTRING(" FHT8V TX");
#endif
serialPrintlnAndFlush(F("FHT8V TX"));
// Set up correct delay to next TX.
halfSecondsToNextFHT8VTX = FHT8VTXGapHalfSeconds(FHT8VGetHC2(), 0);
return(false);
}
// Will need to TX in a following slot in this minor cycle...
return(true);
#endif
}
// If FHT8VPollSyncAndTX_First() returned true then call this each 0.5s from the start of the cycle, as nearly as possible.
// This allows for possible transmission slots on each half second.
//
// * allowDoubleTX if true then a double TX is allowed for better resilience, but at cost of extra time and energy
//
// This will sleep (at reasonably low power) as necessary to the start of its TX slot,
// else will return immediately if no TX needed in this slot.
//
// ALSO MANAGES RX FROM OTHER NODES WHEN ENABLED IN HUB MODE.
//
// Iff this returns false then no further TX slots will be needed
// (and thus this routine need not be called again) on this minor cycle
bool FHT8VPollSyncAndTX_Next(const bool allowDoubleTX)
{
++halfSecondCount; // Reflects count of calls since _First(), ie how many
#ifdef DEBUG
if(halfSecondCount > MAX_HSC) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("FHT8VPollSyncAndTX_Next() called too often"); panic(); }
#endif
#ifdef IGNORE_FHT_SYNC // Will TX on 0 and 2 half second offsets.
if(2 == halfSecondCount)
{
// Sleep until 1s from start of cycle.
sleepUntilSubCycleTimeOptionalRX(SUB_CYCLE_TICKS_PER_S);
// Transmit correct valve-setting command that should already be in the buffer...
valveSettingTX(allowDoubleTX);
return(false); // Don't need any slots after this.
}
return(true); // Need to do further TXes this minor cycle.
#else
// Give priority to getting in sync over all other tasks, though pass control to them afterwards...
// NOTE: startup state, or state to force resync is: syncedWithFHT8V = 0 AND syncStateFHT8V = 0
if(!syncedWithFHT8V) { return(doSync(allowDoubleTX)); }
// TX is due this slot so do it (and no more will be needed this minor cycle).
if(0 == --halfSecondsToNextFHT8VTX)
{
sleepUntilSubCycleTimeOptionalRX((SUB_CYCLE_TICKS_PER_S/2) * halfSecondCount); // Sleep.
valveSettingTX(allowDoubleTX); // Should be heard by valve.
#if 1 && defined(DEBUG)
DEBUG_SERIAL_TIMESTAMP();
DEBUG_SERIAL_PRINT(' ');
// DEBUG_SERIAL_PRINTLN_FLASHSTRING(" FHT8V TX");
#endif
serialPrintlnAndFlush(F("FHT8V TX"));
// Set up correct delay to next TX.
halfSecondsToNextFHT8VTX = FHT8VTXGapHalfSeconds(FHT8VGetHC2(), halfSecondCount);
return(false);
}
// Will need to TX in a following slot in this minor cycle...
return(true);
#endif
}
#if defined(FHT8V_ALLOW_EXTRA_TXES)
// Does an extra (single) TX if safe to help ensure that the hub hears, eg in case of poor comms.
// Safe means when in sync with the valve,
// and well away from the normal transmission windows to avoid confusing the valve.
// Returns true iff a TX was done.
// This may also be omitted if the TX would not be heard by the hub anyway.
// Note: (single) transmission time is up to about 80ms.
// In future this may be transmitted so as never to be decoded by the valve,
// and seen by the hub as an extra TX with its offset from the real TX also sent.
bool FHT8VDoSafeExtraTXToHub()
{
// Do nothing until in sync.
if(!syncedWithFHT8V) { return(false); }
// Do nothing if too close to (within maybe 10s of) the start or finish of a ~2m TX cycle
// (which might cause FHT8V to latch onto the wrong, extra, TX, for example).
if((halfSecondsToNextFHT8VTX < 20) || (halfSecondsToNextFHT8VTX > 210)) { return(false); }
// Do nothing if we would not send something that the hub would hear anyway.
if(getTRVPercentOpen() < getMinValvePcReallyOpen()) { return(false); }
// Do (single) TX.
FHT8VTXFHTQueueAndSendCmd(FHT8VTXCommandArea, false);
// Done it.
return(true);
}
#endif
// Hub-mode receive buffer for RX from FHT8V.
static uint8_t FHT8VRXHubArea[FHT8V_200US_BIT_STREAM_FRAME_BUF_SIZE];
// True while eavesdropping for OpenTRV calls for heat.
static volatile bool eavesdropping;
// Set to a house code on receipt of a valid/appropriate valve-open FS20 frame; ~0 if none.
// Stored as hc1:hc2, ie house code 1 is most significant byte.
// Must be written/read under a lock if any chance of access from ISR.
static volatile uint16_t lastCallForHeatHC = ~0;
// Set to a non-zero value when an error is encountered.
// Can be read and cleared atomically.
// Useful to assess the noise enviromentment.
static volatile uint8_t lastRXerrno;
// Atomically returns and clears last (FHT8V) RX error code, or 0 if none.
// Set with such codes as FHT8VRXErr_GENERIC; never set to zero.
static void setLastRXErr(const uint8_t err) { ATOMIC_BLOCK (ATOMIC_RESTORESTATE) { lastRXerrno = err; } }
static void _SetupRFM22ToEavesdropOnFHT8V()
{
RFM22ModeStandbyAndClearState();
RFM22SetUpRX(MIN_FHT8V_200US_BIT_STREAM_BUF_SIZE, true, true); // Set to RX longest-possible valid FS20 encoded frame.
#if !defined(V0p2_REV)
#error Board revision not defined.
#endif
#if V0p2_REV > 0
// TODO: hook into interrupts?
#endif
}
// Set up radio to listen for remote TRV nodes calling for heat iff not already eavesdropping, else does nothing.
// Only done if in central hub mode.
// May set up interrupts/handlers.
// Does NOT clear flags indicating receipt of call for heat for example.
void SetupToEavesdropOnFHT8V(bool force)
{
if(!force && eavesdropping) { return; } // Already eavesdropping.
eavesdropping = true;
_SetupRFM22ToEavesdropOnFHT8V();
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("RX start");
#endif
}
// Stop listening out for remote TRVs calling for heat iff currently eavesdropping, else does nothing.
// Puts radio in standby mode.
// DOES NOT clear flags which indicate that a call for heat has been heard.
void StopEavesdropOnFHT8V(bool force)
{
if(!force && !eavesdropping) { return; }
eavesdropping = false;
RFM22ModeStandbyAndClearState();
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("RX stop");
#endif
}
// Current decode state.
typedef struct
{
uint8_t const *bitStream; // Initially point to first byte of encoded bit stream.
uint8_t const *lastByte; // point to last byte of bit stream.
uint8_t mask; // Current bit mask (the next pair of bits to read); initially 0 to become 0xc0;
bool failed; // If true, the decode has failed and stays failed/true.
} decode_state_t;
// Decode bit pattern 1100 as 0, 111000 as 1.
// Returns 1 or 0 for the bit decoded, else marks the state as failed.
// Reads two bits at a time, MSB to LSB, advancing the byte pointer if necessary.
static uint8_t readOneBit(decode_state_t *const state)
{
if(state->bitStream > state->lastByte) { state->failed = true; } // Stop if off the buffer end.
if(state->failed) { return(0); } // Refuse to do anything further once decoding has failed.
if(0 == state->mask) { state->mask = 0xc0; } // Special treatment of 0 as equivalent to 0xc0 on entry.
#if defined(DEBUG)
if((state->mask != 0xc0) && (state->mask != 0x30) && (state->mask != 0xc) && (state->mask != 3)) { panic(); }
#endif
// First two bits read must be 11.
if(state->mask != (state->mask & *(state->bitStream)))
{
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("leading 11 corrupt");
#endif
state->failed = true; return(0);
}
// Advance the mask; if the mask becomes 0 (then 0xc0 again) then advance the byte pointer.
if(0 == ((state->mask) >>= 2))
{
state->mask = 0xc0;
// If end of stream is encountered this is an error since more bits need to be read.
if(++(state->bitStream) > state->lastByte) { state->failed = true; return(0); }
}
// Next two bits can be 00 to decode a zero,
// or 10 (followed by 00) to decode a one.
const uint8_t secondPair = (state->mask & *(state->bitStream));
switch(secondPair)
{
case 0:
{
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("decoded 0");
#endif
// Advance the mask; if the mask becomes 0 then advance the byte pointer.
if(0 == ((state->mask) >>= 2)) { ++(state->bitStream); }
return(0);
}
case 0x80: case 0x20: case 8: case 2: break; // OK: looks like second pair of an encoded 1.
default:
{
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINT_FLASHSTRING("Invalid second pair ");
DEBUG_SERIAL_PRINTFMT(secondPair, HEX);
DEBUG_SERIAL_PRINT_FLASHSTRING(" from ");
DEBUG_SERIAL_PRINTFMT(*(state->bitStream), HEX);
DEBUG_SERIAL_PRINTLN();
#endif
state->failed = true; return(0);
}
}
// Advance the mask; if the mask becomes 0 (then 0xc0 again) then advance the byte pointer.
if(0 == ((state->mask) >>= 2))
{
state->mask = 0xc0;
// If end of stream is encountered this is an error since more bits need to be read.
if(++(state->bitStream) > state->lastByte) { state->failed = true; return(0); }
}
// Third pair of bits must be 00.
if(0 != (state->mask & *(state->bitStream)))
{
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("trailing 00 corrupt");
#endif
state->failed = true; return(0);
}
// Advance the mask; if the mask becomes 0 then advance the byte pointer.
if(0 == ((state->mask) >>= 2)) { ++(state->bitStream); }
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("decoded 1");
#endif
return(1); // Decoded a 1.
}
// Decodes a series of encoded bits plus parity (and checks the parity, failing if wrong).
// Returns the byte decoded, else marks the state as failed.
static uint8_t readOneByteWithParity(decode_state_t *const state)
{
if(state->failed) { return(0); } // Refuse to do anything further once decoding has failed.
// Read first bit specially...
const uint8_t b7 = readOneBit(state);
uint8_t result = b7;
uint8_t parity = b7;
// Then remaining 7 bits...
for(int i = 7; --i >= 0; )
{
const uint8_t bit = readOneBit(state);
parity ^= bit;
result = (result << 1) | bit;
}
// Then get parity bit and check.
if(parity != readOneBit(state))
{
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("bad parity");
#endif
state->failed = true;
}
return(result);
}
// Decode raw bitstream into non-null command structure passed in; returns true if successful.
// Will return true if OK, else false if anything obviously invalid is detected such as failing parity or checksum.
// Finds and discards leading encoded 1 and trailing 0.
bool FHT8VDecodeBitStream(uint8_t const *bitStream, uint8_t const *lastByte, fht8v_msg_t *command)
{
decode_state_t state;
state.bitStream = bitStream;
state.lastByte = lastByte;
state.mask = 0;
state.failed = false;
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINT_FLASHSTRING("FHT8VDecodeBitStream:");
for(uint8_t const *p = bitStream; p <= lastByte; ++p)
{
DEBUG_SERIAL_PRINT_FLASHSTRING(" &");
DEBUG_SERIAL_PRINTFMT(*p, HEX);
}
DEBUG_SERIAL_PRINTLN();
#endif
// Find and absorb the leading encoded '1', else quit if not found by end of stream.
while(0 == readOneBit(&state)) { if(state.failed) { return(false); } }
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("Read leading 1");
#endif
command->hc1 = readOneByteWithParity(&state);
command->hc2 = readOneByteWithParity(&state);
#ifdef FHT8V_ADR_USED
command->address = readOneByteWithParity(&state);
#else
const uint8_t address = readOneByteWithParity(&state);
#endif
command->command = readOneByteWithParity(&state);
command->extension = readOneByteWithParity(&state);
const uint8_t checksumRead = readOneByteWithParity(&state);
if(state.failed)
{
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("Failed to read message");
#endif
return(false);
}
// Generate and check checksum.
#ifdef FHT8V_ADR_USED
const uint8_t checksum = 0xc + command->hc1 + command->hc2 + command->address + command->command + command->extension;
#else
const uint8_t checksum = 0xc + command->hc1 + command->hc2 + address + command->command + command->extension;
#endif
if(checksum != checksumRead)
{
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("Checksum failed");
#endif
state.failed = true; return(false);
}
// Check the trailing encoded '0'.
if(0 != readOneBit(&state)) { state.failed = true; return(false); }
return(!state.failed);
}
// Polls radio for OpenTRV calls for heat once/if SetupToEavesdropOnFHT8V() is in effect.
// Does not misbehave (eg return false positives) even if SetupToEavesdropOnFHT8V() not set, eg has been in standby.
// If used instead of an interrupt then should probably called at least about once every 100ms.
// Returns true if any useful activity/progress was detected by this call (not necessarily a full valid call-for-heat).
// Upon receipt of a valid call-for-heat this comes out of eavesdropping mode to save energy.
// If a problem is encountered this restarts the eavesdropping process.
// Does not block nor take significant time.
bool FHT8VCallForHeatPoll()
{
// Do nothing unless already in eavesdropping mode.
if(!eavesdropping) { return(false); }
// Do nothing once call for heat has been collected and is pending action.
if(FHT8VCallForHeatHeard()) { return(false); }
#if defined(PIN_RFM_NIRQ)
// If nIRQ line is available then abort if it is not active (and thus spare the SPI bus).
if(fastDigitalRead(PIN_RFM_NIRQ) != LOW) { return(false); }
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("RX IRQ");
#endif
#endif
const uint16_t status = RFM22ReadStatusBoth(); // reg1:reg2, on V0.08 PICAXE tempB2:SPI_DATAB.
// TODO: capture some entropy from RSSI and timing
if(status & 0x1000) // Received frame.
{
// Ensure that a previous frame is not trivially re-read.
for(uint8_t *p = FHT8VRXHubArea + FHT8V_200US_BIT_STREAM_FRAME_BUF_SIZE; --p >= FHT8VRXHubArea; )
{ *p = 0; }
// Attempt to read the entire frame.
RFM22RXFIFO(FHT8VRXHubArea, FHT8V_200US_BIT_STREAM_FRAME_BUF_SIZE);
uint8_t pos; // Current byte position in RX buffer...
// Validate FHT8V premable (zeros encoded as up to 6x 0xcc bytes), else abort/restart.
// Insist on at least a couple of bytes of valid premable being present.
for(pos = 0; pos < 6; ++pos)
{
if(0xcc != FHT8VRXHubArea[pos])
{
if(pos < 2)
{
setLastRXErr(FHT8VRXErr_BAD_PREAMBLE);
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINT_FLASHSTRING("RX premable bad byte @");
DEBUG_SERIAL_PRINT(pos);
DEBUG_SERIAL_PRINT_FLASHSTRING(" value 0x");
DEBUG_SERIAL_PRINTFMT(FHT8VRXHubArea[pos], HEX);
DEBUG_SERIAL_PRINTLN();
#endif
_SetupRFM22ToEavesdropOnFHT8V(); // Reset/restart RX.
return(false);
}
break; // If enough preamble has been seen, move on to the body.
}
}
fht8v_msg_t command;
const bool decoded = FHT8VDecodeBitStream(FHT8VRXHubArea + pos, FHT8VRXHubArea + FHT8V_200US_BIT_STREAM_FRAME_BUF_SIZE - 1, &command);
if(decoded)
{
#if 0 && defined(DEBUG) // VERY SLOW: cannot leave this enabled in normal operation.
DEBUG_SERIAL_PRINT_FLASHSTRING("RX raw");
for(uint8_t i = pos; i < FHT8V_200US_BIT_STREAM_FRAME_BUF_SIZE; ++i)
{
const uint8_t b = FHT8VRXHubArea[i];
DEBUG_SERIAL_PRINT_FLASHSTRING(" &");
DEBUG_SERIAL_PRINTFMT(b, HEX);
if(0 == b) { break; } // Stop after first zero (0 could contain at most 2 trailing bits of a valid code).
}
DEBUG_SERIAL_PRINTLN();
#endif
#if 0 && defined(DEBUG) // VERY SLOW: cannot leave this enabled in normal operation.
DEBUG_SERIAL_PRINT_FLASHSTRING("RX: HC");
DEBUG_SERIAL_PRINT(command.hc1);
DEBUG_SERIAL_PRINT(',');
DEBUG_SERIAL_PRINT(command.hc2);
DEBUG_SERIAL_PRINT_FLASHSTRING(" cmd ");
DEBUG_SERIAL_PRINT(command.command);
DEBUG_SERIAL_PRINT_FLASHSTRING(" ext ");
DEBUG_SERIAL_PRINT(command.extension);
DEBUG_SERIAL_PRINTLN();
#endif
// Potentially accept as call for heat only if command is 0x26 (38) and value open enough as used by OpenTRV to TX.
if((0x26 == command.command) && (command.extension >= getMinValvePcReallyOpen()))
{
const uint16_t compoundHC = (command.hc1 << 8) | command.hc2;
if(FHT8VHubAcceptedHouseCode(command.hc1, command.hc2))
{
// Accept if house code not filtered out.
ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
{ lastCallForHeatHC = compoundHC; } // Update atomically.
StopEavesdropOnFHT8V(); // Need not eavesdrop for a while.
}
}
return(true); // Got a valid frame.
}
else
{
setLastRXErr(FHT8VRXErr_BAD_RX_FRAME);
#if 1 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("Bad RX frame");
#endif
_SetupRFM22ToEavesdropOnFHT8V(); // Reset/restart RX.
return(false);
}
}
// else if(status & 0x80) // Got sync from incoming FHT8V message.
// {
//// syncSeen = true;
// return(true);
// }
else if(status & 0x8000) // RX FIFO overflow/underflow: give up and restart...
{
setLastRXErr(FHT8VRXErr_GENERIC);
#if 1 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("RX FIFO problem");
#endif
_SetupRFM22ToEavesdropOnFHT8V(); // Reset/restart RX.
return(false);
}
return(false);
}
// Returns true if there is a pending accepted call for heat.
// If so a non-~0 housecode will be returned by FHT8VCallForHeatHeardGetAndClear().
bool FHT8VCallForHeatHeard()
{
ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
{ return(lastCallForHeatHC != (uint16_t)~0); }
}
// Atomically returns and clears one housecode calling for heat heard since last call, or ~0 if none.
uint16_t FHT8VCallForHeatHeardGetAndClear()
{
ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
{
const uint16_t result = lastCallForHeatHC;
lastCallForHeatHC = ~0;
return(result);
}
}
// Atomically returns and clears last (FHT8V) RX error code, or 0 if none.
uint8_t FHT8VLastRXErrGetAndClear()
{
ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
{
const uint8_t result = lastRXerrno;
lastRXerrno = 0;
return(result);
}
}
// Count of house codes selectively listened for at hub.
// If zero then calls for heat are not filtered by house code.
#ifndef FHT8VHubListenCount
uint8_t FHT8VHubListenCount()
{ return(0); } // TODO
#endif
// Get remembered house code N where N < FHT8V_MAX_HUB_REMEMBERED_HOUSECODES.
// Returns hc1:hc2 packed into a 16-bit value, with hc1 in most-significant byte.
// Returns 0xffff if requested house code index not in use.
#ifndef FHT8CHubListenHouseCodeAtIndex
uint16_t FHT8CHubListenHouseCodeAtIndex(uint8_t index)
{ return((uint16_t) ~0); } // TODO
#endif
// Remember and respond to calls for heat from hc1:hc2 when a hub.
// Returns true if successfully remembered (or already present), else false if cannot be remembered.
#ifndef FHT8VHubListenForHouseCode
bool FHT8VHubListenForHouseCode(uint8_t hc1, uint8_t hc2)
{ return(false); } // TODO
#endif
// Forget and no longer respond to calls for heat from hc1:hc2 when a hub.
#ifndef FHT8VHubUnlistenForHouseCode
void FHT8VHubUnlistenForHouseCode(uint8_t hc1, uint8_t hc2)
{ } // TODO
#endif
// Returns true if given house code is a remembered one to accept calls for heat from, or if no filtering is being done.
// Fast, and safe to call from an interrupt routine.
#ifndef FHT8VHubAcceptedHouseCode
bool FHT8VHubAcceptedHouseCode(uint8_t hc1, uint8_t hc2)
{ return(true); } // TODO
#endif
| apache-2.0 |
mathemage/h2o-3 | h2o-algos/src/main/java/hex/tree/TreeStats.java | 1299 | package hex.tree;
import water.Iced;
public class TreeStats extends Iced {
public int _min_depth = 0;
public int _max_depth = 0;
public float _mean_depth;
public int _min_leaves = 0;
public int _max_leaves = 0;
public float _mean_leaves;
public long _byte_size;
public int _num_trees = 0;
transient long _sum_depth = 0;
transient long _sum_leaves = 0;
public boolean isValid() { return _min_depth <= _max_depth; }
public void updateBy(DTree tree) {
if( tree == null ) return;
if( _min_depth == 0 || _min_depth > tree._depth ) _min_depth = tree._depth;
if( _max_depth == 0 || _max_depth < tree._depth ) _max_depth = tree._depth;
if( _min_leaves == 0 || _min_leaves > tree._leaves) _min_leaves = tree._leaves;
if( _max_leaves == 0 || _max_leaves < tree._leaves) _max_leaves = tree._leaves;
_sum_depth += tree._depth;
_sum_leaves += tree._leaves;
_num_trees++;
_mean_depth = ((float) _sum_depth / _num_trees);
_mean_leaves = ((float) _sum_leaves / _num_trees);
}
public void setNumTrees(int i) { _num_trees = i; }
@Override
public String toString() {
return "TreeStats{" +
"_min_depth=" + _min_depth +
", _max_depth=" + _max_depth +
", _mean_depth=" + _mean_depth +
'}';
}
}
| apache-2.0 |