repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
geomaster/Aurora3D | Aurora/include/boost/spirit/home/lex/tokenize_and_parse_attr.hpp | 4451 | // Copyright (c) 2001-2011 Hartmut Kaiser
// Copyright (c) 2001-2011 Joel de Guzman
// Copyright (c) 2009 Carl Barron
//
// 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)
#if !defined(BOOST_PP_IS_ITERATING)
#if !defined(BOOST_SPIRIT_LEXER_PARSE_ATTR_MAY_27_2009_0926AM)
#define BOOST_SPIRIT_LEXER_PARSE_ATTR_MAY_27_2009_0926AM
#include <boost/spirit/home/lex/tokenize_and_parse.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/iterate.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#define BOOST_PP_FILENAME_1 <boost/spirit/home/lex/tokenize_and_parse_attr.hpp>
#define BOOST_PP_ITERATION_LIMITS (2, SPIRIT_ARGUMENTS_LIMIT)
#include BOOST_PP_ITERATE()
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Preprocessor vertical repetition code
//
///////////////////////////////////////////////////////////////////////////////
#else // defined(BOOST_PP_IS_ITERATING)
#define N BOOST_PP_ITERATION()
#define BOOST_SPIRIT_QI_ATTRIBUTE_REFERENCE(z, n, A) BOOST_PP_CAT(A, n)&
namespace boost { namespace spirit { namespace lex
{
template <typename Iterator, typename Lexer, typename ParserExpr
, BOOST_PP_ENUM_PARAMS(N, typename A)>
inline bool
tokenize_and_parse(Iterator& first, Iterator last, Lexer const& lex
, ParserExpr const& expr, BOOST_PP_ENUM_BINARY_PARAMS(N, A, & attr))
{
// Report invalid expression error as early as possible.
// If you got an error_invalid_expression error message here,
// then the expression (expr) is not a valid spirit qi expression.
BOOST_SPIRIT_ASSERT_MATCH(qi::domain, ParserExpr);
typedef fusion::vector<
BOOST_PP_ENUM(N, BOOST_SPIRIT_QI_ATTRIBUTE_REFERENCE, A)
> vector_type;
vector_type attr (BOOST_PP_ENUM_PARAMS(N, attr));
typename Lexer::iterator_type iter = lex.begin(first, last);
return compile<qi::domain>(expr).parse(
iter, lex.end(), unused, unused, attr);
}
///////////////////////////////////////////////////////////////////////////
template <typename Iterator, typename Lexer, typename ParserExpr
, typename Skipper, BOOST_PP_ENUM_PARAMS(N, typename A)>
inline bool
tokenize_and_phrase_parse(Iterator& first, Iterator last, Lexer const& lex
, ParserExpr const& expr, Skipper const& skipper
, BOOST_SCOPED_ENUM(skip_flag) post_skip
, BOOST_PP_ENUM_BINARY_PARAMS(N, A, & attr))
{
// Report invalid expression error as early as possible.
// If you got an error_invalid_expression error message here,
// then either the expression (expr) or skipper is not a valid
// spirit qi expression.
BOOST_SPIRIT_ASSERT_MATCH(qi::domain, ParserExpr);
BOOST_SPIRIT_ASSERT_MATCH(qi::domain, Skipper);
typedef
typename result_of::compile<qi::domain, Skipper>::type
skipper_type;
skipper_type const skipper_ = compile<qi::domain>(skipper);
typedef fusion::vector<
BOOST_PP_ENUM(N, BOOST_SPIRIT_QI_ATTRIBUTE_REFERENCE, A)
> vector_type;
vector_type attr (BOOST_PP_ENUM_PARAMS(N, attr));
typename Lexer::iterator_type iter = lex.begin(first, last);
if (!compile<qi::domain>(expr).parse(
iter, lex.end(), unused, skipper_, attr))
return false;
if (post_skip == skip_flag::postskip)
qi::skip_over(first, last, skipper_);
return true;
}
template <typename Iterator, typename Lexer, typename ParserExpr
, typename Skipper, BOOST_PP_ENUM_PARAMS(N, typename A)>
inline bool
tokenize_and_phrase_parse(Iterator& first, Iterator last, Lexer const& lex
, ParserExpr const& expr, Skipper const& skipper
, BOOST_PP_ENUM_BINARY_PARAMS(N, A, & attr))
{
return tokenize_and_phrase_parse(first, last, expr, skipper
, skip_flag::postskip, BOOST_PP_ENUM_PARAMS(N, attr));
}
}}}
#undef BOOST_SPIRIT_QI_ATTRIBUTE_REFERENCE
#undef N
#endif
| gpl-3.0 |
DeinFreund/Zero-K-Infrastructure | ZkData/Migrations/201712101826097_SpringFilesUnitsyncAttempts.Designer.cs | 859 | // <auto-generated />
namespace ZkData.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
public sealed partial class SpringFilesUnitsyncAttempts : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(SpringFilesUnitsyncAttempts));
string IMigrationMetadata.Id
{
get { return "201712101826097_SpringFilesUnitsyncAttempts"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| gpl-3.0 |
remytms/Distribution | plugin/claco-form/Repository/CategoryRepository.php | 1002 | <?php
/*
* This file is part of the Claroline Connect package.
*
* (c) Claroline Consortium <consortium@claroline.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Claroline\ClacoFormBundle\Repository;
use Claroline\ClacoFormBundle\Entity\ClacoForm;
use Claroline\CoreBundle\Entity\User;
use Doctrine\ORM\EntityRepository;
class CategoryRepository extends EntityRepository
{
public function findCategoriesByManager(ClacoForm $clacoForm, User $manager)
{
$dql = '
SELECT c
FROM Claroline\ClacoFormBundle\Entity\Category c
JOIN c.clacoForm cf
JOIN c.managers m
WHERE cf = :clacoForm
AND m = :manager
';
$query = $this->_em->createQuery($dql);
$query->setParameter('clacoForm', $clacoForm);
$query->setParameter('manager', $manager);
return $query->getResult();
}
}
| gpl-3.0 |
chip/rhodes | platform/wm/rhodes/menubar.cpp | 2643 | #include "stdafx.h"
#if !defined(_WIN32_WCE)
#include "resource.h"
#include "menubar.h"
/*
void CODButtonImpl::DrawItem ( LPDRAWITEMSTRUCT lpdis )
{
CDCHandle dc = lpdis->hDC;
CDC dcMem;
dcMem.CreateCompatibleDC ( dc );
dc.SaveDC();
dcMem.SaveDC();
// Draw the button's background, red if it has the focus, blue if not.
if ( lpdis->itemState & ODS_FOCUS ) {
dc.FillSolidRect ( &lpdis->rcItem, ::GetSysColor(COLOR_3DLIGHT) );
dc.Draw3dRect(&lpdis->rcItem, ::GetSysColor(COLOR_BTNHILIGHT), ::GetSysColor(COLOR_BTNSHADOW));
} else {
dc.FillSolidRect ( &lpdis->rcItem, ::GetSysColor(COLOR_3DLIGHT) );
}
// Draw the bitmap in the top-left, or offset by 1 pixel if the button
// is clicked.
//dcMem.SelectBitmap ( m_bmp );
//if ( lpdis->itemState & ODS_SELECTED )
// dc.BitBlt ( 1, 1, 80, 80, dcMem, 0, 0, SRCCOPY );
//else
// dc.BitBlt ( 0, 0, 80, 80, dcMem, 0, 0, SRCCOPY );
dcMem.RestoreDC(-1);
dc.RestoreDC(-1);
}
*/
LRESULT CMenuBar::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) {
// m_btnLeft.Create(m_hWnd,CWindow::rcDefault,TEXT("Exit"),WS_CHILD|WS_VISIBLE|BS_OWNERDRAW,0,10);
// m_btnRight.Create(m_hWnd,CWindow::rcDefault,TEXT("Menu"),WS_CHILD|WS_VISIBLE|BS_OWNERDRAW,0,11);
m_btnLeft.Create(m_hWnd,CWindow::rcDefault,TEXT("Back"),WS_CHILD|WS_VISIBLE,0,IDB_BACK);
m_btnRight.Create(m_hWnd,CWindow::rcDefault,TEXT("Menu"),WS_CHILD|WS_VISIBLE,0,IDB_MENU);
return 0;
}
LRESULT CMenuBar::OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/) {
if (m_btnLeft.m_hWnd && m_btnRight.m_hWnd) {
int width = LOWORD(lParam)>>1;
m_btnLeft.MoveWindow(1, 1, width-1, HIWORD(lParam)-2);
m_btnRight.MoveWindow(width, 1, LOWORD(lParam)-width-1, HIWORD(lParam)-2);
}
return 0;
}
LRESULT CMenuBar::OnEraseBkgnd(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled) {
HDC hDC = (HDC)wParam;
RECT rect;
GetClientRect(&rect);
COLORREF clrOld = ::SetBkColor(hDC, ::GetSysColor(COLOR_3DLIGHT));
if(clrOld != CLR_INVALID) {
RECT rect;
::GetClientRect(m_hWnd,&rect);
::ExtTextOut(hDC, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
::SetBkColor(hDC, clrOld);
}
bHandled = TRUE;
return 0;
}
LRESULT CMenuBar::OnBackCommand(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
::PostMessage(this->GetParent(),WM_COMMAND,IDM_BACK,0);
return 0;
}
LRESULT CMenuBar::OnMenuCommand(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
::PostMessage(this->GetParent(),WM_COMMAND,IDM_POPUP_MENU,0);
return 0;
}
#endif //!defined(_WIN32_WCE) | gpl-3.0 |
dragome/dragome-examples | dragome-jbox2d-examples/src/main/java/org/jbox2d/gwt/showcase/client/example/ShapeEditing.java | 3986 | /*******************************************************************************
* Copyright (c) 2011, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL DANIEL MURPHY BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
/**
* Created at 2:04:52 PM Jan 23, 2011
*/
package org.jbox2d.gwt.showcase.client.example;
import java.util.List;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.Fixture;
import org.jbox2d.gwt.showcase.client.framework.BaseExample;
import org.jbox2d.gwt.showcase.client.framework.ShowcaseSettings;
/**
* @author Daniel Murphy
*/
public class ShapeEditing extends BaseExample {
Body m_body;
Fixture m_fixture1;
Fixture m_fixture2;
/**
* @see org.jbox2d.testbed.framework.TestbedTest#initTest()
*/
@Override
public void initTest() {
{
BodyDef bd = new BodyDef();
Body ground = m_world.createBody(bd);
PolygonShape shape = new PolygonShape();
shape.setAsEdge(new Vec2(-40.0f, 0.0f), new Vec2(40.0f, 0.0f));
ground.createFixture(shape, 0.0f);
}
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(0.0f, 10.0f);
m_body = m_world.createBody(bd);
PolygonShape shape = new PolygonShape();
shape.setAsBox(4.0f, 4.0f, new Vec2(0.0f, 0.0f), 0.0f);
m_fixture1 = m_body.createFixture(shape, 10.0f);
m_fixture2 = null;
}
/**
* @see org.jbox2d.testbed.framework.TestbedTest#keyPressed(char, int)
*/
@Override
public void keyPressed(char key, int argKeyCode, ShowcaseSettings settings) {
switch (key)
{
case 'c':
if (m_fixture2 == null)
{
CircleShape shape = new CircleShape();
shape.m_radius = 3.0f;
shape.m_p.set(0.5f, -4.0f);
m_fixture2 = m_body.createFixture(shape, 10.0f);
m_body.setAwake(true);
}
break;
case 'd':
if (m_fixture2 != null)
{
m_body.destroyFixture(m_fixture2);
m_fixture2 = null;
m_body.setAwake(true);
}
break;
}
}
@Override
public List<String> getInstructions() {
List<String> instructions = super.getInstructions();
instructions.add("Press: (c) create a shape, (d) destroy a shape.");
return instructions;
}
/**
* @see org.jbox2d.testbed.framework.TestbedTest#getTestName()
*/
@Override
public String getTestName() {
return "Shape Editing";
}
}
| gpl-3.0 |
montecillodavid/createconvert_updates | src/com/createconvertupdates/adapters/ViewPagerAdapter.java | 872 | package com.createconvertupdates.adapters;
import com.createconvertupdates.media.MessageListingFragment;
import com.createconvertupdates.media.ProjectListingFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class ViewPagerAdapter extends FragmentPagerAdapter {
public final static int PAGES = 2;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
switch(arg0){
case 0 : return new ProjectListingFragment();
case 1 : return new MessageListingFragment();
default: assert false;
};
return null;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return PAGES;
}
}
| gpl-3.0 |
cbrherms/Shinobi | web/libs/js/pnotify.custom.min.js | 30744 | /*
PNotify 3.0.0 sciactive.com/pnotify/
(C) 2015 Hunter Perrin; Google, Inc.
license Apache-2.0
*/
(function(b,k){"function"===typeof define&&define.amd?define("pnotify",["jquery"],function(q){return k(q,b)}):"object"===typeof exports&&"undefined"!==typeof module?module.exports=k(require("jquery"),global||b):b.PNotify=k(b.jQuery,b)})("undefined"!==typeof window?window:this,function(b,k){var q=function(l){var k={dir1:"down",dir2:"left",push:"bottom",spacing1:36,spacing2:36,context:b("body"),modal:!1},g,h,n=b(l),r=function(){h=b("body");d.prototype.options.stack.context=h;n=b(l);n.bind("resize",
function(){g&&clearTimeout(g);g=setTimeout(function(){d.positionAll(!0)},10)})},s=function(c){var a=b("<div />",{"class":"ui-pnotify-modal-overlay"});a.prependTo(c.context);c.overlay_close&&a.click(function(){d.removeStack(c)});return a},d=function(c){this.parseOptions(c);this.init()};b.extend(d.prototype,{version:"3.0.0",options:{title:!1,title_escape:!1,text:!1,text_escape:!1,styling:"brighttheme",addclass:"",cornerclass:"",auto_display:!0,width:"300px",min_height:"16px",type:"notice",icon:!0,animation:"fade",
animate_speed:"normal",shadow:!0,hide:!0,delay:8E3,mouse_reset:!0,remove:!0,insert_brs:!0,destroy:!0,stack:k},modules:{},runModules:function(c,a){var p,b;for(b in this.modules)p="object"===typeof a&&b in a?a[b]:a,"function"===typeof this.modules[b][c]&&(this.modules[b].notice=this,this.modules[b].options="object"===typeof this.options[b]?this.options[b]:{},this.modules[b][c](this,"object"===typeof this.options[b]?this.options[b]:{},p))},state:"initializing",timer:null,animTimer:null,styles:null,elem:null,
container:null,title_container:null,text_container:null,animating:!1,timerHide:!1,init:function(){var c=this;this.modules={};b.extend(!0,this.modules,d.prototype.modules);this.styles="object"===typeof this.options.styling?this.options.styling:d.styling[this.options.styling];this.elem=b("<div />",{"class":"ui-pnotify "+this.options.addclass,css:{display:"none"},"aria-live":"assertive","aria-role":"alertdialog",mouseenter:function(a){if(c.options.mouse_reset&&"out"===c.animating){if(!c.timerHide)return;
c.cancelRemove()}c.options.hide&&c.options.mouse_reset&&c.cancelRemove()},mouseleave:function(a){c.options.hide&&c.options.mouse_reset&&"out"!==c.animating&&c.queueRemove();d.positionAll()}});"fade"===this.options.animation&&this.elem.addClass("ui-pnotify-fade-"+this.options.animate_speed);this.container=b("<div />",{"class":this.styles.container+" ui-pnotify-container "+("error"===this.options.type?this.styles.error:"info"===this.options.type?this.styles.info:"success"===this.options.type?this.styles.success:
this.styles.notice),role:"alert"}).appendTo(this.elem);""!==this.options.cornerclass&&this.container.removeClass("ui-corner-all").addClass(this.options.cornerclass);this.options.shadow&&this.container.addClass("ui-pnotify-shadow");!1!==this.options.icon&&b("<div />",{"class":"ui-pnotify-icon"}).append(b("<span />",{"class":!0===this.options.icon?"error"===this.options.type?this.styles.error_icon:"info"===this.options.type?this.styles.info_icon:"success"===this.options.type?this.styles.success_icon:
this.styles.notice_icon:this.options.icon})).prependTo(this.container);this.title_container=b("<h4 />",{"class":"ui-pnotify-title"}).appendTo(this.container);!1===this.options.title?this.title_container.hide():this.options.title_escape?this.title_container.text(this.options.title):this.title_container.html(this.options.title);this.text_container=b("<div />",{"class":"ui-pnotify-text","aria-role":"alert"}).appendTo(this.container);!1===this.options.text?this.text_container.hide():this.options.text_escape?
this.text_container.text(this.options.text):this.text_container.html(this.options.insert_brs?String(this.options.text).replace(/\n/g,"<br />"):this.options.text);"string"===typeof this.options.width&&this.elem.css("width",this.options.width);"string"===typeof this.options.min_height&&this.container.css("min-height",this.options.min_height);d.notices="top"===this.options.stack.push?b.merge([this],d.notices):b.merge(d.notices,[this]);"top"===this.options.stack.push&&this.queuePosition(!1,1);this.options.stack.animation=
!1;this.runModules("init");this.options.auto_display&&this.open();return this},update:function(c){var a=this.options;this.parseOptions(a,c);this.elem.removeClass("ui-pnotify-fade-slow ui-pnotify-fade-normal ui-pnotify-fade-fast");"fade"===this.options.animation&&this.elem.addClass("ui-pnotify-fade-"+this.options.animate_speed);this.options.cornerclass!==a.cornerclass&&this.container.removeClass("ui-corner-all "+a.cornerclass).addClass(this.options.cornerclass);this.options.shadow!==a.shadow&&(this.options.shadow?
this.container.addClass("ui-pnotify-shadow"):this.container.removeClass("ui-pnotify-shadow"));!1===this.options.addclass?this.elem.removeClass(a.addclass):this.options.addclass!==a.addclass&&this.elem.removeClass(a.addclass).addClass(this.options.addclass);!1===this.options.title?this.title_container.slideUp("fast"):this.options.title!==a.title&&(this.options.title_escape?this.title_container.text(this.options.title):this.title_container.html(this.options.title),!1===a.title&&this.title_container.slideDown(200));
!1===this.options.text?this.text_container.slideUp("fast"):this.options.text!==a.text&&(this.options.text_escape?this.text_container.text(this.options.text):this.text_container.html(this.options.insert_brs?String(this.options.text).replace(/\n/g,"<br />"):this.options.text),!1===a.text&&this.text_container.slideDown(200));this.options.type!==a.type&&this.container.removeClass(this.styles.error+" "+this.styles.notice+" "+this.styles.success+" "+this.styles.info).addClass("error"===this.options.type?
this.styles.error:"info"===this.options.type?this.styles.info:"success"===this.options.type?this.styles.success:this.styles.notice);if(this.options.icon!==a.icon||!0===this.options.icon&&this.options.type!==a.type)this.container.find("div.ui-pnotify-icon").remove(),!1!==this.options.icon&&b("<div />",{"class":"ui-pnotify-icon"}).append(b("<span />",{"class":!0===this.options.icon?"error"===this.options.type?this.styles.error_icon:"info"===this.options.type?this.styles.info_icon:"success"===this.options.type?
this.styles.success_icon:this.styles.notice_icon:this.options.icon})).prependTo(this.container);this.options.width!==a.width&&this.elem.animate({width:this.options.width});this.options.min_height!==a.min_height&&this.container.animate({minHeight:this.options.min_height});this.options.hide?a.hide||this.queueRemove():this.cancelRemove();this.queuePosition(!0);this.runModules("update",a);return this},open:function(){this.state="opening";this.runModules("beforeOpen");var c=this;this.elem.parent().length||
this.elem.appendTo(this.options.stack.context?this.options.stack.context:h);"top"!==this.options.stack.push&&this.position(!0);this.animateIn(function(){c.queuePosition(!0);c.options.hide&&c.queueRemove();c.state="open";c.runModules("afterOpen")});return this},remove:function(c){this.state="closing";this.timerHide=!!c;this.runModules("beforeClose");var a=this;this.timer&&(l.clearTimeout(this.timer),this.timer=null);this.animateOut(function(){a.state="closed";a.runModules("afterClose");a.queuePosition(!0);
a.options.remove&&a.elem.detach();a.runModules("beforeDestroy");if(a.options.destroy&&null!==d.notices){var c=b.inArray(a,d.notices);-1!==c&&d.notices.splice(c,1)}a.runModules("afterDestroy")});return this},get:function(){return this.elem},parseOptions:function(c,a){this.options=b.extend(!0,{},d.prototype.options);this.options.stack=d.prototype.options.stack;for(var p=[c,a],m,f=0;f<p.length;f++){m=p[f];if("undefined"===typeof m)break;if("object"!==typeof m)this.options.text=m;else for(var e in m)this.modules[e]?
b.extend(!0,this.options[e],m[e]):this.options[e]=m[e]}},animateIn:function(c){this.animating="in";var a=this;c=function(){a.animTimer&&clearTimeout(a.animTimer);"in"===a.animating&&(a.elem.is(":visible")?(this&&this.call(),a.animating=!1):a.animTimer=setTimeout(c,40))}.bind(c);"fade"===this.options.animation?(this.elem.one("webkitTransitionEnd mozTransitionEnd MSTransitionEnd oTransitionEnd transitionend",c).addClass("ui-pnotify-in"),this.elem.css("opacity"),this.elem.addClass("ui-pnotify-fade-in"),
this.animTimer=setTimeout(c,650)):(this.elem.addClass("ui-pnotify-in"),c())},animateOut:function(c){this.animating="out";var a=this;c=function(){a.animTimer&&clearTimeout(a.animTimer);"out"===a.animating&&("0"!=a.elem.css("opacity")&&a.elem.is(":visible")?a.animTimer=setTimeout(c,40):(a.elem.removeClass("ui-pnotify-in"),this&&this.call(),a.animating=!1))}.bind(c);"fade"===this.options.animation?(this.elem.one("webkitTransitionEnd mozTransitionEnd MSTransitionEnd oTransitionEnd transitionend",c).removeClass("ui-pnotify-fade-in"),
this.animTimer=setTimeout(c,650)):(this.elem.removeClass("ui-pnotify-in"),c())},position:function(c){var a=this.options.stack,b=this.elem;"undefined"===typeof a.context&&(a.context=h);if(a){"number"!==typeof a.nextpos1&&(a.nextpos1=a.firstpos1);"number"!==typeof a.nextpos2&&(a.nextpos2=a.firstpos2);"number"!==typeof a.addpos2&&(a.addpos2=0);var d=!b.hasClass("ui-pnotify-in");if(!d||c){a.modal&&(a.overlay?a.overlay.show():a.overlay=s(a));b.addClass("ui-pnotify-move");var f;switch(a.dir1){case "down":f=
"top";break;case "up":f="bottom";break;case "left":f="right";break;case "right":f="left"}c=parseInt(b.css(f).replace(/(?:\..*|[^0-9.])/g,""));isNaN(c)&&(c=0);"undefined"!==typeof a.firstpos1||d||(a.firstpos1=c,a.nextpos1=a.firstpos1);var e;switch(a.dir2){case "down":e="top";break;case "up":e="bottom";break;case "left":e="right";break;case "right":e="left"}c=parseInt(b.css(e).replace(/(?:\..*|[^0-9.])/g,""));isNaN(c)&&(c=0);"undefined"!==typeof a.firstpos2||d||(a.firstpos2=c,a.nextpos2=a.firstpos2);
if("down"===a.dir1&&a.nextpos1+b.height()>(a.context.is(h)?n.height():a.context.prop("scrollHeight"))||"up"===a.dir1&&a.nextpos1+b.height()>(a.context.is(h)?n.height():a.context.prop("scrollHeight"))||"left"===a.dir1&&a.nextpos1+b.width()>(a.context.is(h)?n.width():a.context.prop("scrollWidth"))||"right"===a.dir1&&a.nextpos1+b.width()>(a.context.is(h)?n.width():a.context.prop("scrollWidth")))a.nextpos1=a.firstpos1,a.nextpos2+=a.addpos2+("undefined"===typeof a.spacing2?25:a.spacing2),a.addpos2=0;"number"===
typeof a.nextpos2&&(a.animation?b.css(e,a.nextpos2+"px"):(b.removeClass("ui-pnotify-move"),b.css(e,a.nextpos2+"px"),b.css(e),b.addClass("ui-pnotify-move")));switch(a.dir2){case "down":case "up":b.outerHeight(!0)>a.addpos2&&(a.addpos2=b.height());break;case "left":case "right":b.outerWidth(!0)>a.addpos2&&(a.addpos2=b.width())}"number"===typeof a.nextpos1&&(a.animation?b.css(f,a.nextpos1+"px"):(b.removeClass("ui-pnotify-move"),b.css(f,a.nextpos1+"px"),b.css(f),b.addClass("ui-pnotify-move")));switch(a.dir1){case "down":case "up":a.nextpos1+=
b.height()+("undefined"===typeof a.spacing1?25:a.spacing1);break;case "left":case "right":a.nextpos1+=b.width()+("undefined"===typeof a.spacing1?25:a.spacing1)}}return this}},queuePosition:function(b,a){g&&clearTimeout(g);a||(a=10);g=setTimeout(function(){d.positionAll(b)},a);return this},cancelRemove:function(){this.timer&&l.clearTimeout(this.timer);this.animTimer&&l.clearTimeout(this.animTimer);"closing"===this.state&&(this.state="open",this.animating=!1,this.elem.addClass("ui-pnotify-in"),"fade"===
this.options.animation&&this.elem.addClass("ui-pnotify-fade-in"));return this},queueRemove:function(){var b=this;this.cancelRemove();this.timer=l.setTimeout(function(){b.remove(!0)},isNaN(this.options.delay)?0:this.options.delay);return this}});b.extend(d,{notices:[],reload:q,removeAll:function(){b.each(d.notices,function(){this.remove&&this.remove(!1)})},removeStack:function(c){b.each(d.notices,function(){this.remove&&this.options.stack===c&&this.remove(!1)})},positionAll:function(c){g&&clearTimeout(g);
g=null;if(d.notices&&d.notices.length)b.each(d.notices,function(){var a=this.options.stack;a&&(a.overlay&&a.overlay.hide(),a.nextpos1=a.firstpos1,a.nextpos2=a.firstpos2,a.addpos2=0,a.animation=c)}),b.each(d.notices,function(){this.position()});else{var a=d.prototype.options.stack;a&&(delete a.nextpos1,delete a.nextpos2)}},styling:{brighttheme:{container:"brighttheme",notice:"brighttheme-notice",notice_icon:"brighttheme-icon-notice",info:"brighttheme-info",info_icon:"brighttheme-icon-info",success:"brighttheme-success",
success_icon:"brighttheme-icon-success",error:"brighttheme-error",error_icon:"brighttheme-icon-error"},jqueryui:{container:"ui-widget ui-widget-content ui-corner-all",notice:"ui-state-highlight",notice_icon:"ui-icon ui-icon-info",info:"",info_icon:"ui-icon ui-icon-info",success:"ui-state-default",success_icon:"ui-icon ui-icon-circle-check",error:"ui-state-error",error_icon:"ui-icon ui-icon-alert"},bootstrap3:{container:"alert",notice:"alert-warning",notice_icon:"glyphicon glyphicon-exclamation-sign",
info:"alert-info",info_icon:"glyphicon glyphicon-info-sign",success:"alert-success",success_icon:"glyphicon glyphicon-ok-sign",error:"alert-danger",error_icon:"glyphicon glyphicon-warning-sign"}}});d.styling.fontawesome=b.extend({},d.styling.bootstrap3);b.extend(d.styling.fontawesome,{notice_icon:"fa fa-exclamation-circle",info_icon:"fa fa-info",success_icon:"fa fa-check",error_icon:"fa fa-warning"});l.document.body?r():b(r);return d};return q(k)});
(function(e,d){"function"===typeof define&&define.amd?define("pnotify.animate",["jquery","pnotify"],d):"object"===typeof exports&&"undefined"!==typeof module?module.exports=d(require("jquery"),require("./pnotify")):d(e.jQuery,e.PNotify)})("undefined"!==typeof window?window:this,function(e,d){d.prototype.options.animate={animate:!1,in_class:"",out_class:""};d.prototype.modules.animate={init:function(a,b){this.setUpAnimations(a,b);a.attention=function(b,d){a.elem.one("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend",
function(){a.elem.removeClass(b);d&&d.call(a)}).addClass("animated "+b)}},update:function(a,b,c){b.animate!=c.animate&&this.setUpAnimations(a,b)},setUpAnimations:function(a,b){if(b.animate){a.options.animation="none";a.elem.removeClass("ui-pnotify-fade-slow ui-pnotify-fade-normal ui-pnotify-fade-fast");a._animateIn||(a._animateIn=a.animateIn);a._animateOut||(a._animateOut=a.animateOut);a.animateIn=this.animateIn.bind(this);a.animateOut=this.animateOut.bind(this);var c=400;"slow"===a.options.animate_speed?
c=600:"fast"===a.options.animate_speed?c=200:0<a.options.animate_speed&&(c=a.options.animate_speed);c/=1E3;a.elem.addClass("animated").css({"-webkit-animation-duration":c+"s","-moz-animation-duration":c+"s","animation-duration":c+"s"})}else a._animateIn&&a._animateOut&&(a.animateIn=a._animateIn,delete a._animateIn,a.animateOut=a._animateOut,delete a._animateOut,a.elem.addClass("animated"))},animateIn:function(a){this.notice.animating="in";var b=this;a=function(){b.notice.elem.removeClass(b.options.in_class);
this&&this.call();b.notice.animating=!1}.bind(a);this.notice.elem.show().one("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend",a).removeClass(this.options.out_class).addClass("ui-pnotify-in").addClass(this.options.in_class)},animateOut:function(a){this.notice.animating="out";var b=this;a=function(){b.notice.elem.removeClass("ui-pnotify-in "+b.options.out_class);this&&this.call();b.notice.animating=!1}.bind(a);this.notice.elem.one("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend",
a).removeClass(this.options.in_class).addClass(this.options.out_class)}}});
(function(d,e){"function"===typeof define&&define.amd?define("pnotify.buttons",["jquery","pnotify"],e):"object"===typeof exports&&"undefined"!==typeof module?module.exports=e(require("jquery"),require("./pnotify")):e(d.jQuery,d.PNotify)})("undefined"!==typeof window?window:this,function(d,e){e.prototype.options.buttons={closer:!0,closer_hover:!0,sticker:!0,sticker_hover:!0,show_on_nonblock:!1,labels:{close:"Close",stick:"Stick",unstick:"Unstick"},classes:{closer:null,pin_up:null,pin_down:null}};e.prototype.modules.buttons=
{closer:null,sticker:null,init:function(a,b){var c=this;a.elem.on({mouseenter:function(b){!c.options.sticker||a.options.nonblock&&a.options.nonblock.nonblock&&!c.options.show_on_nonblock||c.sticker.trigger("pnotify:buttons:toggleStick").css("visibility","visible");!c.options.closer||a.options.nonblock&&a.options.nonblock.nonblock&&!c.options.show_on_nonblock||c.closer.css("visibility","visible")},mouseleave:function(a){c.options.sticker_hover&&c.sticker.css("visibility","hidden");c.options.closer_hover&&
c.closer.css("visibility","hidden")}});this.sticker=d("<div />",{"class":"ui-pnotify-sticker","aria-role":"button","aria-pressed":a.options.hide?"false":"true",tabindex:"0",title:a.options.hide?b.labels.stick:b.labels.unstick,css:{cursor:"pointer",visibility:b.sticker_hover?"hidden":"visible"},click:function(){a.options.hide=!a.options.hide;a.options.hide?a.queueRemove():a.cancelRemove();d(this).trigger("pnotify:buttons:toggleStick")}}).bind("pnotify:buttons:toggleStick",function(){var b=null===c.options.classes.pin_up?
a.styles.pin_up:c.options.classes.pin_up,e=null===c.options.classes.pin_down?a.styles.pin_down:c.options.classes.pin_down;d(this).attr("title",a.options.hide?c.options.labels.stick:c.options.labels.unstick).children().attr("class","").addClass(a.options.hide?b:e).attr("aria-pressed",a.options.hide?"false":"true")}).append("<span />").trigger("pnotify:buttons:toggleStick").prependTo(a.container);(!b.sticker||a.options.nonblock&&a.options.nonblock.nonblock&&!b.show_on_nonblock)&&this.sticker.css("display",
"none");this.closer=d("<div />",{"class":"ui-pnotify-closer","aria-role":"button",tabindex:"0",title:b.labels.close,css:{cursor:"pointer",visibility:b.closer_hover?"hidden":"visible"},click:function(){a.remove(!1);c.sticker.css("visibility","hidden");c.closer.css("visibility","hidden")}}).append(d("<span />",{"class":null===b.classes.closer?a.styles.closer:b.classes.closer})).prependTo(a.container);(!b.closer||a.options.nonblock&&a.options.nonblock.nonblock&&!b.show_on_nonblock)&&this.closer.css("display",
"none")},update:function(a,b){!b.closer||a.options.nonblock&&a.options.nonblock.nonblock&&!b.show_on_nonblock?this.closer.css("display","none"):b.closer&&this.closer.css("display","block");!b.sticker||a.options.nonblock&&a.options.nonblock.nonblock&&!b.show_on_nonblock?this.sticker.css("display","none"):b.sticker&&this.sticker.css("display","block");this.sticker.trigger("pnotify:buttons:toggleStick");this.closer.find("span").attr("class","").addClass(null===b.classes.closer?a.styles.closer:b.classes.closer);
b.sticker_hover?this.sticker.css("visibility","hidden"):a.options.nonblock&&a.options.nonblock.nonblock&&!b.show_on_nonblock||this.sticker.css("visibility","visible");b.closer_hover?this.closer.css("visibility","hidden"):a.options.nonblock&&a.options.nonblock.nonblock&&!b.show_on_nonblock||this.closer.css("visibility","visible")}};d.extend(e.styling.brighttheme,{closer:"brighttheme-icon-closer",pin_up:"brighttheme-icon-sticker",pin_down:"brighttheme-icon-sticker brighttheme-icon-stuck"});d.extend(e.styling.jqueryui,
{closer:"ui-icon ui-icon-close",pin_up:"ui-icon ui-icon-pin-w",pin_down:"ui-icon ui-icon-pin-s"});d.extend(e.styling.bootstrap2,{closer:"icon-remove",pin_up:"icon-pause",pin_down:"icon-play"});d.extend(e.styling.bootstrap3,{closer:"glyphicon glyphicon-remove",pin_up:"glyphicon glyphicon-pause",pin_down:"glyphicon glyphicon-play"});d.extend(e.styling.fontawesome,{closer:"fa fa-times",pin_up:"fa fa-pause",pin_down:"fa fa-play"})});
(function(e,c){"function"===typeof define&&define.amd?define("pnotify.confirm",["jquery","pnotify"],c):"object"===typeof exports&&"undefined"!==typeof module?module.exports=c(require("jquery"),require("./pnotify")):c(e.jQuery,e.PNotify)})("undefined"!==typeof window?window:this,function(e,c){c.prototype.options.confirm={confirm:!1,prompt:!1,prompt_class:"",prompt_default:"",prompt_multi_line:!1,align:"right",buttons:[{text:"Ok",addClass:"",promptTrigger:!0,click:function(b,a){b.remove();b.get().trigger("pnotify.confirm",
[b,a])}},{text:"Cancel",addClass:"",click:function(b){b.remove();b.get().trigger("pnotify.cancel",b)}}]};c.prototype.modules.confirm={container:null,prompt:null,init:function(b,a){this.container=e('<div class="ui-pnotify-action-bar" style="margin-top:5px;clear:both;" />').css("text-align",a.align).appendTo(b.container);a.confirm||a.prompt?this.makeDialog(b,a):this.container.hide()},update:function(b,a){a.confirm?(this.makeDialog(b,a),this.container.show()):this.container.hide().empty()},afterOpen:function(b,
a){a.prompt&&this.prompt.focus()},makeDialog:function(b,a){var h=!1,l=this,g,d;this.container.empty();a.prompt&&(this.prompt=e("<"+(a.prompt_multi_line?'textarea rows="5"':'input type="text"')+' style="margin-bottom:5px;clear:both;" />').addClass(("undefined"===typeof b.styles.input?"":b.styles.input)+" "+("undefined"===typeof a.prompt_class?"":a.prompt_class)).val(a.prompt_default).appendTo(this.container));for(var m=a.buttons[0]&&a.buttons[0]!==c.prototype.options.confirm.buttons[0],f=0;f<a.buttons.length;f++)if(!(null===
a.buttons[f]||m&&c.prototype.options.confirm.buttons[f]&&c.prototype.options.confirm.buttons[f]===a.buttons[f])){g=a.buttons[f];h?this.container.append(" "):h=!0;d=e('<button type="button" class="ui-pnotify-action-button" />').addClass(("undefined"===typeof b.styles.btn?"":b.styles.btn)+" "+("undefined"===typeof g.addClass?"":g.addClass)).text(g.text).appendTo(this.container).on("click",function(k){return function(){"function"==typeof k.click&&k.click(b,a.prompt?l.prompt.val():null)}}(g));a.prompt&&
!a.prompt_multi_line&&g.promptTrigger&&this.prompt.keypress(function(b){return function(a){13==a.keyCode&&b.click()}}(d));b.styles.text&&d.wrapInner('<span class="'+b.styles.text+'"></span>');b.styles.btnhover&&d.hover(function(a){return function(){a.addClass(b.styles.btnhover)}}(d),function(a){return function(){a.removeClass(b.styles.btnhover)}}(d));if(b.styles.btnactive)d.on("mousedown",function(a){return function(){a.addClass(b.styles.btnactive)}}(d)).on("mouseup",function(a){return function(){a.removeClass(b.styles.btnactive)}}(d));
if(b.styles.btnfocus)d.on("focus",function(a){return function(){a.addClass(b.styles.btnfocus)}}(d)).on("blur",function(a){return function(){a.removeClass(b.styles.btnfocus)}}(d))}}};e.extend(c.styling.jqueryui,{btn:"ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only",btnhover:"ui-state-hover",btnactive:"ui-state-active",btnfocus:"ui-state-focus",input:"",text:"ui-button-text"});e.extend(c.styling.bootstrap2,{btn:"btn",input:""});e.extend(c.styling.bootstrap3,{btn:"btn btn-default",
input:"form-control"});e.extend(c.styling.fontawesome,{btn:"btn btn-default",input:"form-control"})});
(function(e,c){"function"===typeof define&&define.amd?define("pnotify.desktop",["jquery","pnotify"],c):"object"===typeof exports&&"undefined"!==typeof module?module.exports=c(require("jquery"),require("./pnotify")):c(e.jQuery,e.PNotify)})("undefined"!==typeof window?window:this,function(e,c){var d,f=function(a,b){f="Notification"in window?function(a,b){return new Notification(a,b)}:"mozNotification"in navigator?function(a,b){return navigator.mozNotification.createNotification(a,b.body,b.icon).show()}:
"webkitNotifications"in window?function(a,b){return window.webkitNotifications.createNotification(b.icon,a,b.body)}:function(a,b){return null};return f(a,b)};c.prototype.options.desktop={desktop:!1,fallback:!0,icon:null,tag:null};c.prototype.modules.desktop={tag:null,icon:null,genNotice:function(a,b){this.icon=null===b.icon?"http://sciactive.com/pnotify/includes/desktop/"+a.options.type+".png":!1===b.icon?null:b.icon;if(null===this.tag||null!==b.tag)this.tag=null===b.tag?"PNotify-"+Math.round(1E6*
Math.random()):b.tag;a.desktop=f(a.options.title,{icon:this.icon,body:b.text||a.options.text,tag:this.tag});!("close"in a.desktop)&&"cancel"in a.desktop&&(a.desktop.close=function(){a.desktop.cancel()});a.desktop.onclick=function(){a.elem.trigger("click")};a.desktop.onclose=function(){"closing"!==a.state&&"closed"!==a.state&&a.remove()}},init:function(a,b){b.desktop&&(d=c.desktop.checkPermission(),0!==d?b.fallback||(a.options.auto_display=!1):this.genNotice(a,b))},update:function(a,b,c){0!==d&&b.fallback||
!b.desktop||this.genNotice(a,b)},beforeOpen:function(a,b){0!==d&&b.fallback||!b.desktop||a.elem.css({left:"-10000px"}).removeClass("ui-pnotify-in")},afterOpen:function(a,b){0!==d&&b.fallback||!b.desktop||(a.elem.css({left:"-10000px"}).removeClass("ui-pnotify-in"),"show"in a.desktop&&a.desktop.show())},beforeClose:function(a,b){0!==d&&b.fallback||!b.desktop||a.elem.css({left:"-10000px"}).removeClass("ui-pnotify-in")},afterClose:function(a,b){0!==d&&b.fallback||!b.desktop||(a.elem.css({left:"-10000px"}).removeClass("ui-pnotify-in"),
"close"in a.desktop&&a.desktop.close())}};c.desktop={permission:function(){"undefined"!==typeof Notification&&"requestPermission"in Notification?Notification.requestPermission():"webkitNotifications"in window&&window.webkitNotifications.requestPermission()},checkPermission:function(){return"undefined"!==typeof Notification&&"permission"in Notification?"granted"===Notification.permission?0:1:"webkitNotifications"in window?0==window.webkitNotifications.checkPermission()?0:1:1}};d=c.desktop.checkPermission()});
(function(b,a){"function"===typeof define&&define.amd?define("pnotify.history",["jquery","pnotify"],a):"object"===typeof exports&&"undefined"!==typeof module?module.exports=a(require("jquery"),require("./pnotify")):a(b.jQuery,b.PNotify)})("undefined"!==typeof window?window:this,function(b,a){var c,e;b(function(){b("body").on("pnotify.history-all",function(){b.each(a.notices,function(){this.modules.history.inHistory&&(this.elem.is(":visible")?this.options.hide&&this.queueRemove():this.open&&this.open())})}).on("pnotify.history-last",
function(){var b="top"===a.prototype.options.stack.push,d=b?0:-1,c;do{c=-1===d?a.notices.slice(d):a.notices.slice(d,d+1);if(!c[0])return!1;d=b?d+1:d-1}while(!c[0].modules.history.inHistory||c[0].elem.is(":visible"));c[0].open&&c[0].open()})});a.prototype.options.history={history:!0,menu:!1,fixed:!0,maxonscreen:Infinity,labels:{redisplay:"Redisplay",all:"All",last:"Last"}};a.prototype.modules.history={inHistory:!1,init:function(a,d){a.options.destroy=!1;this.inHistory=d.history;d.menu&&"undefined"===
typeof c&&(c=b("<div />",{"class":"ui-pnotify-history-container "+a.styles.hi_menu,mouseleave:function(){c.animate({top:"-"+e+"px"},{duration:100,queue:!1})}}).append(b("<div />",{"class":"ui-pnotify-history-header",text:d.labels.redisplay})).append(b("<button />",{"class":"ui-pnotify-history-all "+a.styles.hi_btn,text:d.labels.all,mouseenter:function(){b(this).addClass(a.styles.hi_btnhov)},mouseleave:function(){b(this).removeClass(a.styles.hi_btnhov)},click:function(){b(this).trigger("pnotify.history-all");
return!1}})).append(b("<button />",{"class":"ui-pnotify-history-last "+a.styles.hi_btn,text:d.labels.last,mouseenter:function(){b(this).addClass(a.styles.hi_btnhov)},mouseleave:function(){b(this).removeClass(a.styles.hi_btnhov)},click:function(){b(this).trigger("pnotify.history-last");return!1}})).appendTo("body"),e=b("<span />",{"class":"ui-pnotify-history-pulldown "+a.styles.hi_hnd,mouseenter:function(){c.animate({top:"0"},{duration:100,queue:!1})}}).appendTo(c).offset().top+2,c.css({top:"-"+e+
"px"}),d.fixed&&c.addClass("ui-pnotify-history-fixed"))},update:function(a,b){this.inHistory=b.history;b.fixed&&c?c.addClass("ui-pnotify-history-fixed"):c&&c.removeClass("ui-pnotify-history-fixed")},beforeOpen:function(c,d){if(a.notices&&a.notices.length>d.maxonscreen){var e;e="top"!==c.options.stack.push?a.notices.slice(0,a.notices.length-d.maxonscreen):a.notices.slice(d.maxonscreen,a.notices.length);b.each(e,function(){this.remove&&this.remove()})}}};b.extend(a.styling.jqueryui,{hi_menu:"ui-state-default ui-corner-bottom",
hi_btn:"ui-state-default ui-corner-all",hi_btnhov:"ui-state-hover",hi_hnd:"ui-icon ui-icon-grip-dotted-horizontal"});b.extend(a.styling.bootstrap2,{hi_menu:"well",hi_btn:"btn",hi_btnhov:"",hi_hnd:"icon-chevron-down"});b.extend(a.styling.bootstrap3,{hi_menu:"well",hi_btn:"btn btn-default",hi_btnhov:"",hi_hnd:"glyphicon glyphicon-chevron-down"});b.extend(a.styling.fontawesome,{hi_menu:"well",hi_btn:"btn btn-default",hi_btnhov:"",hi_hnd:"fa fa-chevron-down"})});
(function(g,c){"function"===typeof define&&define.amd?define("pnotify.mobile",["jquery","pnotify"],c):"object"===typeof exports&&"undefined"!==typeof module?module.exports=c(require("jquery"),require("./pnotify")):c(g.jQuery,g.PNotify)})("undefined"!==typeof window?window:this,function(g,c){c.prototype.options.mobile={swipe_dismiss:!0,styling:!0};c.prototype.modules.mobile={swipe_dismiss:!0,init:function(a,b){var c=this,d=null,e=null,f=null;this.swipe_dismiss=b.swipe_dismiss;this.doMobileStyling(a,
b);a.elem.on({touchstart:function(b){c.swipe_dismiss&&(d=b.originalEvent.touches[0].screenX,f=a.elem.width(),a.container.css("left","0"))},touchmove:function(b){d&&c.swipe_dismiss&&(e=b.originalEvent.touches[0].screenX-d,b=(1-Math.abs(e)/f)*a.options.opacity,a.elem.css("opacity",b),a.container.css("left",e))},touchend:function(){if(d&&c.swipe_dismiss){if(40<Math.abs(e)){var b=0>e?-2*f:2*f;a.elem.animate({opacity:0},100);a.container.animate({left:b},100);a.remove()}else a.elem.animate({opacity:a.options.opacity},
100),a.container.animate({left:0},100);f=e=d=null}},touchcancel:function(){d&&c.swipe_dismiss&&(a.elem.animate({opacity:a.options.opacity},100),a.container.animate({left:0},100),f=e=d=null)}})},update:function(a,b){this.swipe_dismiss=b.swipe_dismiss;this.doMobileStyling(a,b)},doMobileStyling:function(a,b){if(b.styling)if(a.elem.addClass("ui-pnotify-mobile-able"),480>=g(window).width())a.options.stack.mobileOrigSpacing1||(a.options.stack.mobileOrigSpacing1=a.options.stack.spacing1,a.options.stack.mobileOrigSpacing2=
a.options.stack.spacing2),a.options.stack.spacing1=0,a.options.stack.spacing2=0;else{if(a.options.stack.mobileOrigSpacing1||a.options.stack.mobileOrigSpacing2)a.options.stack.spacing1=a.options.stack.mobileOrigSpacing1,delete a.options.stack.mobileOrigSpacing1,a.options.stack.spacing2=a.options.stack.mobileOrigSpacing2,delete a.options.stack.mobileOrigSpacing2}else a.elem.removeClass("ui-pnotify-mobile-able"),a.options.stack.mobileOrigSpacing1&&(a.options.stack.spacing1=a.options.stack.mobileOrigSpacing1,
delete a.options.stack.mobileOrigSpacing1),a.options.stack.mobileOrigSpacing2&&(a.options.stack.spacing2=a.options.stack.mobileOrigSpacing2,delete a.options.stack.mobileOrigSpacing2)}}});
| gpl-3.0 |
nkhare/rockstor-core | src/rockstor/storageadmin/static/storageadmin/js/views/add_afp_share.js | 3831 | /*
*
* @licstart The following is the entire license notice for the
* JavaScript code in this page.
*
* Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
* This file is part of RockStor.
*
* RockStor is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* RockStor 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/>.
*
* @licend The above is the entire license notice
* for the JavaScript code in this page.
*
*/
AddAFPShareView = RockstorLayoutView.extend({
events: {
"click #cancel": "cancel"
},
initialize: function() {
this.constructor.__super__.initialize.apply(this, arguments);
this.template = window.JST.afp_add_afp_share;
this.shares = new ShareCollection();
// dont paginate shares for now
this.shares.pageSize = RockStorGlobals.maxPageSize;
this.dependencies.push(this.shares);
this.afpShareId = this.options.afpShareId;
this.afpShares = new AFPCollection({afpShareId: this.afpShareId});
this.dependencies.push(this.afpShares);
this.yes_no_choices = [
{name: 'yes', value: 'yes'},
{name: 'no', value: 'no'},
];
this.time_machine_choices = this.yes_no_choices;
},
render: function() {
this.fetch(this.renderAFPForm, this);
return this;
},
renderAFPForm: function() {
var _this = this;
this.freeShares = this.shares.reject(function(share) {
s = this.afpShares.find(function(afpShare) {
return (afpShare.get('share') == share.get('name'));
});
return !_.isUndefined(s);
}, this);
if(this.afpShareId != null){
this.aShares = this.afpShares.get(this.afpShareId);
}else{
this.aShares = null;
}
$(this.el).html(this.template({
shares: this.freeShares,
afpShare: this.aShares,
afpShareId: this.afpShareId,
time_machine_choices: this.time_machine_choices,
}));
$('#add-afp-share-form :input').tooltip({
html: true,
placement: 'right'
});
this.$('#shares').chosen();
$.validator.setDefaults({ ignore: ":hidden:not(select)" });
$('#add-afp-share-form').validate({
onfocusout: false,
onkeyup: false,
rules: {
shares: "required" ,
},
submitHandler: function() {
var button = $('#create-afp-export');
if (buttonDisabled(button)) return false;
disableButton(button);
var submitmethod = 'POST';
var posturl = '/api/netatalk';
if(_this.afpShareId != null){
submitmethod = 'PUT';
posturl += '/'+_this.afpShareId;
}
$.ajax({
url: posturl,
type: submitmethod,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(_this.$('#add-afp-share-form').getJSON()),
success: function() {
enableButton(button);
_this.$('#add-afp-share-form :input').tooltip('hide');
app_router.navigate('afp', {trigger: true});
},
error: function(xhr, status, error) {
enableButton(button);
}
});
return false;
}
});
},
cancel: function(event) {
event.preventDefault();
this.$('#add-afp-share-form :input').tooltip('hide');
app_router.navigate('afp', {trigger: true});
}
});
| gpl-3.0 |
arraydev/snap-engine | snap-gpf/src/test/java/org/esa/snap/gpf/operators/standard/reproject/ReprojectionOpTest.java | 8543 | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.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/
*/
package org.esa.snap.gpf.operators.standard.reproject;
import org.esa.snap.framework.datamodel.Band;
import org.esa.snap.framework.datamodel.GeoPos;
import org.esa.snap.framework.datamodel.PinDescriptor;
import org.esa.snap.framework.datamodel.PixelPos;
import org.esa.snap.framework.datamodel.Placemark;
import org.esa.snap.framework.datamodel.PlacemarkDescriptor;
import org.esa.snap.framework.datamodel.Product;
import org.esa.snap.framework.datamodel.TiePointGrid;
import org.junit.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
public class ReprojectionOpTest extends AbstractReprojectionOpTest {
@Test
public void testGeoLatLon() throws IOException {
parameterMap.put("crs", WGS84_CODE);
final Product targetPoduct = createReprojectedProduct();
assertNotNull(targetPoduct);
// because source is rectangular the size of source is preserved
assertEquals(50, targetPoduct.getSceneRasterWidth());
assertEquals(50, targetPoduct.getSceneRasterHeight());
assertNotNull(targetPoduct.getGeoCoding());
assertPixelValue(targetPoduct.getBand(FLOAT_BAND_NAME), 23.5f, 13.5f, (double) 299, EPS);
}
@Test
public void testUTMWithWktText() throws IOException {
parameterMap.put("crs", UTM33N_WKT);
final Product targetPoduct = createReprojectedProduct();
assertNotNull(targetPoduct);
assertPixelValue(targetPoduct.getBand(FLOAT_BAND_NAME), 23.5f, 13.5f, (double) 299, EPS);
}
@Test
public void testWithWktFile() throws IOException {
parameterMap.put("wktFile", wktFile);
final Product targetPoduct = createReprojectedProduct();
assertNotNull(targetPoduct);
assertPixelValue(targetPoduct.getBand(FLOAT_BAND_NAME), 23.5f, 13.5f, (double) 299, EPS);
}
@Test
public void testWithCollocationProduct() {
Map<String, Product> productMap = new HashMap<String, Product>(5);
productMap.put("source", sourceProduct);
parameterMap.put("crs", "AUTO:42002");
final Product collocationProduct = createReprojectedProduct(productMap);
productMap = new HashMap<String, Product>(5);
productMap.put("source", sourceProduct);
productMap.put("collocateWith", collocationProduct);
parameterMap.remove("crs");
final Product targetProduct = createReprojectedProduct(productMap);
assertNotNull(targetProduct);
assertTrue(targetProduct.isCompatibleProduct(collocationProduct, 1.0e-6f));
}
@Test
public void testUTM() throws IOException {
parameterMap.put("crs", UTM33N_CODE);
final Product targetPoduct = createReprojectedProduct();
assertNotNull(targetPoduct);
assertPixelValue(targetPoduct.getBand(FLOAT_BAND_NAME), 23.5f, 13.5f, (double) 299, EPS);
}
@Test
public void testStartAndEndTime() throws Exception {
parameterMap.put("crs", UTM33N_CODE);
final Product targetPoduct = createReprojectedProduct();
assertNotNull(targetPoduct.getStartTime());
assertNotNull(targetPoduct.getEndTime());
String meanTime = "02-JAN-2008 10:30:30.000000";
assertEquals(meanTime, targetPoduct.getStartTime().format());
assertEquals(meanTime, targetPoduct.getEndTime().format());
}
@Test
public void testUTM_Bilinear() throws IOException {
parameterMap.put("crs", UTM33N_CODE);
parameterMap.put("resampling", "Bilinear");
final Product targetPoduct = createReprojectedProduct();
assertNotNull(targetPoduct);
assertNotNull(targetPoduct.getGeoCoding());
// 299, 312
// 322, 336
// interpolated = 317.25 for pixel (24, 14)
assertPixelValue(targetPoduct.getBand(FLOAT_BAND_NAME), 24.0f, 14.0f, 317.25, 1.0e-2);
}
@Test
public void testSpecifyingTargetDimension() throws IOException {
final int width = 200;
final int height = 300;
parameterMap.put("crs", WGS84_CODE);
parameterMap.put("width", width);
parameterMap.put("height", height);
final Product targetPoduct = createReprojectedProduct();
assertNotNull(targetPoduct);
assertEquals(width, targetPoduct.getSceneRasterWidth());
assertEquals(height, targetPoduct.getSceneRasterHeight());
assertPixelValue(targetPoduct.getBand(FLOAT_BAND_NAME), 23.5f, 13.5f, (double) 299, EPS);
}
@Test
public void testSpecifyingPixelSize() throws IOException {
final double sizeX = 5; // degree
final double sizeY = 10;// degree
parameterMap.put("crs", WGS84_CODE);
parameterMap.put("pixelSizeX", sizeX);
parameterMap.put("pixelSizeY", sizeY);
final Product targetPoduct = createReprojectedProduct();
assertNotNull(targetPoduct);
assertEquals(5, targetPoduct.getSceneRasterWidth());
assertEquals(3, targetPoduct.getSceneRasterHeight());
}
@Test
public void testSpecifyingReferencing() throws IOException {
parameterMap.put("crs", WGS84_CODE);
parameterMap.put("referencePixelX", 0.5);
parameterMap.put("referencePixelY", 0.5);
parameterMap.put("easting", 9.0); // just move it 3° degrees eastward
parameterMap.put("northing", 52.0); // just move it 2° degrees up
parameterMap.put("orientation", 0.0);
final Product targetPoduct = createReprojectedProduct();
assertNotNull(targetPoduct);
final GeoPos geoPos = targetPoduct.getGeoCoding().getGeoPos(new PixelPos(0.5f, 0.5f), null);
assertEquals(new GeoPos(52.0f, 9.0f), geoPos);
assertPixelValue(targetPoduct.getBand(FLOAT_BAND_NAME), 23.5f, 13.5f, (double) 299, EPS);
}
@Test
public void testIncludeTiePointGrids() throws Exception {
parameterMap.put("crs", WGS84_CODE);
Product targetPoduct = createReprojectedProduct();
TiePointGrid[] tiePointGrids = targetPoduct.getTiePointGrids();
assertNotNull(tiePointGrids);
assertEquals(0, tiePointGrids.length);
Band latGrid = targetPoduct.getBand("latGrid");
assertNotNull(latGrid);
parameterMap.put("includeTiePointGrids", false);
targetPoduct = createReprojectedProduct();
tiePointGrids = targetPoduct.getTiePointGrids();
assertNotNull(tiePointGrids);
assertEquals(0, tiePointGrids.length);
latGrid = targetPoduct.getBand("latGrid");
assertNull(latGrid);
}
@Test
public void testCopyPlacemarkGroups() throws IOException {
final PlacemarkDescriptor pinDescriptor = PinDescriptor.getInstance();
final Placemark pin = Placemark.createPointPlacemark(pinDescriptor, "P1", "", "", new PixelPos(1.5f, 1.5f), null, sourceProduct.getGeoCoding());
final Placemark gcp = Placemark.createPointPlacemark(pinDescriptor, "G1", "", "", new PixelPos(2.5f, 2.5f), null, sourceProduct.getGeoCoding());
sourceProduct.getPinGroup().add(pin);
sourceProduct.getGcpGroup().add(gcp);
parameterMap.put("crs", WGS84_CODE);
Product targetProduct = createReprojectedProduct();
assertEquals(1, targetProduct.getPinGroup().getNodeCount());
assertEquals(1, targetProduct.getGcpGroup().getNodeCount());
final Placemark pin2 = targetProduct.getPinGroup().get(0);
final Placemark gcp2 = targetProduct.getGcpGroup().get(0);
assertEquals("P1", pin2.getName());
assertEquals("G1", gcp2.getName());
assertEquals(pin.getGeoPos(), pin2.getGeoPos());
assertEquals(gcp.getGeoPos(), gcp2.getGeoPos());
assertNotNull(pin2.getPixelPos());
assertNotNull(gcp2.getPixelPos());
}
}
| gpl-3.0 |
cmjatai/cmj | sapl/base/migrations/0011_auto_20171121_0958.py | 655 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-11-21 11:58
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('base', '0010_remove_appconfig_painel_aberto'),
]
operations = [
migrations.AlterModelOptions(
name='appconfig',
options={'ordering': ('-id',), 'permissions': (('menu_sistemas', 'Renderizar Menu Sistemas'), ('view_tabelas_auxiliares', 'Visualizar Tabelas Auxiliares')), 'verbose_name': 'Configurações da Aplicação', 'verbose_name_plural': 'Configurações da Aplicação'},
),
]
| gpl-3.0 |
mbauskar/erpnext | erpnext/buying/doctype/request_for_quotation/request_for_quotation.js | 8841 | // Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
{% include 'erpnext/public/js/controllers/buying.js' %};
cur_frm.add_fetch('contact', 'email_id', 'email_id')
frappe.ui.form.on("Request for Quotation",{
setup: function(frm) {
frm.custom_make_buttons = {
'Supplier Quotation': 'Supplier Quotation'
}
frm.fields_dict["suppliers"].grid.get_field("contact").get_query = function(doc, cdt, cdn) {
let d = locals[cdt][cdn];
return {
query: "erpnext.buying.doctype.request_for_quotation.request_for_quotation.get_supplier_contacts",
filters: {'supplier': d.supplier}
}
}
},
onload: function(frm) {
frm.add_fetch('standard_reply', 'response', 'message_for_supplier');
if(!frm.doc.message_for_supplier) {
frm.set_value("message_for_supplier", __("Please supply the specified items at the best possible rates"))
}
},
refresh: function(frm, cdt, cdn) {
if (frm.doc.docstatus === 1) {
frm.add_custom_button(__("Make"),
function(){ frm.trigger("make_suppplier_quotation") }, __("Supplier Quotation"));
frm.add_custom_button(__("View"),
function(){ frappe.set_route('List', 'Supplier Quotation',
{'request_for_quotation': frm.doc.name}) }, __("Supplier Quotation"));
frm.add_custom_button(__("Send Supplier Emails"), function() {
frappe.call({
method: 'erpnext.buying.doctype.request_for_quotation.request_for_quotation.send_supplier_emails',
freeze: true,
args: {
rfq_name: frm.doc.name
},
callback: function(r){
frm.reload_doc();
}
});
});
}
},
get_suppliers_button: function (frm) {
var doc = frm.doc;
var dialog = new frappe.ui.Dialog({
title: __("Get Suppliers"),
fields: [
{ "fieldtype": "Select", "label": __("Get Suppliers By"),
"fieldname": "search_type",
"options": "Tag\nSupplier Type", "reqd": 1 },
{ "fieldtype": "Link", "label": __("Supplier Type"),
"fieldname": "supplier_type",
"options": "Supplier Type", "reqd": 0,
"depends_on": "eval:doc.search_type == 'Supplier Type'"},
{ "fieldtype": "Data", "label": __("Tag"),
"fieldname": "tag", "reqd": 0,
"depends_on": "eval:doc.search_type == 'Tag'" },
{ "fieldtype": "Button", "label": __("Add All Suppliers"),
"fieldname": "add_suppliers", "cssClass": "btn-primary"},
]
});
dialog.fields_dict.add_suppliers.$input.click(function() {
var args = dialog.get_values();
if(!args) return;
dialog.hide();
//Remove blanks
for (var j = 0; j < frm.doc.suppliers.length; j++) {
if(!frm.doc.suppliers[j].hasOwnProperty("supplier")) {
frm.get_field("suppliers").grid.grid_rows[j].remove();
}
}
function load_suppliers(r) {
if(r.message) {
for (var i = 0; i < r.message.length; i++) {
var exists = false;
if (r.message[i].constructor === Array){
var supplier = r.message[i][0];
} else {
var supplier = r.message[i].name;
}
for (var j = 0; j < doc.suppliers.length;j++) {
if (supplier === doc.suppliers[j].supplier) {
exists = true;
}
}
if(!exists) {
var d = frm.add_child('suppliers');
d.supplier = supplier;
frm.script_manager.trigger("supplier", d.doctype, d.name);
}
}
}
frm.refresh_field("suppliers");
}
if (args.search_type === "Tag" && args.tag) {
return frappe.call({
type: "GET",
method: "frappe.desk.tags.get_tagged_docs",
args: {
"doctype": "Supplier",
"tag": args.tag
},
callback: load_suppliers
});
} else if (args.supplier_type) {
return frappe.call({
method: "frappe.client.get_list",
args: {
doctype: "Supplier",
order_by: "name",
fields: ["name"],
filters: [["Supplier", "supplier_type", "=", args.supplier_type]]
},
callback: load_suppliers
});
}
});
dialog.show();
},
make_suppplier_quotation: function(frm) {
var doc = frm.doc;
var dialog = new frappe.ui.Dialog({
title: __("For Supplier"),
fields: [
{ "fieldtype": "Select", "label": __("Supplier"),
"fieldname": "supplier",
"options": doc.suppliers.map(d => d.supplier),
"reqd": 1 },
{ "fieldtype": "Button", "label": __("Make Supplier Quotation"),
"fieldname": "make_supplier_quotation", "cssClass": "btn-primary" },
]
});
dialog.fields_dict.make_supplier_quotation.$input.click(function() {
var args = dialog.get_values();
if(!args) return;
dialog.hide();
return frappe.call({
type: "GET",
method: "erpnext.buying.doctype.request_for_quotation.request_for_quotation.make_supplier_quotation",
args: {
"source_name": doc.name,
"for_supplier": args.supplier
},
freeze: true,
callback: function(r) {
if(!r.exc) {
var doc = frappe.model.sync(r.message);
frappe.set_route("Form", r.message.doctype, r.message.name);
}
}
});
});
dialog.show()
}
})
frappe.ui.form.on("Request for Quotation Supplier",{
supplier: function(frm, cdt, cdn) {
var d = locals[cdt][cdn]
frappe.call({
method:"erpnext.accounts.party.get_party_details",
args:{
party: d.supplier,
party_type: 'Supplier'
},
callback: function(r){
if(r.message){
frappe.model.set_value(cdt, cdn, 'contact', r.message.contact_person)
frappe.model.set_value(cdt, cdn, 'email_id', r.message.contact_email)
}
}
})
},
download_pdf: function(frm, cdt, cdn) {
var child = locals[cdt][cdn]
var w = window.open(
frappe.urllib.get_full_url("/api/method/erpnext.buying.doctype.request_for_quotation.request_for_quotation.get_pdf?"
+"doctype="+encodeURIComponent(frm.doc.doctype)
+"&name="+encodeURIComponent(frm.doc.name)
+"&supplier_idx="+encodeURIComponent(child.idx)
+"&no_letterhead=0"));
if(!w) {
frappe.msgprint(__("Please enable pop-ups")); return;
}
},
no_quote: function(frm, cdt, cdn) {
var d = locals[cdt][cdn];
if (d.no_quote) {
if (d.quote_status != __('Received')) {
frappe.model.set_value(cdt, cdn, 'quote_status', 'No Quote');
} else {
frappe.msgprint(__("Cannot set a received RFQ to No Quote"));
frappe.model.set_value(cdt, cdn, 'no_quote', 0);
}
} else {
d.quote_status = __('Pending');
frm.call({
method:"update_rfq_supplier_status",
doc: frm.doc,
args: {
sup_name: d.supplier
},
callback: function(r) {
frm.refresh_field("suppliers");
}
});
}
}
})
erpnext.buying.RequestforQuotationController = erpnext.buying.BuyingController.extend({
refresh: function() {
var me = this;
this._super();
if (this.frm.doc.docstatus===0) {
this.frm.add_custom_button(__('Material Request'),
function() {
erpnext.utils.map_current_doc({
method: "erpnext.stock.doctype.material_request.material_request.make_request_for_quotation",
source_doctype: "Material Request",
target: me.frm,
setters: {
company: me.frm.doc.company
},
get_query_filters: {
material_request_type: "Purchase",
docstatus: 1,
status: ["!=", "Stopped"],
per_ordered: ["<", 99.99]
}
})
}, __("Get items from"));
// Get items from open Material Requests based on supplier
this.frm.add_custom_button(__('Possible Supplier'), function() {
// Create a dialog window for the user to pick their supplier
var d = new frappe.ui.Dialog({
title: __('Select Possible Supplier'),
fields: [
{fieldname: 'supplier', fieldtype:'Link', options:'Supplier', label:'Supplier', reqd:1},
{fieldname: 'ok_button', fieldtype:'Button', label:'Get Items from Material Requests'},
]
});
// On the user clicking the ok button
d.fields_dict.ok_button.input.onclick = function() {
var btn = d.fields_dict.ok_button.input;
var v = d.get_values();
if(v) {
$(btn).set_working();
erpnext.utils.map_current_doc({
method: "erpnext.buying.doctype.request_for_quotation.request_for_quotation.get_item_from_material_requests_based_on_supplier",
source_name: v.supplier,
target: me.frm,
setters: {
company: me.frm.doc.company
},
get_query_filters: {
material_request_type: "Purchase",
docstatus: 1,
status: ["!=", "Stopped"],
per_ordered: ["<", 99.99]
}
});
$(btn).done_working();
d.hide();
}
}
d.show();
}, __("Get items from"));
}
},
calculate_taxes_and_totals: function() {
return;
},
tc_name: function() {
this.get_terms();
}
});
// for backward compatibility: combine new and previous states
$.extend(cur_frm.cscript, new erpnext.buying.RequestforQuotationController({frm: cur_frm}));
| gpl-3.0 |
betterangels/buoy | vendor/pear-pear.horde.org/Horde_Imap_Client/Horde/Imap/Client/Translation.php | 1078 | <?php
/**
* Copyright 2010-2016 Horde LLC (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you
* did not receive this file, see http://www.horde.org/licenses/lgpl21.
*
* @category Horde
* @copyright 2010-2016 Horde LLC
* @license http://www.horde.org/licenses/lgpl21 LGPL
* @package Imap_Client
*/
/**
* Translation wrapper class for Horde_Imap_Client.
*
* @author Michael Slusarz <slusarz@horde.org>
* @category Horde
* @copyright 2010-2016 Horde LLC
* @license http://www.horde.org/licenses/lgpl21 LGPL
* @package Imap_Client
*/
class Horde_Imap_Client_Translation extends Horde_Translation_Autodetect
{
/**
* The translation domain
*
* @var string
*/
protected static $_domain = 'Horde_Imap_Client';
/**
* The absolute PEAR path to the translations for the default gettext handler.
*
* @var string
*/
protected static $_pearDirectory = '/srv/www/wordpress-default/wp-content/plugins/buoy/vendor/pear-pear.horde.org/Horde_Imap_Client/data';
}
| gpl-3.0 |
OpenCFD/OpenFOAM-1.7.x | src/turbulenceModels/incompressible/LES/Smagorinsky2/Smagorinsky2.H | 3490 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd.
\\/ 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::incompressible::LESModels::Smagorinsky2
Description
The Isochoric Smagorinsky Model for incompressible flows
Algebraic eddy viscosity SGS model founded on the assumption that
local equilibrium prevails, hence
@verbatim
B = 2/3*k*I - 2*nuSgs*dev(D) - 2*cD2*delta*(D.dev(D));
Beff = 2/3*k*I - 2*nuEff*dev(D) - 2*cD2*delta*(D.dev(D));
where
D = symm(grad(U));
k = cI*delta^2*||D||^2
nuSgs = ck*sqrt(k)*delta
nuEff = nuSgs + nu
@endverbatim
SourceFiles
Smagorinsky2.C
\*---------------------------------------------------------------------------*/
#ifndef Smagorinsky2_H
#define Smagorinsky2_H
#include "Smagorinsky.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace incompressible
{
namespace LESModels
{
/*---------------------------------------------------------------------------*\
Class Smagorinsky2 Declaration
\*---------------------------------------------------------------------------*/
class Smagorinsky2
:
public Smagorinsky
{
// Private data
dimensionedScalar cD2_;
// Private Member Functions
// Disallow default bitwise copy construct and assignment
Smagorinsky2(const Smagorinsky2&);
Smagorinsky2& operator=(const Smagorinsky2&);
public:
//- Runtime type information
TypeName("Smagorinsky2");
// Constructors
//- Construct from components
Smagorinsky2
(
const volVectorField& U,
const surfaceScalarField& phi,
transportModel& transport
);
//- Destructor
virtual ~Smagorinsky2()
{}
// Member Functions
//- Return B.
virtual tmp<volSymmTensorField> B() const;
//- Returns div(B).
// This is the additional term due to the filtering of the NSE.
virtual tmp<fvVectorMatrix> divDevBeff(volVectorField& U) const;
//- Read LESProperties dictionary
virtual bool read();
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace LESModels
} // End namespace incompressible
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| gpl-3.0 |
lospooky/gpforsim | GP4Sim.Trading/Solutions/TradingSolution.cs | 3617 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
using HeuristicLab.Data;
using HeuristicLab.Optimization;
using HeuristicLab.Common;
using System.Reflection;
using GP4Sim.SimulationFramework.Solutions;
using GP4Sim.Trading.Interfaces;
using GP4Sim.Data;
using GP4Sim.SymbolicTrees;
using HeuristicLab.Problems.DataAnalysis;
namespace GP4Sim.Trading.Solutions
{
[StorableClass]
public sealed class TradingSolution : SimulationSolution<ITradingProblemData, ITradingModel>, ITradingSolution
{
#region Time Ranges
private const string TrainingPeriodName = "Training Period";
private const string TestPeriodName = "Test Period";
public DateTimeRange TrainingPeriod
{
get { return ((DateTimeRange)this[TrainingPeriodName].Value); }
}
public DateTimeRange TestPeriod
{
get { return ((DateTimeRange)this[TestPeriodName].Value); }
}
#endregion
#region Constructors
[StorableConstructor]
private TradingSolution(bool deserializing) : base(deserializing) { }
private TradingSolution(TradingSolution original, Cloner cloner)
: base(original, cloner)
{
}
public TradingSolution(ITradingModel model, ITradingProblemData problemData)
: base(model, problemData)
{
string tpVariable = problemData.TimePointVariable;
Add(new Result(TrainingPeriodName, "", new DateTimeRange(problemData.Dataset.GetDateTimeValue(tpVariable, problemData.TrainingPartition.Start), problemData.Dataset.GetDateTimeValue(tpVariable, problemData.TrainingPartition.End))));
Add(new Result(TestPeriodName, "", new DateTimeRange(problemData.Dataset.GetDateTimeValue(tpVariable, problemData.TestPartition.Start), problemData.Dataset.GetDateTimeValue(tpVariable, problemData.TestPartition.End - 1))));
this.name = FitnessName();
}
[StorableHook(HookType.AfterDeserialization)]
private void AfterDeserialization()
{
if ((Model.Interpreter as SymbolicAbstractTreeInterpreter).StatesVarMap == null)
(Model.Interpreter as SymbolicAbstractTreeInterpreter).UpdateInputsMap(ProblemData.AllowedInputVariables, ProblemData.AllowedInputStates);
}
public override IDeepCloneable Clone(Cloner cloner)
{
return new TradingSolution(this, cloner);
}
#endregion
protected override void RecalculateResults()
{
base.RecalculateResults();
}
private static string CleanPriceVariableName(string vName)
{
if (vName.Contains('_'))
return vName.Split(new char[] { '_' }, 1)[0];
else
return vName;
}
public string DescriptiveName
{
get
{
string pv = CleanPriceVariableName(ProblemData.PriceVariable);
DateTime start = ProblemData.Dataset.GetDateTimeValue(ProblemData.TimePointVariable, ProblemData.TrainingPartition.Start);
DateTime end = ProblemData.Dataset.GetDateTimeValue(ProblemData.TimePointVariable, ProblemData.TrainingPartition.End);
return pv + "_" + start.ToString("MM-dd") + "_" + end.ToString("MM-dd");
}
}
private string FitnessName()
{
return "Fitness: " + this.TrainingFitnessScore.ToString("F5");
}
}
}
| gpl-3.0 |
kotsios5/openclassifieds2 | oc/vendor/Instagram-API/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.php | 5682 | <?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
/**
* @author Andreas Möller <am@localheinz.com>
*/
final class NativeFunctionInvocationFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
/**
* {@inheritdoc}
*/
public function getDefinition()
{
return new FixerDefinition(
'Add leading `\` before function invocation of internal function to speed up resolving.',
[
new CodeSample(
'<?php
function baz($options)
{
if (!array_key_exists("foo", $options)) {
throw new \InvalidArgumentException();
}
return json_encode($options);
}
'
),
new CodeSample(
'<?php
function baz($options)
{
if (!array_key_exists("foo", $options)) {
throw new \InvalidArgumentException();
}
return json_encode($options);
}
',
[
'exclude' => [
'json_encode',
],
]
),
],
null,
'Risky when any of the functions are overridden.'
);
}
/**
* {@inheritdoc}
*/
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(T_STRING);
}
/**
* {@inheritdoc}
*/
public function isRisky()
{
return true;
}
/**
* {@inheritdoc}
*/
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
$functionNames = $this->getFunctionNames();
$indexes = [];
for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) {
$token = $tokens[$index];
$tokenContent = $token->getContent();
// test if we are at a function call
if (!$token->isGivenKind(T_STRING)) {
continue;
}
$next = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$next]->equals('(')) {
continue;
}
$functionNamePrefix = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$functionNamePrefix]->isGivenKind([T_DOUBLE_COLON, T_NEW, T_OBJECT_OPERATOR, T_FUNCTION])) {
continue;
}
if ($tokens[$functionNamePrefix]->isGivenKind(T_NS_SEPARATOR)) {
// skip if the call is to a constructor or to a function in a namespace other than the default
$prev = $tokens->getPrevMeaningfulToken($functionNamePrefix);
if ($tokens[$prev]->isGivenKind([T_STRING, T_NEW])) {
continue;
}
}
$lowerFunctionName = \strtolower($tokenContent);
if (!\in_array($lowerFunctionName, $functionNames, true)) {
continue;
}
// do not bother if previous token is already namespace separator
if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_NS_SEPARATOR)) {
continue;
}
$indexes[] = $index;
}
$indexes = \array_reverse($indexes);
foreach ($indexes as $index) {
$tokens->insertAt($index, new Token([T_NS_SEPARATOR, '\\']));
}
}
/**
* {@inheritdoc}
*/
protected function createConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('exclude', 'List of functions to ignore.'))
->setAllowedTypes(['array'])
->setAllowedValues([static function ($value) {
foreach ($value as $functionName) {
if (!\is_string($functionName) || '' === \trim($functionName) || \trim($functionName) !== $functionName) {
throw new InvalidOptionsException(\sprintf(
'Each element must be a non-empty, trimmed string, got "%s" instead.',
\is_object($functionName) ? \get_class($functionName) : \gettype($functionName)
));
}
}
return true;
}])
->setDefault([])
->getOption(),
]);
}
/**
* @return string[]
*/
private function getFunctionNames()
{
$definedFunctions = \get_defined_functions();
return \array_diff(
$this->normalizeFunctionNames($definedFunctions['internal']),
\array_unique($this->normalizeFunctionNames($this->configuration['exclude']))
);
}
/**
* @param string[] $functionNames
*
* @return string[]
*/
private function normalizeFunctionNames(array $functionNames)
{
return \array_map(static function ($functionName) {
return \strtolower($functionName);
}, $functionNames);
}
}
| gpl-3.0 |
numsol/HybGe-Flow3D | documentation/html/search/functions_3.js | 136 | var searchData=
[
['geo_5fsanity',['geo_sanity',['../namespacehgf_1_1mesh.html#aa322d02e2545e3574cc6ade2d4c4a38b',1,'hgf::mesh']]]
];
| gpl-3.0 |
kamcpp/edusys | new-dept-website/src/src/main/java/com/mftvanak/web/portal/web/kaptcha/impl/DefaultWordRenderer.java | 2376 | package com.mftvanak.web.portal.web.kaptcha.impl;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.image.BufferedImage;
import java.util.Random;
import com.mftvanak.web.portal.web.kaptcha.KaptchaCommon;
import com.mftvanak.web.portal.web.kaptcha.WordRenderer;
public class DefaultWordRenderer implements WordRenderer {
@Override
public BufferedImage renderWord(String word, int width, int height) {
int fontSize = KaptchaCommon.getConfigurationProvider()
.getTextProducerFontSize();
Font[] fonts = KaptchaCommon.getConfigurationProvider()
.getTextProducerFonts(fontSize);
Color color = KaptchaCommon.getConfigurationProvider()
.getTextProducerFontColor();
int charSpace = KaptchaCommon.getConfigurationProvider()
.getTextProducerCharSpace();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2D = image.createGraphics();
g2D.setColor(color);
RenderingHints hints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
hints.add(new RenderingHints(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY));
g2D.setRenderingHints(hints);
FontRenderContext frc = g2D.getFontRenderContext();
Random random = new Random();
int startPosY = (height - fontSize) / 5 + fontSize;
char[] wordChars = word.toCharArray();
Font[] chosenFonts = new Font[wordChars.length];
int[] charWidths = new int[wordChars.length];
int widthNeeded = 0;
for (int i = 0; i < wordChars.length; i++) {
chosenFonts[i] = fonts[random.nextInt(fonts.length)];
char[] charToDraw = new char[] { wordChars[i] };
GlyphVector gv = chosenFonts[i].createGlyphVector(frc, charToDraw);
charWidths[i] = (int) gv.getVisualBounds().getWidth();
if (i > 0) {
widthNeeded = widthNeeded + 2;
}
widthNeeded = widthNeeded + charWidths[i];
}
int startPosX = (width - widthNeeded) / 2;
for (int i = 0; i < wordChars.length; i++) {
g2D.setFont(chosenFonts[i]);
char[] charToDraw = new char[] { wordChars[i] };
g2D.drawChars(charToDraw, 0, charToDraw.length, startPosX,
startPosY);
startPosX = startPosX + (int) charWidths[i] + charSpace;
}
return image;
}
}
| gpl-3.0 |
m5w/matxin-lineariser | tg/src/morph2/Distance.java | 1549 | /**
*
*/
package morph2;
/**
* @author Dr. Bernd Bohnet, 14.03.2010
*
*
*/
public class Distance {
//****************************
// Get minimum of three values
//****************************
static private int Minimum (int a, int b, int c) {
int mi;
mi = a;
if (b < mi) {
mi = b;
}
if (c < mi) {
mi = c;
}
return mi;
}
//*****************************
// Compute Levenshtein distance
//*****************************
static public int LD (String s, String t) {
int d[][]; // matrix
int n; // length of s
int m; // length of t
int i; // iterates through s
int j; // iterates through t
char s_i; // ith character of s
char t_j; // jth character of t
int cost; // cost
// Step 1
n = s.length ();
m = t.length ();
if (n == 0) {
return m;
}
if (m == 0) {
return n;
}
d = new int[n+1][m+1];
// Step 2
for (i = 0; i <= n; i++) {
d[i][0] = i;
}
for (j = 0; j <= m; j++) {
d[0][j] = j;
}
// Step 3
for (i = 1; i <= n; i++) {
s_i = s.charAt (i - 1);
// Step 4
for (j = 1; j <= m; j++) {
t_j = t.charAt (j - 1);
// Step 5
if (s_i == t_j) {
cost = 0;
}
else {
cost = 1;
}
// Step 6
d[i][j] = Minimum (d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + cost);
}
}
// Step 7
return d[n][m];
}
}
| gpl-3.0 |
sethryder/modpackindex | app/views/twitch/channel.blade.php | 2139 | @extends('layouts.base')
@section('content')
<script src="//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function () {
window.onPlayerEvent = function (data) {
data.forEach(function (event) {
if (event.event == "playerInit") {
var player = $("#twitch_embed_player")[0];
player.playVideo();
player.mute();
}
});
}
swfobject.embedSWF("//www-cdn.jtvnw.net/swflibs/TwitchPlayer.swf", "twitch_embed_player", "1920", "1080", "11", null,
{
"eventsCallback": "onPlayerEvent",
"embed": 1,
"channel": "{{ $channel->display_name }}",
"auto_play": "true"
},
{
"allowScriptAccess": "always",
"allowFullScreen": "true"
});
});
</script>
<div class="content">
<div class="container">
<div class="portlet">
<h3 class="portlet-title">
<u>{{ $channel->display_name }}</u>
</h3>
<div style="position: relative; bottom: 15px;"><h5>
Modpack: {{{ $modpack_name }}}
</h5>
<div class="portlet-body" style="text-align:center;">
<h3>{{{ $channel->status }}}</h3>
<div class="video-container">
<div id="twitch_embed_player"></div>
</div>
</div>
<br/>
<h3><a href="{{ URL::previous() }}#twitch_streams">Back</a></h3>
</div>
<!-- /.portlet -->
</div>
<!-- /.container -->
</div>
<!-- .content -->
</div>
@stop | gpl-3.0 |
waikato-datamining/adams-base | adams-core/src/test/java/adams/flow/source/newlist/FixedListTest.java | 1808 | /*
* 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/>.
*/
/**
* FixedListTest.java
* Copyright (C) 2014 University of Waikato, Hamilton, New Zealand
*/
package adams.flow.source.newlist;
import adams.core.base.BaseString;
/**
* Tests the FixedList list generator.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision: 5356 $
*/
public class FixedListTest
extends AbstractListGeneratorTestCase {
/**
* Constructs the test case. Called by subclasses.
*
* @param name the name of the test
*/
public FixedListTest(String name) {
super(name);
}
/**
* Returns the setups to use in the regression test.
*
* @return the setups
*/
@Override
protected AbstractListGenerator[] getRegressionSetups() {
FixedList[] result;
result = new FixedList[1];
result[0] = new FixedList();
result[0].setElements(new BaseString[]{new BaseString("1"), new BaseString("42")});
return result;
}
/**
* Returns the ignored line indices to use in the regression test.
*
* @return the setups
*/
@Override
protected int[] getRegressionIgnoredLineIndices() {
return new int[0];
}
}
| gpl-3.0 |
Nakaner/OpenRailwayMap | locales/scan_legends.py | 1868 | #!/usr/bin/python3
import fileinput
import json
import re
if __name__ == "__main__":
from optparse import OptionParser
parser = OptionParser(usage="%prog [options]")
parser.add_option("-i", "--input",
action="append", type="string", dest="ifiles",
help="JSON input file, required")
parser.add_option("-o", "--output",
action="append", type="string", dest="output",
help="po output file, required")
(options, args) = parser.parse_args()
if not options.ifiles or not options.output:
print("input and output parameters are required")
raise SystemExit(1)
ostrings = set()
capt_re = re.compile('^%[^%]+%$')
# get all possible translatable strings from the styles
for i in options.ifiles:
with open(i, 'r') as f:
jsondoc = json.load(f)
for x in jsondoc['mapfeatures']:
if 'heading' in x:
ostrings.add(x['heading'])
elif 'caption' in x:
# check if the whole caption is a single replace expression,
# then do not put that into the file, but only the matching
# expressions from the replace list
if 'replace' in x and capt_re.match(x['caption']):
for r in x['replace']:
ostrings.add(r[x['caption']])
else:
ostrings.add(x['caption'])
msgid_re = re.compile('^msgid "(.+)"$')
esc_table = str.maketrans({ '\\': r"\\",
'"': r"\"" })
for outf in options.output:
msgids = set()
# extract those msgid lines already present
with open(outf) as of:
line = of.readline()
while line:
m = msgid_re.match(line)
if m:
msgids.add(m.group(1))
line = of.readline()
with open(outf, 'a') as of:
# loop over all translatable strings
for i in ostrings:
estr = i.translate(esc_table)
if estr in msgids:
continue
# and add them if they are not already in the file
of.write('\n')
of.write('msgid "' + estr + '"\n')
of.write('msgstr ""\n')
| gpl-3.0 |
nossas/bonde-server | spec/requests/mobilizations/form_entries.rb | 1105 | require 'rails_helper'
RSpec.describe "FormEntries", type: :request do
let(:user) { create(:user) }
before { stub_current_user(user) }
describe 'GET /mobilizations/:mobilization_id/form_entries' do
let!(:widget) { create :widget }
let!(:form_entry_1) { create :form_entry, widget: widget }
let!(:form_entry_2) { create :form_entry }
context 'format csv joint_fields' do
before { get "/mobilizations/#{widget.mobilization.id}/form_entries.csv?widget_id=#{widget.id}&INFO=disjoint_fields" }
it { expect(response).to have_http_status(200) }
it do
expect(response.body).to include('email')
expect(response.body).to include('first name')
expect(response.body).to include('last name')
expect(response.body).not_to include('fields')
end
end
context 'format csv' do
before { get "/mobilizations/#{widget.mobilization.id}/form_entries.csv?widget_id=#{widget.id}" }
it { expect(response).to have_http_status(200) }
it do
expect(response.body).to include('fields')
end
end
end
end
| gpl-3.0 |
moovida/jgrasstools | apps/src/main/java/org/hortonmachine/nww/layers/defaults/spatialite/SpatialitePolygonLayer.java | 15134 | /*
* This file is part of HortonMachine (http://www.hortonmachine.org)
* (C) HydroloGIS - www.hydrologis.com
*
* The HortonMachine is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.hortonmachine.nww.layers.defaults.spatialite;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.hortonmachine.dbs.compat.ASpatialDb;
import org.hortonmachine.dbs.compat.objects.QueryResult;
import org.hortonmachine.dbs.log.Logger;
import org.hortonmachine.dbs.spatialite.hm.SpatialiteDb;
import org.hortonmachine.gears.spatialite.GTSpatialiteThreadsafeDb;
import org.hortonmachine.gears.utils.CrsUtilities;
import org.hortonmachine.nww.layers.defaults.NwwVectorLayer;
import org.hortonmachine.nww.shapes.InfoExtrudedPolygon;
import org.hortonmachine.nww.shapes.InfoPolygon;
import org.hortonmachine.nww.utils.NwwUtilities;
import org.hortonmachine.style.SimpleStyle;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LineString;
import gov.nasa.worldwind.WorldWind;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.layers.RenderableLayer;
import gov.nasa.worldwind.render.BasicShapeAttributes;
import gov.nasa.worldwind.render.Material;
/**
* A simple polygons layer.
*
* @author Andrea Antonello andrea.antonello@gmail.com
*/
public class SpatialitePolygonLayer extends RenderableLayer implements NwwVectorLayer {
private String mHeightFieldName;
private double mVerticalExageration = 1.0;
private double mConstantHeight = 1.0;
private boolean mHasConstantHeight = false;
private boolean mApplyExtrusion = false;
private BasicShapeAttributes mNormalShapeAttributes;
private BasicShapeAttributes mSideShapeAttributes;
private Material mFillMaterial = Material.BLUE;
private Material mSideFillMaterial = new Material(NwwUtilities.darkenColor(Color.BLUE));
private Material mStrokeMaterial = Material.RED;
private double mFillOpacity = 0.8;
private double mStrokeWidth = 2;
private int mElevationMode = WorldWind.CLAMP_TO_GROUND;
private String tableName;
private SpatialiteDb db;
private ReferencedEnvelope tableBounds;
private int featureLimit;
public SpatialitePolygonLayer( ASpatialDb db, String tableName, int featureLimit ) {
this.db = (SpatialiteDb) db;
this.tableName = tableName;
this.featureLimit = featureLimit;
try {
if (db instanceof GTSpatialiteThreadsafeDb) {
GTSpatialiteThreadsafeDb gtDb = (GTSpatialiteThreadsafeDb) db;
tableBounds = gtDb.getTableBounds(tableName);
} else {
tableBounds = CrsUtilities.WORLD;
}
} catch (Exception e) {
Logger.INSTANCE.insertError("", "ERROR", e);
tableBounds = CrsUtilities.WORLD;
}
setStyle(null);
loadData();
}
public void setStyle( SimpleStyle style ) {
if (style != null) {
mFillMaterial = new Material(style.fillColor);
mSideFillMaterial = new Material(NwwUtilities.darkenColor(style.fillColor));
mFillOpacity = style.fillOpacity;
mStrokeMaterial = new Material(style.strokeColor);
mStrokeWidth = style.strokeWidth;
}
if (mNormalShapeAttributes == null)
mNormalShapeAttributes = new BasicShapeAttributes();
mNormalShapeAttributes.setInteriorMaterial(mFillMaterial);
mNormalShapeAttributes.setInteriorOpacity(mFillOpacity);
mNormalShapeAttributes.setOutlineMaterial(mStrokeMaterial);
mNormalShapeAttributes.setOutlineWidth(mStrokeWidth);
if (mSideShapeAttributes == null)
mSideShapeAttributes = new BasicShapeAttributes();
mSideShapeAttributes.setInteriorMaterial(mSideFillMaterial);
mSideShapeAttributes.setInteriorOpacity(mFillOpacity);
}
@Override
public SimpleStyle getStyle() {
SimpleStyle simpleStyle = new SimpleStyle();
simpleStyle.fillColor = mNormalShapeAttributes.getInteriorMaterial().getDiffuse();
simpleStyle.fillOpacity = mNormalShapeAttributes.getInteriorOpacity();
simpleStyle.strokeColor = mNormalShapeAttributes.getOutlineMaterial().getDiffuse();
simpleStyle.strokeWidth = mNormalShapeAttributes.getOutlineWidth();
return simpleStyle;
}
public void setExtrusionProperties( Double constantExtrusionHeight, String heightFieldName, Double verticalExageration,
boolean withoutExtrusion ) {
if (constantExtrusionHeight != null) {
mHasConstantHeight = true;
mConstantHeight = constantExtrusionHeight;
mApplyExtrusion = !withoutExtrusion;
}
if (heightFieldName != null) {
mHeightFieldName = heightFieldName;
mVerticalExageration = verticalExageration;
mApplyExtrusion = !withoutExtrusion;
}
}
public void setElevationMode( int elevationMode ) {
mElevationMode = elevationMode;
}
public void loadData() {
Thread t = new WorkerThread();
t.start();
}
public class WorkerThread extends Thread {
public void run() {
try {
QueryResult tableRecords = db.getTableRecordsMapIn(tableName, null, featureLimit, NwwUtilities.GPS_CRS_SRID,
null);
int count = tableRecords.data.size();
List<String> names = tableRecords.names;
for( int i = 0; i < count; i++ ) {
Object[] objects = tableRecords.data.get(i);
StringBuilder sb = new StringBuilder();
double height = -1;
for( int j = 1; j < objects.length; j++ ) {
String varName = names.get(j);
sb.append(varName).append(": ").append(objects[j]).append("\n");
if (mHeightFieldName != null && varName == mHeightFieldName && objects[j] instanceof Number) {
height = ((Number) objects[j]).doubleValue();
}
}
String info = sb.toString();
Geometry geometry = (Geometry) objects[tableRecords.geometryIndex];
if (geometry == null) {
continue;
}
if (mApplyExtrusion && (mHeightFieldName != null || mHasConstantHeight)) {
addExtrudedPolygon(geometry, info, height);
} else {
addPolygon(geometry, info, height);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void addExtrudedPolygon( Geometry geometry, String info, double height ) {
try {
Coordinate[] coordinates = geometry.getCoordinates();
int numVertices = coordinates.length;
if (numVertices < 4)
return;
boolean hasZ = false;
double h = 0.0;
switch( mElevationMode ) {
case WorldWind.RELATIVE_TO_GROUND:
hasZ = false;
case WorldWind.ABSOLUTE:
default:
if (mHasConstantHeight) {
h = mConstantHeight;
}
if (mHeightFieldName != null) {
double tmpH = height;
tmpH = tmpH * mVerticalExageration;
h += tmpH;
}
break;
}
int numGeometries = geometry.getNumGeometries();
for( int i = 0; i < numGeometries; i++ ) {
Geometry geometryN = geometry.getGeometryN(i);
if (geometryN instanceof org.locationtech.jts.geom.Polygon) {
org.locationtech.jts.geom.Polygon poly = (org.locationtech.jts.geom.Polygon) geometryN;
InfoExtrudedPolygon extrudedPolygon = new InfoExtrudedPolygon();
extrudedPolygon.setInfo(info);
Coordinate[] extCoords = poly.getExteriorRing().getCoordinates();
int extSize = extCoords.length;
List<Position> verticesList = new ArrayList<>(extSize);
for( int n = 0; n < extSize; n++ ) {
Coordinate c = extCoords[n];
if (hasZ) {
double z = c.z;
verticesList.add(Position.fromDegrees(c.y, c.x, z + h));
} else {
verticesList.add(Position.fromDegrees(c.y, c.x, h));
}
}
verticesList.add(verticesList.get(0));
extrudedPolygon.setOuterBoundary(verticesList);
int numInteriorRings = poly.getNumInteriorRing();
for( int k = 0; k < numInteriorRings; k++ ) {
LineString interiorRing = poly.getInteriorRingN(k);
Coordinate[] intCoords = interiorRing.getCoordinates();
int internalNumVertices = intCoords.length;
List<Position> internalVerticesList = new ArrayList<>(internalNumVertices);
for( int j = 0; j < internalNumVertices; j++ ) {
Coordinate c = intCoords[j];
if (hasZ) {
double z = c.z;
internalVerticesList.add(Position.fromDegrees(c.y, c.x, z + h));
} else {
internalVerticesList.add(Position.fromDegrees(c.y, c.x, h));
}
}
extrudedPolygon.addInnerBoundary(internalVerticesList);
}
extrudedPolygon.setAltitudeMode(mElevationMode);
extrudedPolygon.setAttributes(mNormalShapeAttributes);
extrudedPolygon.setSideAttributes(mSideShapeAttributes);
addRenderable(extrudedPolygon);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void addPolygon( Geometry geometry, String info, double height ) {
Coordinate[] coordinates = geometry.getCoordinates();
int numVertices = coordinates.length;
if (numVertices < 4)
return;
boolean hasZ = !Double.isNaN(geometry.getCoordinate().z);
double h = 0.0;
switch( mElevationMode ) {
case WorldWind.CLAMP_TO_GROUND:
hasZ = false;
break;
case WorldWind.RELATIVE_TO_GROUND:
hasZ = false;
case WorldWind.ABSOLUTE:
default:
if (mHasConstantHeight) {
h = mConstantHeight;
}
if (mHeightFieldName != null) {
double tmpH = height;
tmpH = tmpH * mVerticalExageration;
h += tmpH;
}
break;
}
int numGeometries = geometry.getNumGeometries();
for( int i = 0; i < numGeometries; i++ ) {
Geometry geometryN = geometry.getGeometryN(i);
if (geometryN instanceof org.locationtech.jts.geom.Polygon) {
org.locationtech.jts.geom.Polygon poly = (org.locationtech.jts.geom.Polygon) geometryN;
InfoPolygon polygon = new InfoPolygon();
polygon.setInfo(info);
Coordinate[] extCoords = poly.getExteriorRing().getCoordinates();
int extSize = extCoords.length;
List<Position> verticesList = new ArrayList<>(extSize);
for( int n = 0; n < extSize; n++ ) {
Coordinate c = extCoords[n];
if (hasZ) {
double z = c.z;
verticesList.add(Position.fromDegrees(c.y, c.x, z + h));
} else {
verticesList.add(Position.fromDegrees(c.y, c.x, h));
}
}
verticesList.add(verticesList.get(0));
polygon.setOuterBoundary(verticesList);
int numInteriorRings = poly.getNumInteriorRing();
for( int k = 0; k < numInteriorRings; k++ ) {
LineString interiorRing = poly.getInteriorRingN(k);
Coordinate[] intCoords = interiorRing.getCoordinates();
int internalNumVertices = intCoords.length;
List<Position> internalVerticesList = new ArrayList<>(internalNumVertices);
for( int j = 0; j < internalNumVertices; j++ ) {
Coordinate c = intCoords[j];
if (hasZ) {
double z = c.z;
internalVerticesList.add(Position.fromDegrees(c.y, c.x, z + h));
} else {
internalVerticesList.add(Position.fromDegrees(c.y, c.x, h));
}
}
polygon.addInnerBoundary(internalVerticesList);
}
polygon.setAltitudeMode(mElevationMode);
polygon.setAttributes(mNormalShapeAttributes);
addRenderable(polygon);
}
}
}
}
@Override
public Coordinate getCenter() {
return tableBounds.centre();
}
@Override
public String toString() {
return tableName != null ? tableName : "Polygons";
}
@Override
public GEOMTYPE getType() {
return GEOMTYPE.POLYGON;
}
}
| gpl-3.0 |
kira8565/graylog2-server | graylog2-web-interface/src/stores/inputs/InputStatesStore.js | 3034 | import Reflux from 'reflux';
import UserNotification from 'util/UserNotification';
import URLUtils from 'util/URLUtils';
import ApiRoutes from 'routing/ApiRoutes';
import fetch from 'logic/rest/FetchProvider';
const InputStatesStore = Reflux.createStore({
listenables: [],
init() {
this.list();
},
getInitialState() {
return {inputStates: this.inputStates};
},
list() {
const url = URLUtils.qualifyUrl(ApiRoutes.ClusterInputStatesController.list().url);
return fetch('GET', url)
.then((response) => {
const result = {};
Object.keys(response).forEach((node) => {
if (!response[node]) {
return;
}
response[node].forEach((input) => {
if (!result[input.id]) {
result[input.id] = {};
}
result[input.id][node] = input;
});
});
this.inputStates = result;
this.trigger({inputStates: this.inputStates});
return result;
});
},
_checkInputStateChangeResponse(input, response, action) {
const nodes = Object.keys(response).filter(node => input.global ? true : node === input.node);
const failedNodes = nodes.filter((nodeId) => response[nodeId] === null);
if (failedNodes.length === 0) {
UserNotification.success(`Request to ${action.toLowerCase()} input '${input.title}' was sent successfully.`,
`Input '${input.title}' will be ${action === 'START' ? 'started' : 'stopped'} shortly`);
} else if (failedNodes.length === nodes.length) {
UserNotification.error(`Request to ${action.toLowerCase()} input '${input.title}' failed. Check your Graylog logs for more information.`,
`Input '${input.title}' could not be ${action === 'START' ? 'started' : 'stopped'}`);
} else {
UserNotification.warning(`Request to ${action.toLowerCase()} input '${input.title}' failed in some nodes. Check your Graylog logs for more information.`,
`Input '${input.title}' could not be ${action === 'START' ? 'started' : 'stopped'} in all nodes`);
}
},
start(input) {
const url = URLUtils.qualifyUrl(ApiRoutes.ClusterInputStatesController.start(input.id).url);
return fetch('PUT', url)
.then(
(response) => {
this._checkInputStateChangeResponse(input, response, 'START');
this.list();
},
error => {
UserNotification.error(`Error starting input '${input.title}': ${error}`, `Input '${input.title}' could not be started`);
});
},
stop(input) {
const url = URLUtils.qualifyUrl(ApiRoutes.ClusterInputStatesController.stop(input.id).url);
return fetch('DELETE', url)
.then(
(response) => {
this._checkInputStateChangeResponse(input, response, 'STOP');
this.list();
},
error => {
UserNotification.error(`Error stopping input '${input.title}': ${error}`, `Input '${input.title}' could not be stopped`);
});
},
});
export default InputStatesStore;
| gpl-3.0 |
EyeSeeTea/dhis2 | dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/datavalueset/DefaultDataValueSetService.java | 44710 | package org.hisp.dhis.dxf2.datavalueset;
/*
* Copyright (c) 2004-2016, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import com.csvreader.CsvReader;
import org.amplecode.quick.BatchHandler;
import org.amplecode.quick.BatchHandlerFactory;
import org.amplecode.staxwax.factory.XMLFactory;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.common.DxfNamespaces;
import org.hisp.dhis.common.IdScheme;
import org.hisp.dhis.common.IdSchemes;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.common.IdentifiableProperty;
import org.hisp.dhis.common.IllegalQueryException;
import org.hisp.dhis.commons.collection.CachingMap;
import org.hisp.dhis.commons.util.DebugUtils;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo;
import org.hisp.dhis.dataelement.DataElementCategoryService;
import org.hisp.dhis.dataset.CompleteDataSetRegistration;
import org.hisp.dhis.dataset.CompleteDataSetRegistrationService;
import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.datavalue.DataValue;
import org.hisp.dhis.dxf2.common.ImportOptions;
import org.hisp.dhis.dxf2.common.JacksonUtils;
import org.hisp.dhis.dxf2.importsummary.ImportConflict;
import org.hisp.dhis.dxf2.importsummary.ImportCount;
import org.hisp.dhis.dxf2.importsummary.ImportStatus;
import org.hisp.dhis.dxf2.importsummary.ImportSummary;
import org.hisp.dhis.dxf2.pdfform.PdfDataEntryFormUtil;
import org.hisp.dhis.i18n.I18n;
import org.hisp.dhis.i18n.I18nManager;
import org.hisp.dhis.importexport.ImportStrategy;
import org.hisp.dhis.jdbc.batchhandler.DataValueBatchHandler;
import org.hisp.dhis.node.types.CollectionNode;
import org.hisp.dhis.node.types.ComplexNode;
import org.hisp.dhis.node.types.RootNode;
import org.hisp.dhis.node.types.SimpleNode;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodService;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.scheduling.TaskId;
import org.hisp.dhis.setting.SettingKey;
import org.hisp.dhis.setting.SystemSettingManager;
import org.hisp.dhis.system.callable.CategoryOptionComboAclCallable;
import org.hisp.dhis.system.callable.IdentifiableObjectCallable;
import org.hisp.dhis.system.callable.PeriodCallable;
import org.hisp.dhis.system.notification.Notifier;
import org.hisp.dhis.system.util.Clock;
import org.hisp.dhis.system.util.DateUtils;
import org.hisp.dhis.system.util.ValidationUtils;
import org.hisp.dhis.user.CurrentUserService;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import static org.apache.commons.lang3.StringUtils.trimToNull;
import static org.hisp.dhis.system.notification.NotificationLevel.ERROR;
import static org.hisp.dhis.system.notification.NotificationLevel.INFO;
import static org.hisp.dhis.system.util.DateUtils.getDefaultDate;
import static org.hisp.dhis.system.util.DateUtils.parseDate;
/**
* @author Lars Helge Overland
*/
public class DefaultDataValueSetService
implements DataValueSetService
{
private static final Log log = LogFactory.getLog( DefaultDataValueSetService.class );
private static final String ERROR_OBJECT_NEEDED_TO_COMPLETE = "Must be provided to complete data set";
private static final int CACHE_MISS_THRESHOLD = 500;
@Autowired
private IdentifiableObjectManager identifiableObjectManager;
@Autowired
private DataElementCategoryService categoryService;
@Autowired
private OrganisationUnitService organisationUnitService;
@Autowired
private PeriodService periodService;
@Autowired
private BatchHandlerFactory batchHandlerFactory;
@Autowired
private CompleteDataSetRegistrationService registrationService;
@Autowired
private CurrentUserService currentUserService;
@Autowired
private DataValueSetStore dataValueSetStore;
@Autowired
private SystemSettingManager systemSettingManager;
@Autowired
private I18nManager i18nManager;
@Autowired
private Notifier notifier;
// Set methods for test purposes
public void setBatchHandlerFactory( BatchHandlerFactory batchHandlerFactory )
{
this.batchHandlerFactory = batchHandlerFactory;
}
public void setCurrentUserService( CurrentUserService currentUserService )
{
this.currentUserService = currentUserService;
}
// -------------------------------------------------------------------------
// DataValueSet implementation
// -------------------------------------------------------------------------
@Override
public DataExportParams getFromUrl( Set<String> dataSets, Set<String> periods, Date startDate, Date endDate,
Set<String> organisationUnits, boolean includeChildren, Date lastUpdated, Integer limit, IdSchemes idSchemes )
{
DataExportParams params = new DataExportParams();
if ( dataSets != null )
{
params.getDataSets().addAll( identifiableObjectManager.getByUid( DataSet.class, dataSets ) );
}
if ( periods != null && !periods.isEmpty() )
{
params.getPeriods().addAll( periodService.reloadIsoPeriods( new ArrayList<>( periods ) ) );
}
else if ( startDate != null && endDate != null )
{
params.setStartDate( startDate );
params.setEndDate( endDate );
}
if ( organisationUnits != null )
{
params.getOrganisationUnits().addAll( identifiableObjectManager.getByUid( OrganisationUnit.class, organisationUnits ) );
}
params.setIncludeChildren( includeChildren );
params.setLastUpdated( lastUpdated );
params.setLimit( limit );
params.setIdSchemes( idSchemes );
return params;
}
@Override
public void validate( DataExportParams params )
{
String violation = null;
if ( params == null )
{
throw new IllegalArgumentException( "Params cannot be null" );
}
if ( params.getDataSets().isEmpty() )
{
violation = "At least one valid data set must be specified";
}
if ( params.getPeriods().isEmpty() && !params.hasStartEndDate() )
{
violation = "At least one valid period or start/end dates must be specified";
}
if ( params.hasStartEndDate() && params.getStartDate().after( params.getEndDate() ) )
{
violation = "Start date must be before end date";
}
if ( params.getOrganisationUnits().isEmpty() )
{
violation = "At least one valid organisation unit must be specified";
}
if ( params.hasLimit() && params.getLimit() < 0 )
{
violation = "Limit cannot be less than zero: " + params.getLimit();
}
if ( violation != null )
{
log.warn( "Validation failed: " + violation );
throw new IllegalArgumentException( violation );
}
}
@Override
public void decideAccess( DataExportParams params )
{
for ( OrganisationUnit unit : params.getOrganisationUnits() )
{
if ( !organisationUnitService.isInUserHierarchy( unit ) )
{
throw new IllegalQueryException( "User is not allowed to view org unit: " + unit.getUid() );
}
}
}
// -------------------------------------------------------------------------
// Write
// -------------------------------------------------------------------------
@Override
public void writeDataValueSetXml( DataExportParams params, OutputStream out )
{
decideAccess( params );
validate( params );
dataValueSetStore.writeDataValueSetXml( params, getCompleteDate( params ), out );
}
@Override
public void writeDataValueSetJson( DataExportParams params, OutputStream out )
{
decideAccess( params );
validate( params );
dataValueSetStore.writeDataValueSetJson( params, getCompleteDate( params ), out );
}
@Override
public void writeDataValueSetJson( Date lastUpdated, OutputStream outputStream, IdSchemes idSchemes )
{
dataValueSetStore.writeDataValueSetJson( lastUpdated, outputStream, idSchemes );
}
@Override
public void writeDataValueSetCsv( DataExportParams params, Writer writer )
{
decideAccess( params );
validate( params );
dataValueSetStore.writeDataValueSetCsv( params, getCompleteDate( params ), writer );
}
private Date getCompleteDate( DataExportParams params )
{
if ( params.isSingleDataValueSet() )
{
DataElementCategoryOptionCombo optionCombo = categoryService.getDefaultDataElementCategoryOptionCombo(); //TODO
CompleteDataSetRegistration registration = registrationService
.getCompleteDataSetRegistration( params.getFirstDataSet(), params.getFirstPeriod(), params.getFirstOrganisationUnit(), optionCombo );
return registration != null ? registration.getDate() : null;
}
return null;
}
// -------------------------------------------------------------------------
// Template
// -------------------------------------------------------------------------
@Override
public RootNode getDataValueSetTemplate( DataSet dataSet, Period period, List<String> orgUnits,
boolean writeComments, String ouScheme, String deScheme )
{
RootNode rootNode = new RootNode( "dataValueSet" );
rootNode.setNamespace( DxfNamespaces.DXF_2_0 );
rootNode.setComment( "Data set: " + dataSet.getDisplayName() + " (" + dataSet.getUid() + ")" );
CollectionNode collectionNode = rootNode.addChild( new CollectionNode( "dataValues" ) );
collectionNode.setWrapping( false );
if ( orgUnits.isEmpty() )
{
for ( DataElement dataElement : dataSet.getDataElements() )
{
CollectionNode collection = getDataValueTemplate( dataElement, deScheme, null, ouScheme, period,
writeComments );
collectionNode.addChildren( collection.getChildren() );
}
}
else
{
for ( String orgUnit : orgUnits )
{
OrganisationUnit organisationUnit = identifiableObjectManager.search( OrganisationUnit.class, orgUnit );
if ( organisationUnit == null )
{
continue;
}
for ( DataElement dataElement : dataSet.getDataElements() )
{
CollectionNode collection = getDataValueTemplate( dataElement, deScheme, organisationUnit, ouScheme,
period, writeComments );
collectionNode.addChildren( collection.getChildren() );
}
}
}
return rootNode;
}
private CollectionNode getDataValueTemplate( DataElement dataElement, String deScheme,
OrganisationUnit organisationUnit, String ouScheme, Period period, boolean comment )
{
CollectionNode collectionNode = new CollectionNode( "dataValues" );
collectionNode.setWrapping( false );
for ( DataElementCategoryOptionCombo categoryOptionCombo : dataElement.getCategoryCombo().getSortedOptionCombos() )
{
ComplexNode complexNode = collectionNode.addChild( new ComplexNode( "dataValue" ) );
String label = dataElement.getDisplayName();
if ( !categoryOptionCombo.isDefault() )
{
label += " " + categoryOptionCombo.getDisplayName();
}
if ( comment )
{
complexNode.setComment( "Data element: " + label );
}
if ( IdentifiableProperty.CODE.toString().toLowerCase()
.equals( deScheme.toLowerCase() ) )
{
SimpleNode simpleNode = complexNode.addChild( new SimpleNode( "dataElement", dataElement.getCode() ) );
simpleNode.setAttribute( true );
}
else
{
SimpleNode simpleNode = complexNode.addChild( new SimpleNode( "dataElement", dataElement.getUid() ) );
simpleNode.setAttribute( true );
}
SimpleNode simpleNode = complexNode.addChild( new SimpleNode( "categoryOptionCombo", categoryOptionCombo.getUid() ) );
simpleNode.setAttribute( true );
simpleNode = complexNode.addChild( new SimpleNode( "period", period != null ? period.getIsoDate() : "" ) );
simpleNode.setAttribute( true );
if ( organisationUnit != null )
{
if ( IdentifiableProperty.CODE.toString().toLowerCase().equals( ouScheme.toLowerCase() ) )
{
simpleNode = complexNode.addChild( new SimpleNode( "orgUnit", organisationUnit.getCode() == null ? "" : organisationUnit.getCode() ) );
simpleNode.setAttribute( true );
}
else
{
simpleNode = complexNode.addChild( new SimpleNode( "orgUnit", organisationUnit.getUid() == null ? "" : organisationUnit.getUid() ) );
simpleNode.setAttribute( true );
}
}
simpleNode = complexNode.addChild( new SimpleNode( "value", "" ) );
simpleNode.setAttribute( true );
}
return collectionNode;
}
// -------------------------------------------------------------------------
// Save
// -------------------------------------------------------------------------
@Override
public ImportSummary saveDataValueSet( InputStream in )
{
return saveDataValueSet( in, ImportOptions.getDefaultImportOptions(), null );
}
@Override
public ImportSummary saveDataValueSetJson( InputStream in )
{
return saveDataValueSetJson( in, ImportOptions.getDefaultImportOptions(), null );
}
@Override
public ImportSummary saveDataValueSet( InputStream in, ImportOptions importOptions )
{
return saveDataValueSet( in, importOptions, null );
}
@Override
public ImportSummary saveDataValueSetJson( InputStream in, ImportOptions importOptions )
{
return saveDataValueSetJson( in, importOptions, null );
}
@Override
public ImportSummary saveDataValueSetCsv( InputStream in, ImportOptions importOptions )
{
return saveDataValueSetCsv( in, importOptions, null );
}
@Override
public ImportSummary saveDataValueSet( InputStream in, ImportOptions importOptions, TaskId id )
{
try
{
DataValueSet dataValueSet = new StreamingDataValueSet( XMLFactory.getXMLReader( in ) );
return saveDataValueSet( importOptions, id, dataValueSet );
}
catch ( RuntimeException ex )
{
log.error( DebugUtils.getStackTrace( ex ) );
notifier.notify( id, ERROR, "Process failed: " + ex.getMessage(), true );
return new ImportSummary( ImportStatus.ERROR, "The import process failed: " + ex.getMessage() );
}
}
@Override
public ImportSummary saveDataValueSetJson( InputStream in, ImportOptions importOptions, TaskId id )
{
try
{
DataValueSet dataValueSet = JacksonUtils.fromJson( in, DataValueSet.class );
return saveDataValueSet( importOptions, id, dataValueSet );
}
catch ( Exception ex )
{
log.error( DebugUtils.getStackTrace( ex ) );
notifier.notify( id, ERROR, "Process failed: " + ex.getMessage(), true );
return new ImportSummary( ImportStatus.ERROR, "The import process failed: " + ex.getMessage() );
}
}
@Override
public ImportSummary saveDataValueSetCsv( InputStream in, ImportOptions importOptions, TaskId id )
{
try
{
DataValueSet dataValueSet = new StreamingCsvDataValueSet( new CsvReader( in, Charset.forName( "UTF-8" ) ) );
return saveDataValueSet( importOptions, id, dataValueSet );
}
catch ( RuntimeException ex )
{
log.error( DebugUtils.getStackTrace( ex ) );
notifier.clear( id ).notify( id, ERROR, "Process failed: " + ex.getMessage(), true );
return new ImportSummary( ImportStatus.ERROR, "The import process failed: " + ex.getMessage() );
}
}
@Override
public ImportSummary saveDataValueSetPdf( InputStream in, ImportOptions importOptions, TaskId id )
{
try
{
DataValueSet dataValueSet = PdfDataEntryFormUtil.getDataValueSet( in );
return saveDataValueSet( importOptions, id, dataValueSet );
}
catch ( RuntimeException ex )
{
log.error( DebugUtils.getStackTrace( ex ) );
notifier.clear( id ).notify( id, ERROR, "Process failed: " + ex.getMessage(), true );
return new ImportSummary( ImportStatus.ERROR, "The import process failed: " + ex.getMessage() );
}
}
/**
* There are specific id schemes for data elements and organisation units and
* a generic id scheme for all objects. The specific id schemes will take
* precedence over the generic id scheme. The generic id scheme also applies
* to data set and category option combo.
* <p>
* The id schemes uses the following order of precedence:
* <p>
* <ul>
* <li>Id scheme from the data value set</li>
* <li>Id scheme from the import options</li>
* <li>Default id scheme which is UID</li>
* <ul>
* <p>
* If id scheme is specific in the data value set, any id schemes in the import
* options will be ignored.
*
* @param importOptions
* @param id
* @param dataValueSet
* @return
*/
private ImportSummary saveDataValueSet( ImportOptions importOptions, TaskId id, DataValueSet dataValueSet )
{
Clock clock = new Clock( log ).startClock().logTime( "Starting data value import, options: " + importOptions );
notifier.clear( id ).notify( id, "Process started" );
ImportSummary summary = new ImportSummary();
I18n i18n = i18nManager.getI18n();
// ---------------------------------------------------------------------
// Get import options
// ---------------------------------------------------------------------
importOptions = importOptions != null ? importOptions : ImportOptions.getDefaultImportOptions();
log.info( "Import options: " + importOptions );
IdScheme dvSetIdScheme = IdScheme.from( dataValueSet.getIdSchemeProperty() );
IdScheme dvSetDataElementIdScheme = IdScheme.from( dataValueSet.getDataElementIdSchemeProperty() );
IdScheme dvSetOrgUnitIdScheme = IdScheme.from( dataValueSet.getOrgUnitIdSchemeProperty() );
log.info( "Data value set scheme: " + dvSetIdScheme + ", data element scheme: " + dvSetDataElementIdScheme + ", org unit scheme: " + dvSetOrgUnitIdScheme );
IdScheme idScheme = dvSetIdScheme.isNotNull() ? dvSetIdScheme : importOptions.getIdSchemes().getIdScheme();
IdScheme dataElementIdScheme = dvSetDataElementIdScheme.isNotNull() ? dvSetDataElementIdScheme : importOptions.getIdSchemes().getDataElementIdScheme();
IdScheme orgUnitIdScheme = dvSetOrgUnitIdScheme.isNotNull() ? dvSetOrgUnitIdScheme : importOptions.getIdSchemes().getOrgUnitIdScheme();
log.info( "Scheme: " + idScheme + ", data element scheme: " + dataElementIdScheme + ", org unit scheme: " + orgUnitIdScheme );
ImportStrategy strategy = dataValueSet.getStrategy() != null ?
ImportStrategy.valueOf( dataValueSet.getStrategy() ) : importOptions.getImportStrategy();
boolean dryRun = dataValueSet.getDryRun() != null ? dataValueSet.getDryRun() : importOptions.isDryRun();
boolean skipExistingCheck = importOptions.isSkipExistingCheck();
boolean strictPeriods = importOptions.isStrictPeriods() || (Boolean) systemSettingManager.getSystemSetting( SettingKey.DATA_IMPORT_STRICT_PERIODS );
boolean strictCategoryOptionCombos = importOptions.isStrictCategoryOptionCombos() || (Boolean) systemSettingManager.getSystemSetting( SettingKey.DATA_IMPORT_STRICT_CATEGORY_OPTION_COMBOS );
boolean strictAttrOptionCombos = importOptions.isStrictAttributeOptionCombos() || (Boolean) systemSettingManager.getSystemSetting( SettingKey.DATA_IMPORT_STRICT_ATTRIBUTE_OPTION_COMBOS );
boolean strictOrgUnits = importOptions.isStrictOrganisationUnits() || (Boolean) systemSettingManager.getSystemSetting( SettingKey.DATA_IMPORT_STRICT_ORGANISATION_UNITS );
boolean requireCategoryOptionCombo = importOptions.isRequireCategoryOptionCombo() || (Boolean) systemSettingManager.getSystemSetting( SettingKey.DATA_IMPORT_REQUIRE_CATEGORY_OPTION_COMBO );
boolean requireAttrOptionCombo = importOptions.isRequireAttributeOptionCombo() || (Boolean) systemSettingManager.getSystemSetting( SettingKey.DATA_IMPORT_REQUIRE_ATTRIBUTE_OPTION_COMBO );
// ---------------------------------------------------------------------
// Create meta-data maps
// ---------------------------------------------------------------------
CachingMap<String, DataElement> dataElementMap = new CachingMap<>();
CachingMap<String, OrganisationUnit> orgUnitMap = new CachingMap<>();
CachingMap<String, DataElementCategoryOptionCombo> optionComboMap = new CachingMap<>();
CachingMap<String, Period> periodMap = new CachingMap<>();
CachingMap<String, Set<PeriodType>> dataElementPeriodTypesMap = new CachingMap<>();
CachingMap<String, Set<DataElementCategoryOptionCombo>> dataElementCategoryOptionComboMap = new CachingMap<>();
CachingMap<String, Set<DataElementCategoryOptionCombo>> dataElementAttrOptionComboMap = new CachingMap<>();
CachingMap<String, Boolean> dataElementOrgUnitMap = new CachingMap<>();
CachingMap<String, Period> dataElementLatestFuturePeriodMap = new CachingMap<>();
CachingMap<String, Boolean> orgUnitInHierarchyMap = new CachingMap<>();
CachingMap<String, Optional<Set<String>>> dataElementOptionsMap = new CachingMap<>();
// ---------------------------------------------------------------------
// Get meta-data maps
// ---------------------------------------------------------------------
IdentifiableObjectCallable<DataElement> dataElementCallable = new IdentifiableObjectCallable<>(
identifiableObjectManager, DataElement.class, dataElementIdScheme, null );
IdentifiableObjectCallable<OrganisationUnit> orgUnitCallable = new IdentifiableObjectCallable<>(
identifiableObjectManager, OrganisationUnit.class, orgUnitIdScheme, trimToNull( dataValueSet.getOrgUnit() ) );
IdentifiableObjectCallable<DataElementCategoryOptionCombo> optionComboCallable = new CategoryOptionComboAclCallable( categoryService, idScheme, null );
IdentifiableObjectCallable<Period> periodCallable = new PeriodCallable( periodService, null, trimToNull( dataValueSet.getPeriod() ) );
// ---------------------------------------------------------------------
// Heat caches
// ---------------------------------------------------------------------
if ( importOptions.isPreheatCacheDefaultFalse() )
{
dataElementMap.load( identifiableObjectManager.getAll( DataElement.class ), o -> o.getPropertyValue( dataElementIdScheme ) );
orgUnitMap.load( identifiableObjectManager.getAll( OrganisationUnit.class ), o -> o.getPropertyValue( orgUnitIdScheme ) );
optionComboMap.load( identifiableObjectManager.getAll( DataElementCategoryOptionCombo.class ), o -> o.getPropertyValue( idScheme ) );
}
// ---------------------------------------------------------------------
// Get outer meta-data
// ---------------------------------------------------------------------
DataSet dataSet = dataValueSet.getDataSet() != null ? identifiableObjectManager.getObject( DataSet.class, idScheme, dataValueSet.getDataSet() ) : null;
Date completeDate = getDefaultDate( dataValueSet.getCompleteDate() );
Period outerPeriod = periodMap.get( trimToNull( dataValueSet.getPeriod() ), periodCallable );
OrganisationUnit outerOrgUnit = orgUnitMap.get( trimToNull( dataValueSet.getOrgUnit() ), orgUnitCallable );
DataElementCategoryOptionCombo fallbackCategoryOptionCombo = categoryService.getDefaultDataElementCategoryOptionCombo();
DataElementCategoryOptionCombo outerAttrOptionCombo = dataValueSet.getAttributeOptionCombo() != null ?
optionComboMap.get( trimToNull( dataValueSet.getAttributeOptionCombo() ), optionComboCallable.setId( trimToNull( dataValueSet.getAttributeOptionCombo() ) ) ) : null;
// ---------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------
if ( dataSet == null && trimToNull( dataValueSet.getDataSet() ) != null )
{
summary.getConflicts().add( new ImportConflict( dataValueSet.getDataSet(), "Data set not found or not accessible" ) );
summary.setStatus( ImportStatus.ERROR );
}
if ( outerOrgUnit == null && trimToNull( dataValueSet.getOrgUnit() ) != null )
{
summary.getConflicts().add( new ImportConflict( dataValueSet.getDataSet(), "Org unit not found or not accessible" ) );
summary.setStatus( ImportStatus.ERROR );
}
if ( outerAttrOptionCombo == null && trimToNull( dataValueSet.getAttributeOptionCombo() ) != null )
{
summary.getConflicts().add( new ImportConflict( dataValueSet.getDataSet(), "Attribute option combo not found or not accessible" ) );
summary.setStatus( ImportStatus.ERROR );
}
if ( ImportStatus.ERROR.equals( summary.getStatus() ) )
{
summary.setDescription( "Import process was aborted" );
notifier.notify( id, INFO, "Import process aborted", true ).addTaskSummary( id, summary );
dataValueSet.close();
return summary;
}
if ( dataSet != null && completeDate != null )
{
notifier.notify( id, "Completing data set" );
handleComplete( dataSet, completeDate, outerPeriod, outerOrgUnit, fallbackCategoryOptionCombo, summary ); //TODO
}
else
{
summary.setDataSetComplete( Boolean.FALSE.toString() );
}
final String currentUser = currentUserService.getCurrentUsername();
final Set<OrganisationUnit> currentOrgUnits = currentUserService.getCurrentUserOrganisationUnits();
BatchHandler<DataValue> batchHandler = batchHandlerFactory.createBatchHandler( DataValueBatchHandler.class ).init();
int importCount = 0;
int updateCount = 0;
int deleteCount = 0;
int totalCount = 0;
// ---------------------------------------------------------------------
// Data values
// ---------------------------------------------------------------------
Date now = new Date();
clock.logTime( "Validated outer meta-data" );
notifier.notify( id, "Importing data values" );
while ( dataValueSet.hasNextDataValue() )
{
org.hisp.dhis.dxf2.datavalue.DataValue dataValue = dataValueSet.getNextDataValue();
totalCount++;
final DataElement dataElement =
dataElementMap.get( trimToNull( dataValue.getDataElement() ), dataElementCallable.setId( trimToNull( dataValue.getDataElement() ) ) );
final Period period = outerPeriod != null ? outerPeriod :
periodMap.get( trimToNull( dataValue.getPeriod() ), periodCallable.setId( trimToNull( dataValue.getPeriod() ) ) );
final OrganisationUnit orgUnit = outerOrgUnit != null ? outerOrgUnit :
orgUnitMap.get( trimToNull( dataValue.getOrgUnit() ), orgUnitCallable.setId( trimToNull( dataValue.getOrgUnit() ) ) );
DataElementCategoryOptionCombo categoryOptionCombo = optionComboMap.get( trimToNull( dataValue.getCategoryOptionCombo() ),
optionComboCallable.setId( trimToNull( dataValue.getCategoryOptionCombo() ) ) );
DataElementCategoryOptionCombo attrOptionCombo = outerAttrOptionCombo != null ? outerAttrOptionCombo :
optionComboMap.get( trimToNull( dataValue.getAttributeOptionCombo() ), optionComboCallable.setId( trimToNull( dataValue.getAttributeOptionCombo() ) ) );
// -----------------------------------------------------------------
// Potentially heat caches
// -----------------------------------------------------------------
if ( !dataElementMap.isCacheLoaded() && dataElementMap.getCacheMissCount() > CACHE_MISS_THRESHOLD )
{
dataElementMap.load( identifiableObjectManager.getAll( DataElement.class ), o -> o.getPropertyValue( dataElementIdScheme ) );
log.info( "Data element cache heated after cache miss threshold reached" );
}
if ( !orgUnitMap.isCacheLoaded() && orgUnitMap.getCacheMissCount() > CACHE_MISS_THRESHOLD )
{
orgUnitMap.load( identifiableObjectManager.getAll( OrganisationUnit.class ), o -> o.getPropertyValue( orgUnitIdScheme ) );
log.info( "Org unit cache heated after cache miss threshold reached" );
}
// -----------------------------------------------------------------
// Validation
// -----------------------------------------------------------------
if ( dataElement == null )
{
summary.getConflicts().add( new ImportConflict( dataValue.getDataElement(), "Data element not found or not accessible" ) );
continue;
}
if ( period == null )
{
summary.getConflicts().add( new ImportConflict( dataValue.getPeriod(), "Period not valid" ) );
continue;
}
if ( orgUnit == null )
{
summary.getConflicts().add( new ImportConflict( dataValue.getOrgUnit(), "Organisation unit not found or not accessible" ) );
continue;
}
if ( categoryOptionCombo == null && trimToNull( dataValue.getCategoryOptionCombo() ) != null )
{
summary.getConflicts().add( new ImportConflict( dataValue.getCategoryOptionCombo(), "Category option combo not found or not accessible" ) );
continue;
}
if ( attrOptionCombo == null && trimToNull( dataValue.getAttributeOptionCombo() ) != null )
{
summary.getConflicts().add( new ImportConflict( dataValue.getAttributeOptionCombo(), "Attribute option combo not found or not accessible" ) );
continue;
}
boolean inUserHierarchy = orgUnitInHierarchyMap.get( orgUnit.getUid(), () -> orgUnit.isDescendant( currentOrgUnits ) );
if ( !inUserHierarchy )
{
summary.getConflicts().add( new ImportConflict( orgUnit.getUid(), "Organisation unit not in hierarchy of current user: " + currentUser ) );
continue;
}
Period latestFuturePeriod = dataElementLatestFuturePeriodMap.get( dataElement.getUid(), () -> dataElement.getLatestOpenFuturePeriod() );
if ( period.isAfter( latestFuturePeriod ) )
{
summary.getConflicts().add( new ImportConflict( period.getIsoDate(), "Period: " +
period.getIsoDate() + " is after latest open future period: " + latestFuturePeriod.getIsoDate() + " for data element: " + dataElement.getUid() ) );
continue;
}
if ( dataValue.getValue() == null && dataValue.getComment() == null )
{
continue;
}
String valueValid = ValidationUtils.dataValueIsValid( dataValue.getValue(), dataElement );
if ( valueValid != null )
{
summary.getConflicts().add( new ImportConflict( dataValue.getValue(), i18n.getString( valueValid ) + ", must match data element type: " + dataElement.getUid() ) );
continue;
}
String commentValid = ValidationUtils.commentIsValid( dataValue.getComment() );
if ( commentValid != null )
{
summary.getConflicts().add( new ImportConflict( "Comment", i18n.getString( commentValid ) ) );
continue;
}
Optional<Set<String>> optionCodes = dataElementOptionsMap.get( dataElement.getUid(), () -> dataElement.hasOptionSet() ?
Optional.of( dataElement.getOptionSet().getOptionCodesAsSet() ) : Optional.empty() );
if ( optionCodes.isPresent() && !optionCodes.get().contains( dataValue.getValue() ) )
{
summary.getConflicts().add( new ImportConflict( dataValue.getValue(), "Data value is not a valid option of the data element option set: " + dataElement.getUid() ) );
continue;
}
// -----------------------------------------------------------------
// Constraints
// -----------------------------------------------------------------
if ( categoryOptionCombo == null )
{
if ( requireCategoryOptionCombo )
{
summary.getConflicts().add( new ImportConflict( dataValue.getValue(), "Category option combo is required but is not specified" ) );
continue;
}
else
{
categoryOptionCombo = fallbackCategoryOptionCombo;
}
}
if ( attrOptionCombo == null )
{
if ( requireAttrOptionCombo )
{
summary.getConflicts().add( new ImportConflict( dataValue.getValue(), "Attribute option combo is required but is not specified" ) );
continue;
}
else
{
attrOptionCombo = fallbackCategoryOptionCombo;
}
}
if ( strictPeriods && !dataElementPeriodTypesMap.get( dataElement.getUid(),
() -> dataElement.getPeriodTypes() ).contains( period.getPeriodType() ) )
{
summary.getConflicts().add( new ImportConflict( dataValue.getPeriod(),
"Period type of period: " + period.getIsoDate() + " not valid for data element: " + dataElement.getUid() ) );
continue;
}
if ( strictCategoryOptionCombos && !dataElementCategoryOptionComboMap.get( dataElement.getUid(),
() -> dataElement.getCategoryCombo().getOptionCombos() ).contains( categoryOptionCombo ) )
{
summary.getConflicts().add( new ImportConflict( categoryOptionCombo.getUid(),
"Category option combo: " + categoryOptionCombo.getUid() + " must be part of category combo of data element: " + dataElement.getUid() ) );
continue;
}
if ( strictAttrOptionCombos && !dataElementAttrOptionComboMap.get( dataElement.getUid(),
() -> dataElement.getDataSetCategoryOptionCombos() ).contains( attrOptionCombo ) )
{
summary.getConflicts().add( new ImportConflict( attrOptionCombo.getUid(),
"Attribute option combo: " + attrOptionCombo.getUid() + " must be part of category combo of data sets of data element: " + dataElement.getUid() ) );
continue;
}
if ( strictOrgUnits && BooleanUtils.isFalse( dataElementOrgUnitMap.get( dataElement.getUid() + orgUnit.getUid(),
() -> orgUnit.hasDataElement( dataElement ) ) ) )
{
summary.getConflicts().add( new ImportConflict( orgUnit.getUid(),
"Data element: " + dataElement.getUid() + " must be assigned through data sets to organisation unit: " + orgUnit.getUid() ) );
continue;
}
boolean zeroInsignificant = ValidationUtils.dataValueIsZeroAndInsignificant( dataValue.getValue(), dataElement );
if ( zeroInsignificant )
{
summary.getConflicts().add( new ImportConflict( dataValue.getValue(), "Value is zero and not significant, must match data element: " + dataElement.getUid() ) );
continue;
}
String storedByValid = ValidationUtils.storedByIsValid( dataValue.getStoredBy() );
if ( storedByValid != null )
{
summary.getConflicts().add( new ImportConflict( dataValue.getStoredBy(), i18n.getString( storedByValid ) ) );
continue;
}
String storedBy = dataValue.getStoredBy() == null || dataValue.getStoredBy().trim().isEmpty() ? currentUser : dataValue.getStoredBy();
// -----------------------------------------------------------------
// Create data value
// -----------------------------------------------------------------
DataValue internalValue = new DataValue();
internalValue.setDataElement( dataElement );
internalValue.setPeriod( period );
internalValue.setSource( orgUnit );
internalValue.setCategoryOptionCombo( categoryOptionCombo );
internalValue.setAttributeOptionCombo( attrOptionCombo );
internalValue.setValue( trimToNull( dataValue.getValue() ) );
internalValue.setStoredBy( storedBy );
internalValue.setCreated( dataValue.hasCreated() ? parseDate( dataValue.getCreated() ) : now );
internalValue.setLastUpdated( dataValue.hasLastUpdated() ? parseDate( dataValue.getLastUpdated() ) : now );
internalValue.setComment( trimToNull( dataValue.getComment() ) );
internalValue.setFollowup( dataValue.getFollowup() );
// -----------------------------------------------------------------
// Save, update or delete data value
// -----------------------------------------------------------------
if ( !skipExistingCheck && batchHandler.objectExists( internalValue ) )
{
if ( strategy.isCreateAndUpdate() || strategy.isUpdate() )
{
if ( !dryRun )
{
if ( !internalValue.isNullValue() )
{
batchHandler.updateObject( internalValue );
}
else
{
batchHandler.deleteObject( internalValue );
}
}
updateCount++;
}
else if ( strategy.isDelete() )
{
if ( !dryRun )
{
batchHandler.deleteObject( internalValue );
}
deleteCount++;
}
}
else
{
if ( strategy.isCreateAndUpdate() || strategy.isCreate() )
{
if ( !dryRun && !internalValue.isNullValue() )
{
if ( batchHandler.addObject( internalValue ) )
{
importCount++;
}
}
}
}
}
batchHandler.flush();
int ignores = totalCount - importCount - updateCount - deleteCount;
summary.setImportCount( new ImportCount( importCount, updateCount, ignores, deleteCount ) );
summary.setStatus( ImportStatus.SUCCESS );
summary.setDescription( "Import process completed successfully" );
notifier.notify( id, INFO, "Import done", true ).addTaskSummary( id, summary );
clock.logTime( "Data value import done, total: " + totalCount + ", import: " + importCount + ", update: " + updateCount + ", delete: " + deleteCount );
dataValueSet.close();
return summary;
}
// -------------------------------------------------------------------------
// Supportive methods
// -------------------------------------------------------------------------
private void handleComplete( DataSet dataSet, Date completeDate, Period period, OrganisationUnit orgUnit,
DataElementCategoryOptionCombo attributeOptionCombo, ImportSummary summary )
{
if ( orgUnit == null )
{
summary.getConflicts().add( new ImportConflict( OrganisationUnit.class.getSimpleName(), ERROR_OBJECT_NEEDED_TO_COMPLETE ) );
return;
}
if ( period == null )
{
summary.getConflicts().add( new ImportConflict( Period.class.getSimpleName(), ERROR_OBJECT_NEEDED_TO_COMPLETE ) );
return;
}
period = periodService.reloadPeriod( period );
CompleteDataSetRegistration completeAlready = registrationService
.getCompleteDataSetRegistration( dataSet, period, orgUnit, attributeOptionCombo );
String username = currentUserService.getCurrentUsername();
if ( completeAlready != null )
{
completeAlready.setStoredBy( username );
completeAlready.setDate( completeDate );
registrationService.updateCompleteDataSetRegistration( completeAlready );
}
else
{
CompleteDataSetRegistration registration = new CompleteDataSetRegistration( dataSet, period, orgUnit,
attributeOptionCombo, completeDate, username );
registrationService.saveCompleteDataSetRegistration( registration );
}
summary.setDataSetComplete( DateUtils.getMediumDateString( completeDate ) );
}
}
| gpl-3.0 |
ayman-alkom/espocrm | application/Espo/Core/Field/DateTime/DateTimeFactory.php | 1979 | <?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2021 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
*
* EspoCRM 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.
*
* EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Core\Field\DateTime;
use Espo\{
ORM\Entity,
ORM\Value\ValueFactory,
};
use Espo\Core\Field\DateTime;
use RuntimeException;
class DateTimeFactory implements ValueFactory
{
public function isCreatableFromEntity(Entity $entity, string $field): bool
{
return $entity->get($field) !== null;
}
public function createFromEntity(Entity $entity, string $field): DateTime
{
if (!$this->isCreatableFromEntity($entity, $field)) {
throw new RuntimeException();
}
return new DateTime(
$entity->get($field)
);
}
}
| gpl-3.0 |
OpenCFD/OpenFOAM-1.7.x | src/thermophysicalModels/specie/reaction/Reactions/Reaction/Reaction.H | 8320 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd.
\\/ 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::Reaction
Description
Simple extension of ReactionThermo to handle reaction kinetics in addition
to the equilibrium thermodynamics already handled.
SourceFiles
ReactionI.H
Reaction.C
\*---------------------------------------------------------------------------*/
#ifndef Reaction_H
#define Reaction_H
#include "speciesTable.H"
#include "HashPtrTable.H"
#include "scalarField.H"
#include "typeInfo.H"
#include "runTimeSelectionTables.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// Forward declaration of friend functions and operators
template<class ReactionThermo>
class Reaction;
template<class ReactionThermo>
inline Ostream& operator<<(Ostream&, const Reaction<ReactionThermo>&);
/*---------------------------------------------------------------------------*\
Class Reaction Declaration
\*---------------------------------------------------------------------------*/
template<class ReactionThermo>
class Reaction
:
public ReactionThermo
{
public:
// Public data types
//- Class to hold the specie index and its coefficients in the
// reaction rate expression
struct specieCoeffs
{
label index;
scalar stoichCoeff;
scalar exponent;
specieCoeffs()
:
index(-1),
stoichCoeff(0),
exponent(1)
{}
specieCoeffs(const speciesTable& species, Istream& is);
bool operator==(const specieCoeffs& sc) const
{
return index == sc.index;
}
bool operator!=(const specieCoeffs& sc) const
{
return index != sc.index;
}
friend Ostream& operator<<(Ostream& os, const specieCoeffs& sc)
{
os << sc.index << token::SPACE
<< sc.stoichCoeff << token::SPACE
<< sc.exponent;
return os;
}
};
private:
// Private data
//- List of specie names present in reaction system
const speciesTable& species_;
//- Specie info for the left-hand-side of the reaction
List<specieCoeffs> lhs_;
//- Specie info for the right-hand-side of the reaction
List<specieCoeffs> rhs_;
// Private member functions
void setLRhs(Istream&);
void setThermo(const HashPtrTable<ReactionThermo>& thermoDatabase);
//- Disallow default bitwise assignment
void operator=(const Reaction<ReactionThermo>&);
public:
//- Runtime type information
TypeName("Reaction");
// Declare run-time constructor selection tables
declareRunTimeSelectionTable
(
autoPtr,
Reaction,
Istream,
(
const speciesTable& species,
const HashPtrTable<ReactionThermo>& thermoDatabase,
Istream& is
),
(species, thermoDatabase, is)
);
// Public classes
//- Class used for the read-construction of PtrLists of reaction
class iNew
{
const speciesTable& species_;
const HashPtrTable<ReactionThermo>& thermoDatabase_;
public:
iNew
(
const speciesTable& species,
const HashPtrTable<ReactionThermo>& thermoDatabase
)
:
species_(species),
thermoDatabase_(thermoDatabase)
{}
autoPtr<Reaction> operator()(Istream& is) const
{
return autoPtr<Reaction>
(
Reaction::New(species_, thermoDatabase_, is)
);
}
};
// Constructors
//- Construct from components
Reaction
(
const speciesTable& species,
const List<specieCoeffs>& lhs,
const List<specieCoeffs>& rhs,
const HashPtrTable<ReactionThermo>& thermoDatabase
);
//- Construct as copy given new speciesTable
Reaction(const Reaction<ReactionThermo>&, const speciesTable& species);
//- Construct from Istream
Reaction
(
const speciesTable& species,
const HashPtrTable<ReactionThermo>& thermoDatabase,
Istream& is
);
//- Construct and return a clone
virtual autoPtr<Reaction<ReactionThermo> > clone() const
{
return autoPtr<Reaction<ReactionThermo> >
(
new Reaction<ReactionThermo>(*this)
);
}
//- Construct and return a clone with new speciesTable
virtual autoPtr<Reaction<ReactionThermo> > clone
(
const speciesTable& species
) const
{
return autoPtr<Reaction<ReactionThermo> >
(
new Reaction<ReactionThermo>(*this, species)
);
}
// Selectors
//- Return a pointer to a new patchField created on freestore from input
static autoPtr<Reaction<ReactionThermo> > New
(
const speciesTable& species,
const HashPtrTable<ReactionThermo>& thermoDatabase,
Istream&
);
// Destructor
virtual ~Reaction()
{}
// Member Functions
// Access
inline const List<specieCoeffs>& lhs() const;
inline const List<specieCoeffs>& rhs() const;
// Reaction rate coefficients
//- Forward rate constant
virtual scalar kf
(
const scalar T,
const scalar p,
const scalarField& c
) const;
//- Reverse rate constant from the given forward rate constant
virtual scalar kr
(
const scalar kfwd,
const scalar T,
const scalar p,
const scalarField& c
) const;
//- Reverse rate constant.
// Note this evaluates the forward rate constant and divides by the
// equilibrium constant
virtual scalar kr
(
const scalar T,
const scalar p,
const scalarField& c
) const;
//- Write
virtual void write(Ostream&) const;
// Ostream Operator
friend Ostream& operator<< <ReactionThermo>
(
Ostream&,
const Reaction<ReactionThermo>&
);
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#include "ReactionI.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#ifdef NoRepository
# include "Reaction.C"
#endif
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| gpl-3.0 |
iblacksand/SimpleDiveMeets | node_modules/electron-packager/test/ignore.js | 5016 | 'use strict'
const common = require('../common')
const fs = require('fs-extra')
const ignore = require('../ignore')
const path = require('path')
const packager = require('..')
const test = require('ava')
const util = require('./_util')
function ignoreTest (t, opts, ignorePattern, ignoredFile) {
opts.dir = util.fixtureSubdir('basic')
if (ignorePattern) {
opts.ignore = ignorePattern
}
const targetDir = path.join(t.context.tempDir, 'result')
ignore.generateIgnores(opts)
return fs.copy(opts.dir, targetDir, {
dereference: false,
filter: ignore.userIgnoreFilter(opts)
}).then(() => fs.pathExists(path.join(targetDir, 'package.json')))
.then(exists => {
t.true(exists, 'The expected output directory should exist and contain files')
return fs.pathExists(path.join(targetDir, ignoredFile))
}).then(exists => t.false(exists, `Ignored file '${ignoredFile}' should not exist in copied directory`))
}
function ignoreOutDirTest (t, opts, distPath) {
opts.name = 'ignoreOutDirTest'
opts.dir = t.context.workDir
// we don't use path.join here to avoid normalizing
const outDir = opts.dir + path.sep + distPath
opts.out = outDir
return fs.copy(util.fixtureSubdir('basic'), t.context.workDir, {
dereference: true,
stopOnErr: true,
filter: file => { return path.basename(file) !== 'node_modules' }
}).then(() =>
// create out dir before packager (real world issue - when second run includes unignored out dir)
fs.ensureDir(outDir)
).then(() =>
// create file to ensure that directory will be not ignored because empty
fs.open(path.join(outDir, 'ignoreMe'), 'w')
).then(fd => fs.close(fd))
.then(() => packager(opts))
.then(() => fs.pathExists(path.join(outDir, common.generateFinalBasename(opts), util.generateResourcesPath(opts), 'app', path.basename(outDir))))
.then(exists => t.false(exists, 'Out dir must not exist in output app directory'))
}
function ignoreImplicitOutDirTest (t, opts) {
opts.name = 'ignoreImplicitOutDirTest'
opts.dir = t.context.workDir
delete opts.out
const testFilename = 'ignoreMe'
let previousPackedResultDir
return fs.copy(util.fixtureSubdir('basic'), t.context.workDir, {
dereference: true,
stopOnErr: true,
filter: file => { return path.basename(file) !== 'node_modules' }
}).then(() => {
previousPackedResultDir = path.join(opts.dir, `${common.sanitizeAppName(opts.name)}-linux-ia32`)
return fs.ensureDir(previousPackedResultDir)
}).then(() =>
// create file to ensure that directory will be not ignored because empty
fs.open(path.join(previousPackedResultDir, testFilename), 'w')
).then(fd => fs.close(fd))
.then(() => packager(opts))
.then(() => fs.pathExists(path.join(opts.dir, common.generateFinalBasename(opts), util.generateResourcesPath(opts), 'app', testFilename)))
.then(exists => t.false(exists, 'Out dir must not exist in output app directory'))
}
test('generateIgnores ignores the generated temporary directory only on Linux', t => {
const tmpdir = '/foo/bar'
const expected = path.join(tmpdir, 'electron-packager')
let opts = {tmpdir}
ignore.generateIgnores(opts)
// Array.prototype.includes is added (not behind a feature flag) in Node 6
if (process.platform === 'linux') {
t.false(opts.ignore.indexOf(expected) === -1, 'temporary dir in opts.ignore')
} else {
t.true(opts.ignore.indexOf(expected) === -1, 'temporary dir not in opts.ignore')
}
})
test('generateOutIgnores ignores all possible platform/arch permutations', (t) => {
const ignores = ignore.generateOutIgnores({name: 'test'})
t.is(ignores.length, util.allPlatformArchCombosCount)
})
util.testSinglePlatformParallel('ignore default test: .o files', ignoreTest, null, 'ignore.o')
util.testSinglePlatformParallel('ignore default test: .obj files', ignoreTest, null, 'ignore.obj')
util.testSinglePlatformParallel('ignore test: string in array', ignoreTest, ['ignorethis'],
'ignorethis.txt')
util.testSinglePlatformParallel('ignore test: string', ignoreTest, 'ignorethis', 'ignorethis.txt')
util.testSinglePlatformParallel('ignore test: RegExp', ignoreTest, /ignorethis/, 'ignorethis.txt')
util.testSinglePlatformParallel('ignore test: Function', ignoreTest,
file => file.match(/ignorethis/), 'ignorethis.txt')
util.testSinglePlatformParallel('ignore test: string with slash', ignoreTest, 'ignore/this',
path.join('ignore', 'this.txt'))
util.testSinglePlatformParallel('ignore test: only match subfolder of app', ignoreTest,
'electron-packager', path.join('electron-packager', 'readme.txt'))
util.testSinglePlatform('ignore out dir test', ignoreOutDirTest, 'ignoredOutDir')
util.testSinglePlatform('ignore out dir test: unnormalized path', ignoreOutDirTest,
'./ignoredOutDir')
util.testSinglePlatform('ignore out dir test: implicit path', ignoreImplicitOutDirTest)
| gpl-3.0 |
SpiritsThief/mifit | libs/chemlib/RefmacAtomTyper.cpp | 16064 | #include "RefmacType.h"
#include "RefmacAtomTyper.h"
#include "atom_util.h"
#include <chemlib/Monomer.h>
#include "mol_util.h"
using namespace std;
namespace chemlib
{
RefmacAtomTyper::RefmacAtomTyper(const Residue &res, const vector<Bond> &bonds)
: AtomTyper(res, bonds)
{
}
char*RefmacAtomTyper::AtomType(const MIAtom *a) const
{
std::string name = a->name();
const MIAtom *atom = m_mol.residues[0]->atomByName(name);
switch (atom->atomicnumber())
{
case 1: return TypeHydrogen(atom);
case 6: return TypeCarbon(atom);
case 7: return TypeNitrogen(atom);
case 8: return TypeOxygen(atom);
case 14: return TypeSilicon(atom);
case 15: return TypePhosphorus(atom);
case 16: return TypeSulfur(atom);
case 32: return TypeGermanium(atom);
case 33: return TypeArsenic(atom);
default: return TypeOther(atom);
}
}
char*RefmacAtomTyper::TypeHydrogen(const MIAtom *atom) const
{
if (atom->nabors().size())
{
return Name(RefmacType::H);
}
if (atom->nabors()[0]->atomicnumber() == 16) //Only one type for
{
return Name(RefmacType::HSH1); //H's bound to sulfur
}
char nabor_type[RefmacType::MAXLENGTH];
strncpy(nabor_type, AtomType(atom->nabors()[0]), RefmacType::MAXLENGTH);
switch (Index(nabor_type))
{
case RefmacType::CSP1:
return Name(RefmacType::H);
case RefmacType::C1:
return Name(RefmacType::HC1);
case RefmacType::C2:
return Name(RefmacType::HC2);
case RefmacType::CR1H:
return Name(RefmacType::HCR1);
case RefmacType::CR15:
return Name(RefmacType::HCR5);
case RefmacType::CR16:
return Name(RefmacType::HCR6);
case RefmacType::CH1:
return Name(RefmacType::HCH1);
case RefmacType::CH2:
return Name(RefmacType::HCH2);
case RefmacType::CH3:
return Name(RefmacType::HCH3);
case RefmacType::NC1:
return Name(RefmacType::HNC1);
case RefmacType::NC2:
return Name(RefmacType::HNC2);
case RefmacType::NH1:
return Name(RefmacType::HNH1);
case RefmacType::NH2:
return Name(RefmacType::HNH2);
case RefmacType::NR15:
return Name(RefmacType::HNR5);
case RefmacType::NR16:
return Name(RefmacType::HNR6);
case RefmacType::NT1:
return Name(RefmacType::HNT1);
case RefmacType::NT2:
return Name(RefmacType::HNT2);
case RefmacType::NT3:
return Name(RefmacType::HNT3);
case RefmacType::OH1:
return Name(RefmacType::HOH1);
case RefmacType::OH2:
return Name(RefmacType::HOH2);
case RefmacType::OHA:
return Name(RefmacType::HOHA);
case RefmacType::OHB:
return Name(RefmacType::HOHB);
case RefmacType::OHC:
return Name(RefmacType::HOHC);
default:
return Name(RefmacType::H);
}
}
char*RefmacAtomTyper::TypeCarbon(const MIAtom *atom) const
{
int n_hydrogen = GetNumHydrogens(*atom);
int naBonds = CountAromaticBonds(*atom, m_mol.bonds);
switch (atom->hybrid())
{
case 1:
switch (n_hydrogen)
{
case 0:
return Name(RefmacType::CSP);
case 1:
return Name(RefmacType::CSP1);
}
case 2:
if (naBonds == 2 && atom->smallest_aromatic_ring() == 6)
{
switch (n_hydrogen)
{
case 0:
return Name(RefmacType::CR6);
case 1:
return Name(RefmacType::CR16);
}
}
if (naBonds == 2 && atom->smallest_aromatic_ring() == 5)
{
switch (n_hydrogen)
{
case 0:
return Name(RefmacType::CR5);
case 1:
return Name(RefmacType::CR15);
}
}
if (naBonds == 3 && AtSixSixFusion(*atom, m_mol.bonds))
{
return Name(RefmacType::CR66);
}
if (naBonds == 3 && AtFiveSixFusion(*atom, m_mol.bonds))
{
return Name(RefmacType::CR55);
}
if (naBonds == 3 && AtFiveFiveFusion(*atom, m_mol.bonds))
{
return Name(RefmacType::CR56);
}
switch (n_hydrogen)
{
case 0:
return Name(RefmacType::C);
case 1:
return Name(RefmacType::C1);
case 2:
return Name(RefmacType::C2);
}
case 3:
switch (n_hydrogen)
{
case 0:
return Name(RefmacType::CT);
case 1:
return Name(RefmacType::CH1);
case 2:
return Name(RefmacType::CH2);
case 3:
return Name(RefmacType::CH3);
default:
return Name(RefmacType::CH3); //Carbon in methane ends up here
}
} //switch(atom->hybrid)
return Name(RefmacType::C);
} //TypeCarbon() function
char*RefmacAtomTyper::TypeNitrogen(const MIAtom *atom) const
{
int n_hydrogen = GetNumHydrogens(*atom);
int degree = atom->nabors().size() + atom->hcount();
switch (atom->hybrid())
{
case 1:
return Name(RefmacType::NS);
case 2:
if (atom->smallest_aromatic_ring() == 6 && n_hydrogen == 1)
{
return Name(RefmacType::NR16);
}
if (atom->smallest_aromatic_ring() == 6 && degree == 3)
{
return Name(RefmacType::NR6);
}
if (atom->smallest_aromatic_ring() == 6 && degree == 2)
{
return Name(RefmacType::NRD6);
}
if (atom->smallest_aromatic_ring() == 5 && n_hydrogen == 1)
{
return Name(RefmacType::NR15);
}
if (atom->smallest_aromatic_ring() == 5 && degree == 3)
{
return Name(RefmacType::NR5);
}
if (atom->smallest_aromatic_ring() == 5 && degree == 2)
{
return Name(RefmacType::NRD5);
}
switch (n_hydrogen)
{
case 0:
return Name(RefmacType::N);
case 1:
return Name(RefmacType::NH1);
case 2:
return Name(RefmacType::NH2);
}
case 3:
switch (n_hydrogen)
{
case 0:
return Name(RefmacType::NT);
case 1:
return Name(RefmacType::NT1);
case 2:
return Name(RefmacType::NT2);
case 3:
return Name(RefmacType::NT3);
default:
return Name(RefmacType::NT3); //ammonium ends up here
}
} //switch(atom->hybrid)
return Name(RefmacType::N);
} //TypeNitrogen() function
char*RefmacAtomTyper::TypeOxygen(const MIAtom *atom) const
{
int n_hydrogen = GetNumHydrogens(*atom);
int hvy_degree = atom->nabors().size() + atom->hcount() - n_hydrogen; //# of nonhydrogen nabors
if (hvy_degree == 1 && atom->nabors()[0]->atomicnumber() == 15)
{
return Name(RefmacType::OP);
}
else if (hvy_degree == 1 && atom->nabors()[0]->atomicnumber() == 16)
{
return Name(RefmacType::OS);
}
else if (hvy_degree == 1 && atom->nabors()[0]->atomicnumber() == 5)
{
return Name(RefmacType::OB);
}
switch (atom->hybrid())
{
case 2:
return Name(RefmacType::O);
case 3:
switch (n_hydrogen)
{
case 0:
return Name(RefmacType::O2);
case 1:
return Name(RefmacType::OH1);
case 2:
return Name(RefmacType::OH2);
}
} //switch(atom->hybrid)
return Name(RefmacType::O);
} //TypeOxygen() function
char*RefmacAtomTyper::TypeSilicon(const MIAtom *atom) const
{
switch (atom->hybrid())
{
case 3:
return Name(RefmacType::SI);
default: return Name(RefmacType::SI1);
} //switch(atom->hybrid)
} //TypeSilicon() function
char*RefmacAtomTyper::TypePhosphorus(const MIAtom *atom) const
{
switch (atom->hybrid())
{
case 3:
return Name(RefmacType::P);
default: return Name(RefmacType::P1);
} //switch(atom->hybrid)
} //TypePhosphorus() function
char*RefmacAtomTyper::TypeSulfur(const MIAtom *atom) const
{
int n_hydrogen = GetNumHydrogens(*atom);
if (n_hydrogen > 0) // Mercapto/sulfhydryls/thiols
{
return Name(RefmacType::SH1);
}
int degree = atom->nabors().size();
if (degree == 1 && atom->hybrid() == 2) //Thiocarbonyls, isothiocyanates
{
return Name(RefmacType::S1);
}
if (degree == 2 && atom->hybrid() == 3) //Sulfides, disulfides
{
return Name(RefmacType::S2);
}
if (degree == 3) //Sulfoxides, sulfur trioxide
{
return Name(RefmacType::S3);
}
if (degree == 4 && atom->hybrid() == 3) //Sulfites, sulfonamides, etc.
{
return Name(RefmacType::ST);
}
return Name(RefmacType::S); //Catch-all for sulfur with no
} //hydrogen, including sulfates
//I haven't found documentation for this. Rather it's inferred by analogy
//with silicon.
char*RefmacAtomTyper::TypeGermanium(const MIAtom *atom) const
{
switch (atom->hybrid())
{
case 3:
return Name(RefmacType::GE);
default: return Name(RefmacType::GE1);
}
}
//I haven't found documentation for this. Rather it's inferred by analogy
//with silicon.
char*RefmacAtomTyper::TypeArsenic(const MIAtom *atom) const
{
switch (atom->hybrid())
{
case 3:
return Name(RefmacType::AS);
default: return Name(RefmacType::AS1);
}
}
char*RefmacAtomTyper::TypeOther(const MIAtom *atom) const
{
static char per_tab[NELEMENTS+1][RefmacType::MAXLENGTH+1] =
{
"DUM",
"H", "HE",
"LI", "BE", "B", "C", "N", "O", "F", "NE",
"NA", "MG", "AL", "SI", "P", "S", "CL", "AR",
"K", "CA", "SC", "TI", "V", "CR", "MN", "FE", "CO",
"NI", "CU", "ZN", "GA", "GE", "AS", "SE", "BR", "KR",
"RB", "SR", "Y", "ZR", "NB", "MO", "TC", "RU", "RH",
"PD", "AG", "CD", "IN", "SN", "SB", "TE", "I", "XE",
"CS", "BA", "LA",
"CE", "PR", "ND", "DUM", "SM", "EU", "GD", "TB", "DY",
"HO", "ER", "TM", "YB", "LU",
"HF", "TA", "W", "RE", "OSE", "IR",
"PT", "AU", "HG", "TL", "PB", "BI", "PO", "AT", "RN",
"DUM", "DUM", "AC",
"TH", "PA", "U", "NP",
};
return per_tab[atom->atomicnumber()];
}
char*RefmacAtomTyper::Name(unsigned int index) const
{
static char types[RefmacType::MAXTYPE][RefmacType::MAXLENGTH+1] =
{
"DUM",
"CSP", "CSP1", "C", "C1", "C2", "CR1", "CR2", "CR1H", //1-19 Carbon
"CR15", "CR5", "CR56", "CR55", "CR16", "CR6", "CR66",
"CH1", "CH2", "CH3", "CT",
"NS", "N", "NC1", "NH1", "NC2", "NH2", "NC3", "NT", //20-41 Nitrogen
"NT1", "NT2", "NT3", "NPA", "NPB", "NR5", "NR15",
"NRD5", "NR56", "NR55", "NR6", "NR66", "NR16", "NRD6",
"OS", "O", "O2", "OH1", "OH2", "OHA", "OHB", "OHC", //42-53 Oxygen
"OC2", "OC", "OP", "OB",
"P", "P1", "PS", //54-56 Phosphorus
"S", "S3", "S2", "S1", "ST", "SH1", //57-62 Sulfur
"H", "HCH", "HCH1", "HCH2", "HCH3", "HCR1", "HC1", //63-87 Hydrogen
"HC2", "HCR5", "HCR6", "HNC1", "HNC2", "HNH1", "HNH2",
"HNR5", "HNR6", "HNT1", "HNT2", "HNT3", "HOH1", "HOH2",
"HOHA", "HOHB", "HOHC", "HSH1",
"SI", "SI1", "GE", "GE1", "SN", "PB", //88-93 Group 14
"LI", "NA", "K", "RB", "CS", //94-98 Group 1
"BE", "MG", "CA", "SR", "BA", //99-103 Group 2
"SC", "Y", "LA", "CE", "PR", "ND", //104-109 Group 3
"SM", "EU", "GD", "TB", "DY", "HO", "ER", "TM", "YB", "LU", //110-119 Lanthanides
"AC", "TH", "PA", "U", "NP", //120-124 Actinides
"TI", "ZR", "HF", //125-127 Group 4
"V", "NB", "TA", //128-130 Group 5
"CR", "MO", "W", //131-133 Group 6
"MN", "TC", "RE", //134-136 Group 7
"FE", "RU", "OSE", //137-139 Group 8
"CO", "RH", "IR", //140-142 Group 9
"NI", "PD", "PT", //143-145 Group 10
"CU", "AG", "AU", //146-148 Group 11
"ZN", "CD", "HG", //149-151 Group 12
"B", "AL", "GA", "IN", "TL", //152-156 Group 13
"AS", "AS1", "SB", "BI", //157-160 Group 15
"SE", "TE", "PO", //161-163 Group 16
"F", "CL", "BR", "I", "AT", //164-168 Halogens
"HE", "NE", "AR", "KR", "XE", "RN" //169-174 Noble Gases
};
return types[index];
}
unsigned int RefmacAtomTyper::Index(const char *name) const
{
static char types[RefmacType::MAXTYPE][RefmacType::MAXLENGTH+1] =
{
"DUM",
"CSP", "CSP1", "C", "C1", "C2", "CR1", "CR2", "CR1H", //1-19 Carbon
"CR15", "CR5", "CR56", "CR55", "CR16", "CR6", "CR66",
"CH1", "CH2", "CH3", "CT",
"NS", "N", "NC1", "NH1", "NC2", "NH2", "NC3", "NT", //20-41 Nitrogen
"NT1", "NT2", "NT3", "NPA", "NPB", "NR5", "NR15",
"NRD5", "NR56", "NR55", "NR6", "NR66", "NR16", "NRD6",
"OS", "O", "O2", "OH1", "OH2", "OHA", "OHB", "OHC", //42-53 Oxygen
"OC2", "OC", "OP", "OB",
"P", "P1", "PS", //54-56 Phosphorus
"S", "S3", "S2", "S1", "ST", "SH1", //57-62 Sulfur
"H", "HCH", "HCH1", "HCH2", "HCH3", "HCR1", "HC1", //63-87 Hydrogen
"HC2", "HCR5", "HCR6", "HNC1", "HNC2", "HNH1", "HNH2",
"HNR5", "HNR6", "HNT1", "HNT2", "HNT3", "HOH1", "HOH2",
"HOHA", "HOHB", "HOHC", "HSH1",
"SI", "SI1", "GE", "GE1", "SN", "PB", //88-93 Group 14
"LI", "NA", "K", "RB", "CS" //94-98 Group 1
"BE", "MG", "CA", "SR", "BA", //99-103 Group 2
"SC", "IN", "LA", "CE", "PR", "ND" //104-109 Group 3
"SM", "EU", "GD", "TB", "DY", "HO", "ER", "TM", "YB", "LU" //110-119 Lanthanides
"AC", "TH", "PA", "U", "NP", //120-124 Actinides
"TI", "ZR", "HF", //125-127 Group 4
"V", "NB", "TA", //128-130 Group 5
"CR", "MO", "W", //131-133 Group 6
"MN", "TC", "RE", //134-136 Group 7
"FE", "RU", "OSE", //137-139 Group 8
"CO", "RH", "IR", //140-142 Group 9
"NI", "PD", "PT", //143-145 Group 10
"CU", "AG", "AU", //146-148 Group 11
"ZN", "CD", "HG", //149-151 Group 12
"B", "AL", "GA", "IN", "TL", //152-156 Group 13
"AS", "AS1", "SB", "BI", //157-160 Group 15
"SE", "TE", "PO", //161-163 Group 16
"F", "CL", "BR", "I", "AT", //164-168 Halogens
"HE", "NE", "AR", "KR", "XE", "RN" //169-174 Noble Gases
};
for (unsigned int i = 0; i < RefmacType::MAXTYPE; ++i)
{
if (!strncmp(name, types[i], RefmacType::MAXLENGTH))
{
return i;
}
}
return 0;
}
}
| gpl-3.0 |
nishanttotla/predator | cpachecker/src/org/sosy_lab/cpachecker/cfa/types/Type.java | 1304 | /*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2014 Dirk Beyer
* 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.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.cfa.types;
public interface Type {
/**
* Return a string representation of a variable declaration with a given name
* and this type.
*
* Example:
* If this type is array of int, and we call <code>toASTString("foo")</code>,
* the result is <pre>int foo[]</pre>.
*
* @param declarator The name of the variable to declare.
* @return A string representation of this type.
*/
public String toASTString(String declarator);
}
| gpl-3.0 |
enormandeau/Scripts | 00_deprecated/fasta_qual_to_fastq.py | 888 | #!/usr/bin/env python
"""Convert a FASTA and a QUAL file from Roche 454 sequencing in a FASTQ file.
Usage:
%program <input_file> <start_marker> <stop_marker> <output_file>"""
import sys
import re
try:
from Bio import SeqIO
except:
print "This program requires the Biopython library"
sys.exit(0)
try:
quality_file = sys.argv[1] # 454 output quality file <filename>.qual
fasta_file = sys.argv[2] # 454 output fasta file : <filename>.fna
output_file = sys.argv[3] # Out-put file with FASTQ format
except:
print __doc__
sys.exit(0)
reads = SeqIO.to_dict(SeqIO.parse(open(fasta_file), "fasta"))
with open(output_file, "w") as f:
for rec in SeqIO.parse(open(quality_file), "qual"):
reads[rec.id].letter_annotations["phred_quality"] = \
rec.letter_annotations["phred_quality"]
f.write(reads[rec.id].format("fastq"))
| gpl-3.0 |
adjivas/mouse | app/script/mouscreen/selector.js | 2141 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* selector.js :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adjivas <adjivas@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/09/15 10:02:36 by adjivas #+# #+# */
/* Updated: 2014/09/15 10:02:36 by adjivas ### ########.fr */
/* */
/* ************************************************************************** */
'use strict';
/*
** The Selector's class is call for move the text's cursor.
*/
var Selector = {
'shift': false,
'interval': undefined,
'door': function (key) {
var method = (Selector.shift ? 'shell' : 'tap');
Door.send({'class': 'keyboard', 'method': method}, {'key': key});
},
'move': function (arg) {
/* The function does a conversion from degret to direction,
and requests the server for move the text's selector. */
var key = [
['right', '+{RIGHT}', (45 < Pointer.degret && Pointer.degret <= 135)],
['down' , '+{DOWN}' , (135 < Pointer.degret && Pointer.degret <= 225)],
['left' , '+{LEFT}' , (225 < Pointer.degret && Pointer.degret <= 315)],
['up' , '+{UP}' , true]
];
var count = -1;
while (key[++count])
if (key[count][2])
break ;
key = key[count][Selector.shift | 0];
Selector.door(key);
},
'action': function (number) {
/* The function starts or stops the move. */
var speed = (typeof number !== 'number' ? Selector.speed : number);
if (Selector.interval !== undefined)
Selector.interval = window.clearInterval(Selector.interval);
else
Selector.interval = window.setInterval(Selector.move, speed);
}
};
| gpl-3.0 |
sinfulspartan/Hackathon--InfoRep | Cmfcmf/OpenWeatherMap/WeatherHistory.php | 3452 | <?php
/**
* OpenWeatherMap-PHP-API — A php api to parse weather data from http://www.OpenWeatherMap.org .
*
* @license MIT
*
* Please see the LICENSE file distributed with this source code for further
* information regarding copyright and licensing.
*
* Please visit the following links to read about the usage policies and the license of
* OpenWeatherMap before using this class:
*
* @see http://www.OpenWeatherMap.org
* @see http://www.OpenWeatherMap.org/terms
* @see http://openweathermap.org/appid
*/
namespace Cmfcmf\OpenWeatherMap;
use Cmfcmf\OpenWeatherMap\Util\City;
/**
* Class WeatherHistory.
*/
class WeatherHistory implements \Iterator
{
/**
* The city object. IMPORTANT: Not all values will be set
*
* @var Util\City
*/
public $city;
/**
* The time needed to calculate the request data.
*
* @var float
*/
public $calctime;
/**
* An array of {@link WeatherHistory} objects.
*
* @var array
*
* @see WeatherForecast The WeatherForecast class.
*/
private $histories;
/**
* @internal
*/
private $position = 0;
public function __construct($weatherHistory, $query)
{
if (isset($weatherHistory['list'][0]['city'])) {
$country = $weatherHistory['list'][0]['city']['country'];
$population = $weatherHistory['list'][0]['city']['population'];
} else {
$country = null;
$population = null;
}
$this->city = new City(
$weatherHistory['city_id'],
(is_string($query)) ? $query : null,
(isset($query['lat'])) ? $query['lat'] : null,
(isset($query['lon'])) ? $query['lon'] : null,
$country,
$population
);
$this->calctime = $weatherHistory['calctime'];
$utctz = new \DateTimeZone('UTC');
foreach ($weatherHistory['list'] as $history) {
if (isset($history['rain'])) {
$units = array_keys($history['rain']);
} else {
$units = array(0 => null);
}
$this->histories[] = new History(
$this->city,
$history['weather'][0],
array(
'now' => $history['main']['temp'],
'min' => $history['main']['temp_min'],
'max' => $history['main']['temp_max']
),
$history['main']['pressure'],
$history['main']['humidity'],
$history['clouds']['all'],
isset($history['rain']) ? array(
'val' => $history['rain'][($units[0])],
'unit' => $units[0]) : null,
$history['wind'],
\DateTime::createFromFormat('U', $history['dt'], $utctz));
}
}
/**
* @internal
*/
public function rewind()
{
$this->position = 0;
}
/**
* @internal
*/
public function current()
{
return $this->histories[$this->position];
}
/**
* @internal
*/
public function key()
{
return $this->position;
}
/**
* @internal
*/
public function next()
{
++$this->position;
}
/**
* @internal
*/
public function valid()
{
return isset($this->histories[$this->position]);
}
}
| gpl-3.0 |
luben93/Navi | NaviMobile/Assets/NaviMobileScripts/PoseManager.cs | 8477 | #if !UNITY_IOS
/*
* This file is part of Navi.
* Copyright 2015 Vasanth Mohan. All Rights Reserved.
*
* Navi 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.
*
* Navi 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 Navi. If not, see <http://www.gnu.org/licenses/>.
*/
using UnityEngine;
using System.Collections;
using Tango;
using System;
/// <summary>
/// This class extends TransformManagerInterface and is responsbile for informing the system of the current pose of the
/// device. In this case, it uses the TangoSDK to set rotational and positional data.
/// </summary>
public class PoseManager : TransformManagerInterface , ITangoPose {
private TangoApplication m_tangoApplication; // Instance for Tango Client
private Vector3 m_tangoPosition; // Position from Pose Callback
private Quaternion m_tangoRotation; // Rotation from Pose Callback
[HideInInspector]
public float m_metersToWorldUnitsScaler = 1.0f;
private Vector3 m_zeroPosition; //the physical position of the device when reset
private Quaternion m_zeroRotation; //the physical rotation of the device when reset
private Vector3 m_startPosition; // the position the device starts at (0,0,0)
private Quaternion m_startRotation; //the rotation the device starts at (0,0,0,0)
private float m_movementScale = 10.0f; //the translation between physical and virtual movement
private TangoPoseData prevPose = new TangoPoseData(); //past pose; used for interpolation
private TangoPoseData currPose = new TangoPoseData(); //current pose
private float unityTimestampOffset = 0;
/// <summary>
/// Initalize variables
/// </summary>
void Awake(){
base.Awake ();
m_startPosition = transform.position;
m_startRotation = transform.rotation;
ComputeTransformUsingPose (out m_zeroPosition, out m_zeroRotation, currPose);
}
/// <summary>
/// Set more variables once scene has loaded and all scripts are ready
/// </summary>
void Start ()
{
Application.targetFrameRate = 60;
// Initialize some variables
m_tangoRotation = Quaternion.identity;
m_tangoPosition = Vector3.zero;
m_startPosition = transform.position;
m_tangoApplication = FindObjectOfType<TangoApplication>();
if(m_tangoApplication != null)
{
// Request Tango permissions
m_tangoApplication.RegisterPermissionsCallback(PermissionsCallback);
m_tangoApplication.RequestNecessaryPermissionsAndConnect();
m_tangoApplication.Register(this);
}
else
{
Debug.Log("No Tango Manager found in scene.");
}
}
/// <summary>
/// Clean up when app closes
/// </summary>
void OnDestroy(){
#if UNITY_EDITOR
return;
#endif
base.OnDestroy ();
m_tangoApplication.Unregister (this);
}
/// <summary>
/// Gets permission of Project Tango to use Motion Control
/// </summary>
/// <param name="success">Whether we are given permission</param>
private void PermissionsCallback(bool success)
{
if(success)
{
m_tangoApplication.InitApplication(); // Initialize Tango Client
m_tangoApplication.InitProviders(string.Empty); // Initialize listeners
m_tangoApplication.ConnectToService(); // Connect to Tango Service
}
else
{
#if UNITY_ANDROID
AndroidHelper.ShowAndroidToastMessage("Motion Tracking Permissions Needed", true);
#endif
}
}
/// <summary>
/// Updates the virtual device position and rotation from interpolation data
/// </summary>
/// <param name="t">The time between each poll of the sensor data</param>
void UpdateUsingInterpolatedPose(double t) {
float dt = (float)((t - prevPose.timestamp)/(currPose.timestamp - prevPose.timestamp));
//restrict this, so it isn't doesn't swing out of control
if(dt > 4)
dt = 4;
Vector3 currPos = new Vector3();
Vector3 prevPos = new Vector3();
Quaternion currRot = new Quaternion();
Quaternion prevRot = new Quaternion();
ComputeTransformUsingPose(out currPos, out currRot, currPose);
ComputeTransformUsingPose(out prevPos, out prevRot, prevPose);
//We actually do not want to zero the rotation, because that will need to awkard rotations on the sphere
transform.rotation = m_startRotation*Quaternion.Inverse(m_zeroRotation)*Quaternion.Slerp (prevRot, currRot, dt);
//transform.rotation = m_startRotation*Quaternion.Slerp (prevRot, currRot, dt);
transform.position = m_startRotation*(Vector3.Lerp(prevPos, currPos, dt) - m_zeroPosition)*m_metersToWorldUnitsScaler + m_startPosition;
}
/// <summary>
/// Computes position and rotation based on sensor data from TangoSDK
/// </summary>
/// <param name="position">The output position from the calculation</param>
/// <param name="rot">The output rotation from the calculation</param>
/// <param name="pose">The input pose data</param>
void ComputeTransformUsingPose(out Vector3 position, out Quaternion rot, TangoPoseData pose) {
position = new Vector3((float)pose.translation [0],
(float)pose.translation [2],
(float)pose.translation [1]);
rot = new Quaternion((float)pose.orientation [0],
(float)pose.orientation [2], // these rotation values are swapped on purpose
(float)pose.orientation [1],
(float)pose.orientation [3]);
// This rotation needs to be put into Unity coordinate space.
Quaternion axisFix = Quaternion.Euler(-rot.eulerAngles.x,
-rot.eulerAngles.z,
rot.eulerAngles.y);
Quaternion rotationFix = Quaternion.Euler(90.0f, 0.0f, 0.0f);
rot = rotationFix * axisFix;
}
/// <summary>
/// Makes a deep copy of the sensor data
/// </summary>
/// <param name="other">The object we would like to copy</param>
private TangoPoseData DeepCopyTangoPose(TangoPoseData other)
{
TangoPoseData poseCopy = new TangoPoseData();
poseCopy.version = other.version;
poseCopy.timestamp = other.timestamp;
poseCopy.orientation = other.orientation;
poseCopy.translation = other.translation;
poseCopy.status_code = other.status_code;
poseCopy.framePair.baseFrame = other.framePair.baseFrame;
poseCopy.framePair.targetFrame = other.framePair.targetFrame;
poseCopy.confidence = other.confidence;
poseCopy.accuracy = other.accuracy;
return poseCopy;
}
/// <summary>
/// Updates instance pose data based on new data point
/// </summary>
/// <param name="pose">The pose data</param>
private void UpdateInterpolationData(TangoPoseData pose) {
prevPose = currPose;
// We need to make sure to deep copy the pose because it is
// only guaranteed to be valid for the duration of our callback.
currPose = DeepCopyTangoPose(pose);
float timestampSmoothing = 0.95f;
if(unityTimestampOffset < float.Epsilon)
unityTimestampOffset = (float)pose.timestamp - Time.realtimeSinceStartup;
else
unityTimestampOffset = timestampSmoothing*unityTimestampOffset + (1-timestampSmoothing)*((float)pose.timestamp - Time.realtimeSinceStartup);
}
/// <summary>
/// Handle the callback sent by the Tango Service
/// when a new pose is sampled.
/// </summary>
/// <param name="callbackContext">Callback context.</param>
/// <param name="pose">Pose.</param>
public void OnTangoPoseAvailable(Tango.TangoPoseData pose)
{
// The callback pose is for device with respect to start of service pose.
if (pose.framePair.baseFrame == TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE &&
pose.framePair.targetFrame == TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE)
{
if(pose.status_code == TangoEnums.TangoPoseStatusType.TANGO_POSE_VALID)
{
UpdateInterpolationData(pose);
if(unityTimestampOffset > float.Epsilon) {
UpdateUsingInterpolatedPose(Time.realtimeSinceStartup + unityTimestampOffset);
}
}
}
}
/// <summary>
/// How to reset the position of the device
/// </summary>
public override void Reset() {
ComputeTransformUsingPose (out m_zeroPosition, out m_zeroRotation, currPose);
}
}
#endif | gpl-3.0 |
OpenCFD/OpenFOAM-1.7.x | src/OpenFOAM/meshes/meshShapes/cellShape/cellShapeIO.C | 3974 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd.
\\/ 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/>.
Description
Reads a cellShape
\*---------------------------------------------------------------------------*/
#include "cellShape.H"
#include "token.H"
#include "cellModeller.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
Istream& operator>>(Istream& is, cellShape& s)
{
bool readEndBracket = false;
// Read the 'name' token for the symbol
token t(is);
if (t.isPunctuation())
{
if (t.pToken() == token::BEGIN_LIST)
{
readEndBracket = true;
is >> t;
}
else
{
FatalIOErrorIn("operator>>(Istream&, cellShape& s)", is)
<< "incorrect first token, expected '(', found "
<< t.info()
<< exit(FatalIOError);
}
}
// it is allowed to have either a word or a number describing the model
if (t.isLabel())
{
s.m = cellModeller::lookup(int(t.labelToken()));
}
else if (t.isWord())
{
s.m = cellModeller::lookup(t.wordToken());
}
else
{
FatalIOErrorIn("operator>>(Istream& is, cellShape& s)", is)
<< "Bad type of token for cellShape symbol " << t.info()
<< exit(FatalIOError);
return is;
}
// Check that a model was found
if (!s.m)
{
FatalIOErrorIn("operator>>(Istream& is, cellShape& s)", is)
<< "CellShape has unknown model " << t.info()
<< exit(FatalIOError);
return is;
}
// Read the geometry labels
is >> static_cast<labelList&>(s);
if (readEndBracket)
{
// Read end)
is.readEnd("cellShape");
}
return is;
}
Ostream& operator<<(Ostream& os, const cellShape & s)
{
// Write beginning of record
os << token::BEGIN_LIST;
// Write the list label for the symbol (ONE OR THE OTHER !!!)
os << (s.m)->index() << token::SPACE;
// Write the model name instead of the label (ONE OR THE OTHER !!!)
// os << (s.m)->name() << token::SPACE;
// Write the geometry
os << static_cast<const labelList&>(s);
// End of record
os << token::END_LIST;
return os;
}
#if defined (__GNUC__)
template<>
#endif
Ostream& operator<<(Ostream& os, const InfoProxy<cellShape>& ip)
{
const cellShape& cs = ip.t_;
if (!(&cs.model()))
{
os << " cellShape has no model!\n";
}
else
{
os << cs.model().info() << endl;
}
os << "\tGeom:\tpoint\tlabel\txyz\n";
forAll(cs, i)
{
os << "\t\t" << i << "\t" << cs[i] << endl;
}
return os;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// ************************************************************************* //
| gpl-3.0 |
MauHernandez/cyclope | cyclope/apps/medialibrary/frontend_views.py | 3039 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010-2013 Código Sur Sociedad Civil.
# All rights reserved.
#
# This file is part of Cyclope.
#
# Cyclope 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.
#
# Cyclope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.utils.translation import ugettext_lazy as _
from cyclope.core import frontend
from cyclope import views
from models import *
class MediaDetail(frontend.FrontendView):
name='detail'
is_default = True
is_instance_view = True
is_content_view = True
params = {'template_object_name': 'media'}
def get_response(self, request, req_context, options, content_object):
return views.object_detail(request, req_context, content_object, **self.params)
class PictureDetail(MediaDetail):
"""Detail view of a Picture.
"""
verbose_name=_('detailed view of the selected Picture')
frontend.site.register_view(Picture, PictureDetail)
class SoundTrackDetail(MediaDetail):
"""Detail view of an SoundTrack.
"""
verbose_name=_('detailed view of the selected Audio Track')
frontend.site.register_view(SoundTrack, SoundTrackDetail)
class MovieClipDetail(MediaDetail):
"""Detail view of a MovieClip.
"""
verbose_name=_('detailed view of the selected Movie Clip')
frontend.site.register_view(MovieClip, MovieClipDetail)
class DocumentDetail(MediaDetail):
"""Detail view of a Document.
"""
verbose_name=_('detailed view of the selected Document')
frontend.site.register_view(Document, DocumentDetail)
class RegularFileDetail(MediaDetail):
"""Detail view of a regular file.
"""
verbose_name=_('detailed view of the selected File')
frontend.site.register_view(RegularFile, RegularFileDetail)
class ExternalContentDetail(MediaDetail):
"""Detail view of external content.
"""
verbose_name=_('detailed view of the selected External Content')
frontend.site.register_view(ExternalContent, ExternalContentDetail)
class FlashMovieDetail(MediaDetail):
"""Detail view of a Flash Movie.
"""
verbose_name=_('detailed view of the selected Flash Movie')
def get_response(self, request, req_context, options, content_object):
p = content_object.flash.url_full
i = p.rfind("/")+1
base = p[:i]
req_context.update({'url_base': base})
return views.object_detail(request, req_context, content_object,
**self.params)
frontend.site.register_view(FlashMovie, FlashMovieDetail)
| gpl-3.0 |
bjornsturmberg/EMUstack | examples/simo_031-1D_grating-2_inclusions.py | 4681 | """
simo_030-1D_grating.py is a simulation example for EMUstack.
Copyright (C) 2015 Bjorn Sturmberg
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/>.
"""
"""
Increase complexity of grating to contain 2 inclusions that are interleaved.
"""
import time
import datetime
import numpy as np
import sys
from multiprocessing import Pool
sys.path.append("../backend/")
import objects
import materials
import plotting
from stack import *
start = time.time()
# Remove results of previous simulations.
plotting.clear_previous()
################ Simulation parameters ################
# Select the number of CPUs to use in simulation.
num_cores = 2
################ Light parameters #####################
wl_1 = 400
wl_2 = 800
no_wl_1 = 2
wavelengths = np.linspace(wl_1, wl_2, no_wl_1)
light_list = [objects.Light(wl, max_order_PWs = 5, theta = 0.0, phi = 0.0) for wl in wavelengths]
# The period must be consistent throughout a simulation!
period = 300
# Define each layer of the structure
# We need to inform EMUstack at this point that all layers in the stack will
# be at most be periodic in one dimension (i.e. there are no '2D_arrays's).
superstrate = objects.ThinFilm(period, height_nm = 'semi_inf', world_1d=True,
material = materials.Air)
substrate = objects.ThinFilm(period, height_nm = 'semi_inf', world_1d=True,
material = materials.Air)
# Define 1D grating that is periodic in x and contains 2 interleaved inclusions.
# Inclusion_a is in the center of the unit cell. Inclusion_b has diameter
# diameter2 and can be of a different refractive index and by default the
# centers of the inclusions are seperated by period/2.
# See Fortran Backends section of tutorial for more details.
grating = objects.NanoStruct('1D_array', period, int(round(0.15*period)),
diameter2 = int(round(0.27*period)), height_nm = 2900,
background = materials.Material(1.46 + 0.0j), inclusion_a = materials.Material(5.0 + 0.0j),
inclusion_b = materials.Material(3.0 + 0.0j),
loss = True, lc_bkg = 0.0051)
# To dictate the seperation of the inclusions set the Keyword Arg small_space to the
# distance (in nm) between between the inclusions edges.
grating_2 = objects.NanoStruct('1D_array', period, int(round(0.15*period)),
diameter2 = int(round(0.27*period)), small_space = 50, height_nm = 2900,
background = materials.Material(1.46 + 0.0j), inclusion_a = materials.Material(5.0 + 0.0j),
inclusion_b = materials.Material(3.0 + 0.0j),
loss = True, lc_bkg = 0.0051)
def simulate_stack(light):
################ Evaluate each layer individually ##############
sim_superstrate = superstrate.calc_modes(light)
sim_grating = grating.calc_modes(light)
sim_substrate = substrate.calc_modes(light)
###################### Evaluate structure ######################
""" Now define full structure. Here order is critical and
stack list MUST be ordered from bottom to top!
"""
# For demonstration we only simulate one of the gratings defined above.
stack = Stack((sim_substrate, sim_grating, sim_superstrate))
stack.calc_scat(pol = 'TE')
return stack
pool = Pool(num_cores)
stacks_list = pool.map(simulate_stack, light_list)
# Save full simo data to .npz file for safe keeping!
np.savez('Simo_results', stacks_list=stacks_list)
######################## Post Processing ########################
# The total transmission should be zero.
plotting.t_r_a_plots(stacks_list)
######################## Wrapping up ########################
print('\n*******************************************')
# Calculate and record the (real) time taken for simulation,
elapsed = (time.time() - start)
hms = str(datetime.timedelta(seconds=elapsed))
hms_string = 'Total time for simulation was \n \
%(hms)s (%(elapsed)12.3f seconds)'% {
'hms' : hms,
'elapsed' : elapsed, }
print(hms_string)
print('*******************************************')
print('')
# and store this info.
python_log = open("python_log.log", "w")
python_log.write(hms_string)
python_log.close()
| gpl-3.0 |
yeppoint/oneplus | upload/catalog/language/chinese/amazonus/order.php | 356 | <?php
/**
* $Author: http://www.opencartchina.com
**/
$_['paid_on_amazonus_text'] = 'Amazon US 支付';
$_['shipping_text'] = '配送';
$_['shipping_tax_text'] = '配送税率';
$_['gift_wrap_text'] = '包装';
$_['gift_wrap_tax_text'] = '包装税率';
$_['sub_total_text'] = '小计';
$_['tax_text'] = '税率';
$_['total_text'] = '总计'; | gpl-3.0 |
roastedlasagna/mo-food-mod | src/com/watabou/mofoodpd/items/armor/MailArmor.java | 1084 | /*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.watabou.mofoodpd.items.armor;
import com.watabou.mofoodpd.sprites.ItemSpriteSheet;
public class MailArmor extends Armor {
{
name = "mail armor";
image = ItemSpriteSheet.ARMOR_MAIL;
}
public MailArmor() {
super( 3 );
}
@Override
public String desc() {
return
"Interlocking metal links make for a tough but flexible suit of armor.";
}
}
| gpl-3.0 |
aschmitz/nepenthes | app/workers/cipher_worker.rb | 1403 | require 'net/https'
require 'openssl'
module Net
class HTTP
def set_context=(value)
@ssl_context = OpenSSL::SSL::SSLContext.new
@ssl_context &&= OpenSSL::SSL::SSLContext.new(value)
end
end
end
class CipherWorker
include Sidekiq::Worker
sidekiq_options :queue => :lomem_slow
def perform(id, host, port)
ssl_data = "Accepted Ciphers - anything below 128 Bits is BAD"
protocol_versions = [:SSLv23, :TLSv1, :TLSv1_1, :TLSv1_2] # Set all protocol versions
protocol_versions.each do |version|
cipher_set = OpenSSL::SSL::SSLContext.new(version).ciphers # Get available ciphers
cipher_data += "\n============================================\n"
cipher_data += version.to_s
cipher_data += "\n============================================\n"
cipher_set.each do |cipher_name, ignore_me_cipher_version, bits, ignore_me_algorithm_bits|
request = Net::HTTP.new(host, port)
request.use_ssl = true
request.set_context = version
request.ciphers = cipher_name
request.verify_mode = OpenSSL::SSL::VERIFY_NONE
begin
response = request.get("/")
ssl_data += "[+] Accepted\t #{bits} bits\t#{cipher_name}\n" # Only return accepted ciphers
rescue
OpenSSL::SSL::SSLError
rescue
end
end
end
Sidekiq::Client.enqueue(SslResults, id, cipher_data)
end
end
| gpl-3.0 |
naughtyboy83/android-netspoof | androidnetspoof/src/main/java/uk/digitalsquid/netspoofer/About.java | 2592 | /*
* This file is part of Network Spoofer for Android.
* Network Spoofer lets you change websites on other people’s computers
* from an Android phone.
* Copyright (C) 2014 Will Shackleton <will@digitalsquid.co.uk>
*
* Network Spoofer 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.
*
* Network Spoofer 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 Network Spoofer, in the file COPYING.
* If not, see <http://www.gnu.org/licenses/>.
*/
package uk.digitalsquid.netspoofer;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
public class About extends Activity implements OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
findViewById(R.id.website).setOnClickListener(this);
findViewById(R.id.donate).setOnClickListener(this);
findViewById(R.id.reportBug).setOnClickListener(this);
// Google analytics
Tracker t = ((App)getApplication()).getTracker();
if(t != null) {
t.setScreenName(getClass().getCanonicalName());
t.send(new HitBuilders.AppViewBuilder().build());
}
}
@Override
public void onClick(View v) {
Intent intent;
switch(v.getId()) {
case R.id.website:
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://digitalsquid.co.uk/netspoof"));
startActivity(intent);
break;
case R.id.reportBug:
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/w-shackleton/android-netspoof/issues/new"));
startActivity(intent);
break;
case R.id.donate:
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://digitalsquid.co.uk/netspoof/donate"));
startActivity(intent);
break;
}
}
}
| gpl-3.0 |
wpXtreme/wpdk | classes/core/wpdk-functions.php | 25435 | <?php
/**
* @file wpdk-functions.php
*
* Very useful functions for common cases. All that is missing in WordPress.
*
* ## Overview
* This file contains the pure inline function without class wrapper. You can use these function directly from code.
*
* @brief Very useful functions for common cases.
* @author =undo= <info@wpxtre.me>
* @copyright Copyright (C) 2012-2015 wpXtreme Inc. All Rights Reserved.
* @date 2015-01-22
* @version 1.0.1
*
* @history 1.0.1 - Added `wpdk_is_lock()` function.
*/
// ---------------------------------------------------------------------------------------------------------------------
// has/is zone
// ---------------------------------------------------------------------------------------------------------------------
if( !function_exists( 'wpdk_is_bool' ) ) {
/**
* Return TRUE if the string NOT contains '', 'false', '0', 'no', 'n', 'off', null.
*
* @brief Check for generic boolean
*
* @param string $str String to check
*
* @return bool
*
* @file wpdk-functions.php
*
*/
function wpdk_is_bool( $str )
{
return !in_array( strtolower( $str ), array( '', 'false', '0', 'no', 'n', 'off', null ) );
}
}
if( !function_exists( 'wpdk_is_url' ) ) {
/**
* Return TRUE if a url is a URI
*
* @brief Check URI
*
* @since 1.0.0.b2
*
* @param string $url
*
* @return bool
*
* @file wpdk-functions.php
*/
function wpdk_is_url( $url )
{
if( !empty( $url ) && is_string( $url ) ) {
return ( '#' === substr( $url, 0, 1 ) || '/' === substr( $url, 0, 1 ) || 'http' === substr( $url, 0, 4 ) ||
false !== strpos( $url, '?' ) || false !== strpos( $url, '&' ) );
}
return false;
}
}
if( !function_exists( 'wpdk_is_infinity' ) ) {
/**
* Check if infinity
*
* @brief Infinity
*
* @param float|string $value Check value
*
* @return bool TRUE if $value is equal to INF (php) or WPDKMath::INFINITY
*
* @file wpdk-functions.php
* @deprecated Since 1.2.0 Use WPDKMath::isInfinity() instead
*
*/
function wpdk_is_infinity( $value )
{
_deprecated_function( __FUNCTION__, '1.2.0', 'WPDKMath::isInfinity()' );
return WPDKMath::isInfinity( $value );
}
}
if( !function_exists( 'wpdk_is_ajax' ) ) {
/**
* Return TRUE if we are called by Ajax. Used to be sure that we are responding to an HTTPRequest request and that
* the WordPress define DOING_AJAX is defined.
*
* @brief Ajax validation
*
* @return bool TRUE if Ajax trusted
*/
function wpdk_is_ajax()
{
if( defined( 'DOING_AJAX' ) ) {
return true;
}
if( isset( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) && strtolower( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) == 'xmlhttprequest'
) {
return true;
}
else {
return false;
}
}
}
if( !function_exists( 'wpdk_is_child' ) ) {
/**
* Returns TRUE if the current page is a child of another.
*
* @param array|int|string $parent Mixed format for parent page
*
* @return bool TRUE if the current page is a child of another
*/
function wpdk_is_child( $parent = '' )
{
global $post;
$parent_obj = get_post( $post->post_parent, ARRAY_A );
$parent = (string)$parent;
$parent_array = (array)$parent;
if( $parent_obj && isset( $parent_obj[ 'ID' ] ) ) {
if( in_array( (string)$parent_obj[ 'ID' ], $parent_array ) ) {
return true;
}
elseif( in_array( (string)$parent_obj[ 'post_title' ], $parent_array ) ) {
return true;
}
elseif( in_array( (string)$parent_obj[ 'post_name' ], $parent_array ) ) {
return true;
}
else {
return false;
}
}
return false;
}
}
// ---------------------------------------------------------------------------------------------------------------------
// Sanitize
// ---------------------------------------------------------------------------------------------------------------------
if( !function_exists( 'wpdk_sanitize_function' ) ) {
/**
* Return a possibile function name
*
* @brief Sanitize for function name
* @since 1.0.0.b3
*
* @param string $key String key
*
* @return mixed
*/
function wpdk_sanitize_function( $key )
{
return str_replace( '-', '_', sanitize_key( $key ) );
}
}
// ---------------------------------------------------------------------------------------------------------------------
// Posts
// ---------------------------------------------------------------------------------------------------------------------
if( !function_exists( 'wpdk_get_image_size' ) ) {
/**
* Return registered image size information
*
* @param string $name Image size ID
*
* @return bool|array FALSE if not found Image size ID
*/
function wpdk_get_image_size( $name )
{
global $_wp_additional_image_sizes;
if( isset( $_wp_additional_image_sizes[ $name ] ) ) {
return $_wp_additional_image_sizes[ $name ];
}
return false;
}
}
if( !function_exists( 'wpdk_checked' ) ) {
/**
* Commodity to extends checked() WordPress function with array check
*
* @param string|array $haystack Single value or array
* @param mixed $current (true) The other value to compare if not just true
* @param bool $echo Whether to echo or just return the string
*
* @return string html attribute or empty string
*/
function wpdk_checked( $haystack, $current, $echo = true )
{
if( is_array( $haystack ) ) {
if( in_array( $current, $haystack ) ) {
$current = $haystack = 1;
return checked( $haystack, $current, $echo );
}
return false;
}
return checked( $haystack, $current, $echo );
}
}
if( !function_exists( 'wpdk_selected' ) ) {
/**
* Commodity to extends selected() WordPress function with array check
*
* @param string|array $haystack Single value or array
* @param mixed $current (true) The other value to compare if not just true
* @param bool $echo Whether to echo or just return the string
*
* @return string html attribute or empty string
* @deprecated Since 1.2.0 Use WPDKHTMLTagSelect::selected() instead
*/
function wpdk_selected( $haystack, $current, $echo = true )
{
_deprecated_function( __FUNCTION__, '1.2.0', 'WPDKHTMLTagSelect::selected()' );
return WPDKHTMLTagSelect::selected( $haystack, $current );
}
}
if( !function_exists( 'wpdk_page_with_slug' ) ) {
/**
* Return a post object by slug or alternative slug.
*
* @since 1.8.0
*
* @param string $slug Post slug.
* @param string $post_type Optional. Post type. Default 'page'.
* @param string $alternative_slug Optional. Alternative slug whether the post is not found. Default empty.
*
* @uses get_page_by_path()
* @note WPML compatible
*
* @return null|WP_Post
*/
function wpdk_page_with_slug( $slug, $post_type = 'page', $alternative_slug = '' )
{
/**
* @var wpdb $wpdb
*/
global $wpdb;
// Stability
if( empty( $slug ) ) {
return null;
}
// Get object
$page = get_page_by_path( $slug, OBJECT, $post_type );
if( is_null( $page ) ) {
$page = get_page_by_path( $alternative_slug, OBJECT, $post_type );
if( is_null( $page ) ) {
// Check WPML
if( function_exists( 'icl_object_id' ) ) {
$sql = <<<SQL
SELECT ID FROM {$wpdb->posts}
WHERE post_name = '{$slug}'
AND post_type = '{$post_type}'
AND post_status = 'publish'
SQL;
$id = $wpdb->get_var( $sql );
$id = icl_object_id( $id, $post_type, true );
}
else {
return null;
}
}
else {
$id = $page->ID;
}
return get_post( $id );
}
return $page;
}
}
if( !function_exists( 'wpdk_content_page_with_slug' ) ) {
/**
* Return the post content by slug or alternative slug.
*
* @param string $slug Post slug.
* @param string $post_type Optional. Post type. Default 'page'.
* @param string $alternative_slug Optional. Alternative slug whether the post is not found. Default empty.
*
* @note WPML compatible
* @uses wpdk_page_with_slug()
*
* @return null|string
*/
function wpdk_content_page_with_slug( $slug, $post_type = 'page', $alternative_slug = '' )
{
$page = wpdk_page_with_slug( $slug, $post_type, $alternative_slug );
if( is_null( $page ) ) {
return $page;
}
return apply_filters( 'the_content', $page->post_content );
}
}
if( !function_exists( 'wpdk_permalink_page_with_slug' ) ) {
/**
* Return the post permalink content by slug or alternative slug. FALSE otherwise.
*
* @param string $slug Post slug.
* @param string $post_type Optional. Post type. Default 'page'.
* @param string $alternative_slug Optional. Alternative slug whether the post is not found. Default empty.
*
* @note WPML compatible
* @uses wpdk_page_with_slug()
*
* @return bool|string
*/
function wpdk_permalink_page_with_slug( $slug, $post_type = 'page', $alternative_slug = '' )
{
$page = wpdk_page_with_slug( $slug, $post_type, $alternative_slug );
if( is_null( $page ) ) {
return false;
}
$permalink = get_permalink( $page->ID );
// Append slash
return trailingslashit( $permalink );
}
}
if( !function_exists( 'wpdk_delta_object' ) ) {
/**
* Do a merge/combine between two object tree.
* If the old version not contains an object or property, that is added.
* If the old version contains an object or property less in last version, that is deleted.
*
* @brief Object delta compare for combine
*
* @param mixed $last_version Object tree with new or delete object/value
* @param mixed $old_version Current Object tree, loaded from serialize or database for example
*
* @return Object the delta Object tree
*
* @deprecated Since 1.2.0 Use WPDKObject::__delta() instead
*/
function wpdk_delta_object( $last_version, $old_version )
{
_deprecated_function( __FUNCTION__, '1.2.0', 'WPDKObject::__delta()' );
return WPDKObject::__delta( $last_version, $old_version );
}
}
if( !function_exists( 'wpdk_get_image_in_post_content' ) ) {
/**
* Get the img src value fron content of a post or page.
*
* @brief Get an img tag from the content
*
* @param int $id_post ID post
*
* @return mixed
*/
function wpdk_get_image_in_post_content( $id_post )
{
_deprecated_function( __FUNCTION__, '1.3.1', '_WPDKPost::imageContent() or _WPDKPost::imageContentWithID()' );
ob_start();
ob_end_clean();
$output = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', get_post_field( 'post_content', $id_post ), $matches );
if( !empty( $matches ) && is_array( $matches ) && isset( $matches[ 1 ][ 0 ] ) ) {
$display_img = $matches[ 1 ][ 0 ];
return $display_img;
}
return null;
}
}
if( !function_exists( 'wpdk_get_image_from_post_thumbnail' ) ) {
/**
* Function to find image using WP available function get_the_post_thumbnail().
*
* @brief Get thumbnail image
* @deprecated Since 1.3.1 Use _WPDKPost::thumbnail() or _WPDKPost::thumbnailWithID()
*
* @param int $id_post ID post
*
* @return mixed|null
*/
function wpdk_get_image_from_post_thumbnail( $id_post )
{
_deprecated_function( __FUNCTION__, '1.3.1', '_WPDKPost::thumbnail() or _WPDKPost::thumbnailWithID()' );
if( function_exists( 'has_post_thumbnail' ) ) {
if( has_post_thumbnail( $id_post ) ) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $id_post ), 'full' );
return $image[ 0 ];
}
}
return null;
}
}
if( !function_exists( 'wpdk_get_image_from_attachments' ) ) {
/**
* Get src url image from first image attachment post
*
* @brief Get image from post attachment
*
* @param int $id_post ID post
*
* @return array|bool
*/
function wpdk_get_image_from_attachments( $id_post )
{
_deprecated_function( __FUNCTION__, '1.3.1', '_WPDKPost::imageAttachmentsWithID() or _WPDKPost::imageAttachments()' );
if( function_exists( 'wp_get_attachment_image' ) ) {
$children = get_children( array(
'post_parent' => $id_post,
'post_type' => 'attachment',
'numberposts' => 1,
'post_status' => 'inherit',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ASC'
) );
if( empty( $children ) || !is_array( $children ) ) {
return false;
}
$item = current( $children );
if( is_object( $item ) && isset( $item->ID ) ) {
$image = wp_get_attachment_image_src( $item->ID, 'full' );
return $image[ 0 ];
}
}
return false;
}
}
// ---------------------------------------------------------------------------------------------------------------------
// WPDKResult check
// ---------------------------------------------------------------------------------------------------------------------
if( !function_exists( 'is_wpdk_error' ) ) {
/**
* Looks at the object and if a WPDKError class. Does not check to see if the parent is also WPDKError or a WPDKResult,
* so can't inherit both the classes and still use this function.
*
* @brief Check whether variable is a WPDK result error.
*
* @param mixed $thing Check if unknown variable is WPDKError object.
*
* @return bool TRUE, if WPDKError. FALSE, if not WPDKError.
*
* @deprecated Since 1.2.0 Use WPDKResult::isError() instead
*
*/
function is_wpdk_error( $thing )
{
_deprecated_function( __FUNCTION__, '1.2.0', 'WPDKResult::isError()' );
return WPDKResult::isError( $thing );
}
}
if( !function_exists( 'is_wpdk_warning' ) ) {
/**
* Looks at the object and if a WPDKWarning class. Does not check to see if the parent is also WPDKWarning or a
* WPDKResult, so can't inherit both the classes and still use this function.
*
* @brief Check whether variable is a WPDK result warning.
*
* @param mixed $thing Check if unknown variable is WPDKWarning object.
*
* @return bool TRUE, if WPDKWarning. FALSE, if not WPDKWarning.
*
* @deprecated Since 1.2.0 Use WPDKResult::isWarning() instead
*/
function is_wpdk_warning( $thing )
{
_deprecated_function( __FUNCTION__, '1.2.0', 'WPDKResult::isWarning()' );
return WPDKResult::isWarning( $thing );
}
}
if( !function_exists( 'is_wpdk_status' ) ) {
/**
* Looks at the object and if a WPDKStatus class. Does not check to see if the parent is also WPDKStatus or a
* WPDKResult, so can't inherit both the classes and still use this function.
*
* @brief Check whether variable is a WPDK result status.
*
* @param mixed $thing Check if unknown variable is WPDKStatus object.
*
* @return bool TRUE, if WPDKStatus. FALSE, if not WPDKStatus.
*
* @deprecated Since 1.2.0 Use WPDKResult::isStatus() instead
*/
function is_wpdk_status( $thing )
{
_deprecated_function( __FUNCTION__, '1.2.0', 'WPDKResult::isStatus()' );
return WPDKResult::isWarning( $thing );
}
}
// ---------------------------------------------------------------------------------------------------------------------
// Miscellanea
// ---------------------------------------------------------------------------------------------------------------------
if( !function_exists( 'wpdk_add_page' ) ) {
/**
* Add a custom hidden (without menu) page in the admin backend area and return the page's hook_suffix.
*
* @brief Add a page
*
* @param string $page_slug The slug name to refer to this hidden pahe by (should be unique)
* @param string $page_title The text to be displayed in the title tags of the page when the page is selected
* @param string $capability The capability required for this page to be displayed to the user.
* @param callback|string $function Optional. The function to be called to output the content for this page.
* @param string $hook_head Optional. Callback when head is loaded
* @param string $hook_load Optional. Callback when loaded
*
* @return string
*/
function wpdk_add_page( $page_slug, $page_title, $capability, $function = '', $hook_head = '', $hook_load = '' )
{
global $admin_page_hooks, $_registered_pages, $_parent_pages;
$hook_name = '';
if( !empty( $function ) && current_user_can( $capability ) ) {
$page_slug = plugin_basename( $page_slug );
$admin_page_hooks[ $page_slug ] = $page_title;
$hook_name = get_plugin_page_hookname( $page_slug, '' );
if( !empty( $hook_name ) ) {
add_action( $hook_name, $function );
$_registered_pages[ $hook_name ] = true;
$_parent_pages[ $page_slug ] = false;
if( !empty( $hook_head ) ) {
add_action( 'admin_head-' . $hook_name, $hook_head );
}
if( !empty( $hook_load ) ) {
add_action( 'load-' . $hook_name, $hook_load );
}
}
}
return $hook_name;
}
}
if( !function_exists( 'wpdk_enqueue_script_page' ) ) {
/**
* Enqueue script for list of page template
*
* @brief Enqueue script
* @deprecated since 1.4.21 Use WPDKScripts::enqueue_scripts_page_template() instead
*
* @param array $pages Array of page slug
* @param string $handle The script /unique) handle
* @param bool $src Optional. Source URI
* @param array $deps Optional. Array of other handle
* @param bool $ver Optional. Version to avoid cache
* @param bool $in_footer Optional. Load in footer
*/
function wpdk_enqueue_script_page( $pages, $handle, $src = false, $deps = array(), $ver = false, $in_footer = false )
{
foreach( $pages as $slug ) {
if( is_page_template( $slug ) ) {
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );
break;
}
}
}
}
if( !function_exists( 'wpdk_enqueue_script_page_template' ) ) {
/**
* Enqueue script for list of page template. Return FALSE if $page_templates is empty
*
* @brief Enqueue script
* @deprecated since 1.4.21 Use WPDKScripts::enqueue_scripts_page_template() instead
*
* @param array $page_templates Array of page slug template
* @param string $handle The script /unique) handle
* @param bool $src Optional. Source URI
* @param array $deps Optional. Array of other handle
* @param bool $ver Optional. Version to avoid cache
* @param bool $in_footer Optional. Load in footer
*
* @return bool
*/
function wpdk_enqueue_script_page_template( $page_templates, $handle, $src = false, $deps = array(), $ver = false, $in_footer = false )
{
if( empty( $page_templates ) ) {
return false;
}
if( is_string( $page_templates ) ) {
$page_templates = array( $page_templates );
}
foreach( $page_templates as $slug ) {
if( is_page_template( $slug ) ) {
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );
break;
}
}
return true;
}
}
if( !function_exists( 'wpdk_set_user_transient' ) ) {
/**
* Set/update the value of a user transient.
*
* You do not need to serialize values. If the value needs to be serialized, then it will be serialized before it is
* set.
*
* @brief Set
* @since 1.0.0
* @deprecated since 1.3.0 - Use WPDKUser::setTransientWithUser() instead
*
* @uses apply_filters() Calls 'pre_set_user_transient_$transient' hook to allow overwriting the transient value
* to be stored.
* @uses do_action() Calls 'set_user_transient_$transient' and 'setted_transient' hooks on success.
*
* @param string $transient Transient name. Expected to not be SQL-escaped.
* @param mixed $value Transient value. Expected to not be SQL-escaped.
* @param int $expiration Time until expiration in seconds, default 0
* @param int $user_id Optional. User ID. If null the current user id is used instead
*
* @return bool False if value was not set and true if value was set.
*/
function wpdk_set_user_transient( $transient, $value, $expiration = 0, $user_id = null )
{
_deprecated_function( __CLASS__ . '::' . __FUNCTION__, '1.3.0', 'WPDKUser::setTransientWithUser()' );
return WPDKUser::setTransientWithUser( $transient, $value, $expiration, $user_id );
}
}
if( !function_exists( 'wpdk_get_user_transient' ) ) {
/**
* Get the value of a user transient.
* If the transient does not exist or does not have a value, then the return value will be false.
*
* @brief Get
* @since 1.0.0
* @deprecated since 1.4.8 - Use WPDKUser::getTransientWithUser() instead
*
* @uses apply_filters() Calls 'pre_user_transient_$transient' hook before checking the transient. Any value
* other than false will "short-circuit" the retrieval of the transient and return the returned value.
* @uses apply_filters() Calls 'user_transient_$transient' hook, after checking the transient, with the transient
* value.
*
* @param string $transient Transient name. Expected to not be SQL-escaped
* @param int $user_id Optional. User ID. If null the current user id is used instead
*
* @return mixed Value of transient
*/
function wpdk_get_user_transient( $transient, $user_id = null )
{
_deprecated_function( __CLASS__ . '::' . __FUNCTION__, '1.4.8', 'WPDKUser::getTransientWithUser()' );
return WPDKUser::getTransientWithUser( $transient, $user_id );
}
}
if( !function_exists( 'wpdk_delete_user_transient' ) ) {
/**
* Delete a user transient.
*
* @brief Delete
* @since 1.1.0
* @deprecated since 1.5.1 - Use WPDKUser::deleteTransientWithUser() instead
*
* @uses do_action() Calls 'delete_user_transient_$transient' hook before transient is deleted.
* @uses do_action() Calls 'deleted_user_transient' hook on success.
*
* @param string $transient Transient name. Expected to not be SQL-escaped.
* @param int $user_id Optional. User ID. If null the current user id is used instead
*
* @return bool true if successful, false otherwise
*/
function wpdk_delete_user_transient( $transient, $user_id = null )
{
_deprecated_function( __CLASS__ . '::' . __FUNCTION__, '1.5.1', 'WPDKUser::deleteTransientWithUser()' );
return WPDKUser::deleteTransientWithUser( $transient, $user_id );
}
}
if( !function_exists( 'wpdk_is_request' ) ) {
/**
* Return true if the $verb param in input match with REQUEST METHOD
*
* @brief Check request
* @since 1.1.0
*
* @param string $verb The verb, for instance; GET, post, delete, etc...
*
* @return bool
*/
function wpdk_is_request( $verb )
{
$verb = strtolower( $verb );
return ( $verb == strtolower( $_SERVER[ 'REQUEST_METHOD' ] ) );
}
}
if( !function_exists( 'wpdk_is_request_get' ) ) {
/**
* Return true if the REQUEST METHOD is GET
*
* @brief Check if request is get
*
* @return bool
*/
function wpdk_is_request_get()
{
return wpdk_is_request( 'get' );
}
}
if( !function_exists( 'wpdk_is_request_post' ) ) {
/**
* Return true if the REQUEST METHOD is POST
*
* @brief Check if request is post
*
* @return bool
*/
function wpdk_is_request_post()
{
return wpdk_is_request( 'post' );
}
}
// ---------------------------------------------------------------------------------------------------------------------
// Lock down
// ---------------------------------------------------------------------------------------------------------------------
if( !function_exists( 'wpdk_is_lock' ) ) {
/**
* Return TRUE (or the calculate hash) if the hash has been locked.
*
* @since 1.11.0
*
* @param array|string $hash Optional. Any string or array used to generate an unique hash. If no hash is set, then
* this function provides to generate one for you and return the first time as string.
* @param int $expiration Optional. Expiratin in seconds. Default 5.
*
* @return array|bool
*/
function wpdk_is_lock( $hash = array(), $expiration = 5 )
{
// Prepare result
$result = true;
// If no hash we create onfly for you
if( empty( $hash ) ) {
$hash = $result = array( time() );
}
// Hash
$hash_name = '_wpdk_lock-' . md5( serialize( $hash ) );
// Check exists
if( 'lock' === get_transient( $hash_name ) ) {
return $result;
}
// Set transient
set_transient( $hash_name, 'lock', $expiration );
return false;
}
} | gpl-3.0 |
WinterMute/codeblocks_sf | src/plugins/contrib/wxSmith/wxsproject.cpp | 11636 | /*
* This file is part of wxSmith plugin for Code::Blocks Studio
* Copyright (C) 2006-2007 Bartlomiej Swiecki
*
* wxSmith 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.
*
* wxSmith 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 wxSmith. If not, see <http://www.gnu.org/licenses/>.
*
* $Revision$
* $Id$
* $HeadURL$
*/
#include "wxsproject.h"
#include "wxsmith.h"
#include "wxsresource.h"
#include "wxsresourcefactory.h"
#include "wxsguifactory.h"
#include "wxsgui.h"
#include "wxsversionconverter.h"
#include <wx/string.h>
#include <logmanager.h>
namespace
{
const int CurrentVersion = 1;
const char* CurrentVersionStr = "1";
}
wxsProject::wxsProject(cbProject* Project):
m_Project(Project),
m_GUI(0),
m_UnknownConfig("unknown_config"),
m_UnknownResources("unknown_resource"),
m_WasModifiedDuringLoad(false)
{
assert(Project);
// Creating resource tree entery for this project
m_TreeItem = wxsTree()->NewProjectItem(GetCBProject()->GetTitle(),this);
// Building paths
wxFileName PathBuilder( (Project->GetFilename()) );
m_ProjectPath = PathBuilder.GetPath(wxPATH_GET_VOLUME|wxPATH_GET_SEPARATOR);
}
wxsProject::~wxsProject()
{
delete m_GUI;
m_GUI = 0;
for ( size_t i=m_Resources.Count(); i-->0; )
{
delete m_Resources[i];
m_Resources[i] = 0;
}
m_Resources.Clear();
wxsTree()->Delete(m_TreeItem);
wxsTree()->Refresh();
}
void wxsProject::ReadConfiguration(TiXmlElement* element)
{
TiXmlElement* SmithNode = element->FirstChildElement("wxsmith");
if ( !SmithNode ) return;
TiXmlDocument TempDoc;
// Checking version
if ( wxsVersionConverter::Get().DetectOldConfig(SmithNode,this) )
{
TiXmlElement* ConvertedSmithNode = wxsVersionConverter::Get().ConvertFromOldConfig(SmithNode,&TempDoc,this);
if ( !ConvertedSmithNode )
{
for ( TiXmlNode* Node = SmithNode->FirstChild(); Node; Node=Node->NextSibling() )
{
m_UnknownConfig.InsertEndChild(*Node);
}
return;
}
else
{
SmithNode = ConvertedSmithNode;
m_WasModifiedDuringLoad = true;
}
}
const char* VersionStr = SmithNode->Attribute("version");
int Version = VersionStr ? atoi(VersionStr) : 1;
if ( Version > CurrentVersion )
{
// TODO: Show some dialog box that resources were created by newer version,
// store all configuration for later save and return
return;
}
if ( Version < CurrentVersion )
{
SmithNode = wxsVersionConverter::Get().Convert(SmithNode,&TempDoc,this);
if ( !SmithNode )
{
// TODO: Show some dialog box that resources were created by newer version,
// store all configuration for later save and return
return;
}
else
{
m_WasModifiedDuringLoad = true;
}
}
// Iterating through elements
for ( TiXmlElement* Node = SmithNode->FirstChildElement(); Node; Node=Node->NextSiblingElement() )
{
wxString NodeValue = cbC2U(Node->Value());
if ( NodeValue == _T("gui") )
{
wxString GUIName = cbC2U(Node->Attribute("name"));
wxsGUI* NewGUI = wxsGUIFactory::Build(GUIName,this);
if ( !NewGUI )
{
m_UnknownConfig.InsertEndChild(*Node);
}
else
{
delete m_GUI;
m_GUI = NewGUI;
if ( NewGUI )
{
NewGUI->ReadConfig(Node);
}
}
}
else if ( NodeValue == _T("resources") )
{
for ( TiXmlElement* ResNode = Node->FirstChildElement(); ResNode; ResNode = ResNode->NextSiblingElement() )
{
wxString Type = cbC2U(ResNode->Value());
wxsResource* Res = wxsResourceFactory::Build(Type,this);
if ( Res )
{
// Storing unknown Xml Element
if ( !Res->ReadConfig(ResNode) )
{
m_UnknownResources.InsertEndChild(*ResNode);
delete Res;
}
else
{
m_Resources.Add(Res);
Res->BuildTreeEntry(GetResourceTypeTreeId(Type));
}
}
else
{
m_UnknownResources.InsertEndChild(*ResNode);
}
}
}
else
{
m_UnknownConfig.InsertEndChild(*Node);
}
}
}
void wxsProject::WriteConfiguration(TiXmlElement* element)
{
TiXmlElement* SmithElement = element->FirstChildElement("wxsmith");
if ( !m_GUI && m_Resources.empty() && m_UnknownConfig.NoChildren() && m_UnknownResources.NoChildren() )
{
// Nothing to write
if ( SmithElement )
{
element->RemoveChild(SmithElement);
}
return;
}
if ( !SmithElement )
{
SmithElement = element->InsertEndChild(TiXmlElement("wxsmith"))->ToElement();
}
SmithElement->Clear();
SmithElement->SetAttribute("version",CurrentVersionStr);
// saving GUI item
if ( m_GUI )
{
TiXmlElement* GUIElement = SmithElement->InsertEndChild(TiXmlElement("gui"))->ToElement();
GUIElement->SetAttribute("name",cbU2C(m_GUI->GetName()));
m_GUI->WriteConfig(GUIElement);
}
// saving resources
if ( !m_Resources.empty() || !m_UnknownResources.NoChildren() )
{
TiXmlElement* ResElement = SmithElement->InsertEndChild(TiXmlElement("resources"))->ToElement();
size_t Count = m_Resources.Count();
for ( size_t i=0; i<Count; i++ )
{
const wxString& Name = m_Resources[i]->GetResourceName();
const wxString& Type = m_Resources[i]->GetResourceType();
TiXmlElement* Element = ResElement->InsertEndChild(TiXmlElement(cbU2C(Type)))->ToElement();
// TODO: Check value returned from WriteConfig
m_Resources[i]->WriteConfig(Element);
Element->SetAttribute("name",cbU2C(Name));
}
// Saving all unknown resources
for ( TiXmlNode* Node = m_UnknownResources.FirstChild(); Node; Node=Node->NextSibling() )
{
SmithElement->InsertEndChild(*Node);
}
}
// Saving all unknown configuration nodes
for ( TiXmlNode* Node = m_UnknownConfig.FirstChild(); Node; Node=Node->NextSibling() )
{
SmithElement->InsertEndChild(*Node);
}
}
bool wxsProject::AddResource(wxsResource* NewResource)
{
if ( NewResource == 0 )
{
return false;
}
const wxString& Type = NewResource->GetResourceType();
const wxString& Name = NewResource->GetResourceName();
if ( FindResource(Name) != 0 )
{
return false;
}
m_Resources.Add(NewResource);
wxsResourceItemId Id = GetResourceTypeTreeId(Type);
NewResource->BuildTreeEntry(Id);
m_Project->SetModified(true);
return true;
}
bool wxsProject::DelResource(wxsResource* Resource)
{
int Index = m_Resources.Index(Resource);
if ( Index == wxNOT_FOUND ) return false;
delete Resource;
m_Resources.RemoveAt(Index);
m_Project->SetModified(true);
return true;
}
wxsResource* wxsProject::FindResource(const wxString& Name)
{
for ( size_t i = m_Resources.Count(); i-->0; )
{
if ( m_Resources[i]->GetResourceName() == Name )
{
return m_Resources[i];
}
}
return 0;
}
void wxsProject::Configure()
{
if ( !m_GUI )
{
m_GUI = wxsGUIFactory::SelectNew(_("wxSmith does not manage any GUI for this project.\nPlease select GUI you want to be managed in wxSmith."),this);
if ( m_GUI )
{
NotifyChange();
}
}
if ( m_GUI )
{
if ( !m_GUI->CheckIfApplicationManaged() )
{
// TODO: Prepare better communicate, consider chancing to cbAnnoyingDiaog
if ( wxMessageBox(_("wxSmith does not manage this application's source.\n"
"Should I create proper bindings?"),_("wxSmith"),wxYES_NO) == wxNO ) return;
if ( !m_GUI->CreateApplicationBinding() ) return;
}
cbConfigurationDialog Dlg(0,-1,_("Configuring wxSmith"));
Dlg.AttachConfigurationPanel(m_GUI->BuildConfigurationPanel(&Dlg));
PlaceWindow(&Dlg);
Dlg.ShowModal();
}
}
cbConfigurationPanel* wxsProject::GetProjectConfigurationPanel(wxWindow* parent)
{
if ( m_GUI )
{
if ( m_GUI->CheckIfApplicationManaged() )
{
return m_GUI->BuildConfigurationPanel(parent);
}
}
return 0;
}
wxString wxsProject::GetProjectPath()
{
return m_ProjectPath;
}
bool wxsProject::CanOpenEditor(const wxString& FileName)
{
for ( size_t i=m_Resources.Count(); i-->0; )
{
if ( m_Resources[i]->OnCanHandleFile(FileName) )
{
return true;
}
}
return false;
}
bool wxsProject::TryOpenEditor(const wxString& FileName)
{
for ( size_t i=m_Resources.Count(); i-->0; )
{
if ( m_Resources[i]->OnCanHandleFile(FileName) )
{
m_Resources[i]->EditOpen();
return true;
}
}
return false;
}
void wxsProject::SetGUI(wxsGUI* NewGUI)
{
if ( m_GUI != NewGUI )
{
delete m_GUI;
m_GUI = NewGUI;
}
}
void wxsProject::NotifyChange()
{
return m_Project->SetModified(true);
}
wxsResourceItemId wxsProject::GetResourceTypeTreeId(const wxString& Name)
{
if ( m_ResBrowserIds.find(Name) != m_ResBrowserIds.end() )
{
return m_ResBrowserIds[Name];
}
return m_ResBrowserIds[Name] = wxsTree()->AppendItem(m_TreeItem,Name,wxsResourceFactory::ResourceTreeIcon(Name));
}
void wxsProject::UpdateName()
{
wxsResourceTree::Get()->SetItemText(m_TreeItem,GetCBProject()->GetTitle());
}
bool wxsProject::RecoverWxsFile( const wxString& ResourceDescription )
{
TiXmlDocument doc;
doc.Parse( ( _T("<") + ResourceDescription + _T(" />") ).mb_str( wxConvUTF8 ) );
if ( doc.Error() )
{
wxMessageBox( cbC2U( doc.ErrorDesc() ) + wxString::Format(_T(" in %d x %d"), doc.ErrorRow(), doc.ErrorCol() ) );
return false;
}
TiXmlElement* elem = doc.RootElement();
if ( !elem )
{
return false;
}
// Try to build resource of given type
wxString Type = cbC2U(elem->Value());
wxsResource* Res = wxsResourceFactory::Build(Type,this);
if ( !Res ) return false;
// Read settings
if ( !Res->ReadConfig( elem ) )
{
delete Res;
return false;
}
// Prevent duplicating resource names
if ( FindResource( Res->GetResourceName() ) )
{
delete Res;
return false;
}
// Finally add the resource
m_Resources.Add(Res);
Res->BuildTreeEntry(GetResourceTypeTreeId(Type));
return true;
}
| gpl-3.0 |
epfl-lara/leon | testcases/lazy-datastructures/withOrb/Haskell-Library/StreamLibrary.scala | 6605 | package haskell
import leon._
import lang._
import annotation._
import instrumentation._
import mem._
import higherorder._
import collection._
import invariant._
/**
* This is a collection of methods translated to Scala from the haskell stream library.
* To prove a running steps bound, we impose a precondition that the input stream is an infinite
* stream of natural numbers, and the higher-order function parameters are constant steps functions
* We ignored methods that are not guaranteed to terminate on all streams e.g. `filter`, `dropWhile` etc.
*/
object StreamLibrary {
sealed abstract class LList {
lazy val tail = {
require(this != SNil())
this match {
case SCons(_, tailFun) => tailFun()
}
}
def tailOrNil = {
this match {
case SNil() => this
case _ => tail
}
}
}
case class SCons(x: BigInt, tailFun: () => LList) extends LList
case class SNil() extends LList
/**
* Stream for all natural numbers starting from n
*/
def natsFromn(n: BigInt): LList = {
SCons(n, () => genNextNatFrom(n))
}
def genNextNatFrom(n: BigInt): LList = {
val nn = n + 1
SCons(nn, () => genNextNatFrom(nn))
} ensuring(_ => steps <= ?) // Orb result: ??
/**
* A property that asserts that the a stream is a `natstream`
*/
def validNatStream(s: LList): Boolean = {
s match {
case SCons(_, tailFun) =>
tailFun fmatch[BigInt, Boolean] {
case n if tailFun.is(() => genNextNatFrom(n)) => true
case _ => false
}
case _ => true
}
}
@ignore
var array = Array[BigInt]()
@extern
def constFun1(n: BigInt): BigInt = {
array(0)
} ensuring (_ => steps <= 1)
/**
* Apply a function over all elements of a sequence.
* Requires that the input is a `nat` stream, and `f` is
* constFun1 which is a constant steps function.
*/
def map(f: BigInt => BigInt, s: LList): LList = {
require(validNatStream(s) && f.is(constFun1 _))
s match {
case SNil() => SNil()
case l @ SCons(x, _) => SCons(f(x), () => mapSusp(f, s))
}
} ensuring{_ => steps <= ?}
def mapSusp(f: BigInt => BigInt, s: LList) = {
require(validNatStream(s) && f.is(constFun1 _))
map(f, s.tailOrNil)
} ensuring(_ => steps <= ?)
/**
* The function `appendList` appends a stream to a list,
* returning a stream of all the list elements
* followed by all the original stream elements.
*/
def appendList(l: List[BigInt], s: LList): LList = {
l match {
case Nil() => s
case Cons(x, tail) => SCons(x, () => appendList(tail, s))
}
} ensuring (_ => steps <= ?) // Orb result: ??
/**
* The function repeat expects an integer and returns a
* stream that represents infinite appends of the
* integer to itself.
*/
def repeat(n: BigInt): LList = {
SCons(n, () => repeat(n))
} ensuring (_ => steps <= ?) // Orb result: ??
/**
* The function cycle expects a list and returns a
* stream that represents infinite appends of the
* list to itself.
*/
def cycle(l: List[BigInt]): LList = {
l match {
case Nil() => SNil()
case Cons(x, t) =>
SCons(x, () => appendList(t, cycle(l)))
}
} ensuring (_ => steps <= ?) // Orb result: ??
@extern
def constFun2(n: BigInt): Boolean = {
array(0) == 0
} ensuring (_ => steps <= 1)
/**
* 'takeWhile' returns the longest prefix of the stream for which the
* predicate p holds.
*/
def takeWhile(p: BigInt => Boolean, s: LList): LList = {
require(validNatStream(s) && p.is(constFun2 _))
s match {
case SNil() => SNil()
case l @ SCons(x, _) =>
if(p(x))
SCons(x, () => takeWhileSusp(p, s))
else
SNil()
}
} ensuring (_ => steps <= ?)
def takeWhileSusp(p: BigInt => Boolean, s: LList): LList = {
require(validNatStream(s) && p.is(constFun2 _))
takeWhile(p, s.tailOrNil)
} ensuring(_ => steps <= ?)
@extern
def constFun3(n: BigInt, m: BigInt): BigInt = {
array(0)
} ensuring (_ => steps <= 1)
/**
* 'scan' yields a stream of successive reduced values from:
* scan f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
*/
def scan(f: (BigInt, BigInt) => BigInt, z: BigInt, s: LList): LList = {
require(validNatStream(s) && f.is(constFun3 _))
s match {
case SNil() => SNil()
case l @ SCons(x, _) =>
val r = f(z, x)
SCons(z, () => scanSusp(f, r, s))
}
} ensuring (_ => steps <= ?)
def scanSusp(f: (BigInt, BigInt) => BigInt, z: BigInt, s: LList) = {
require(validNatStream(s) && f.is(constFun3 _))
scan(f, z, s.tailOrNil)
} ensuring(_ => steps <= ?)
@extern
def constFun4(n: BigInt): (BigInt, BigInt) = {
(array(0), array(0))
} ensuring (_ => steps <= 1)
/**
* The unfold function is similar to the unfold for lists. Note
* there is no base case: all streams must be infinite.
*/
def unfold(f: BigInt => (BigInt, BigInt), c: BigInt): LList = {
require(f.is(constFun4 _))
val (x, d) = f(c)
SCons(x, () => unfold(f, d))
} ensuring(_ => steps <= ?)
/**
* The 'isPrefixOf' function returns True if the first argument is
* a prefix of the second.
*/
def isPrefixOf(l: List[BigInt], s: LList): Boolean = {
require(validNatStream(s))
s match {
case SNil() =>
l match {
case Nil() => true
case _ => false
}
case ss @ SCons(x, _) =>
l match {
case Nil() => true
case ll @ Cons(y, tail) =>
if(x == y) isPrefixOf(tail, s.tailOrNil)
else false
}
}
} ensuring(_ => steps <= ? * l.size + ?)
/**
* The elements of two tuples are combined using the function
* passed as the first argument to 'zipWith'.
*/
def zipWith(f: (BigInt, BigInt) => BigInt, a: LList, b: LList): LList = {
require(validNatStream(a) && validNatStream(b) && f.is(constFun3 _))
a match {
case SNil() => SNil()
case al @ SCons(x, _) =>
b match {
case SNil() => SNil()
case bl @ SCons(y, _) =>
SCons(f(x, y), () => zipWithSusp(f, al, bl))
}
}
} ensuring(_ => steps <= ?)
def zipWithSusp(f: (BigInt, BigInt) => BigInt, a: LList, b: LList) = {
require(validNatStream(a) && validNatStream(b) && f.is(constFun3 _))
zipWith(f, a.tailOrNil, b.tailOrNil)
} ensuring(_ => steps <= ?)
}
| gpl-3.0 |
DarkSynopsis/Kuriimu | src/game/game_maple_story_3ds/Properties/Resources.Designer.cs | 4609 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace game_maple_story_3ds.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("game_maple_story_3ds.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap background {
get {
object obj = ResourceManager.GetObject("background", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap blank {
get {
object obj = ResourceManager.GetObject("blank", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap icon {
get {
object obj = ResourceManager.GetObject("icon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap MainFont {
get {
object obj = ResourceManager.GetObject("MainFont", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] MainFont_bcfnt {
get {
object obj = ResourceManager.GetObject("MainFont_bcfnt", resourceCulture);
return ((byte[])(obj));
}
}
}
}
| gpl-3.0 |
tinygg/MCIR | sqlol/includes/adodb/adodb-lib.inc.php | 36732 | <?php
// security - hide paths
if (!defined('ADODB_DIR')) die();
global $ADODB_INCLUDED_LIB;
$ADODB_INCLUDED_LIB = 1;
/*
@version V5.14 8 Sept 2011 (c) 2000-2011 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Less commonly used functions are placed here to reduce size of adodb.inc.php.
*/
function adodb_strip_order_by($sql)
{
$rez = preg_match('/(\sORDER\s+BY\s[^)]*)/is',$sql,$arr);
if ($arr)
if (strpos($arr[0],'(') !== false) {
$at = strpos($sql,$arr[0]);
$cntin = 0;
for ($i=$at, $max=strlen($sql); $i < $max; $i++) {
$ch = $sql[$i];
if ($ch == '(') {
$cntin += 1;
} elseif($ch == ')') {
$cntin -= 1;
if ($cntin < 0) {
break;
}
}
}
$sql = substr($sql,0,$at).substr($sql,$i);
} else
$sql = str_replace($arr[0], '', $sql);
return $sql;
}
if (false) {
$sql = 'select * from (select a from b order by a(b),b(c) desc)';
$sql = '(select * from abc order by 1)';
die(adodb_strip_order_by($sql));
}
function adodb_probetypes(&$array,&$types,$probe=8)
{
// probe and guess the type
$types = array();
if ($probe > sizeof($array)) $max = sizeof($array);
else $max = $probe;
for ($j=0;$j < $max; $j++) {
$row = $array[$j];
if (!$row) break;
$i = -1;
foreach($row as $v) {
$i += 1;
if (isset($types[$i]) && $types[$i]=='C') continue;
//print " ($i ".$types[$i]. "$v) ";
$v = trim($v);
if (!preg_match('/^[+-]{0,1}[0-9\.]+$/',$v)) {
$types[$i] = 'C'; // once C, always C
continue;
}
if ($j == 0) {
// If empty string, we presume is character
// test for integer for 1st row only
// after that it is up to testing other rows to prove
// that it is not an integer
if (strlen($v) == 0) $types[$i] = 'C';
if (strpos($v,'.') !== false) $types[$i] = 'N';
else $types[$i] = 'I';
continue;
}
if (strpos($v,'.') !== false) $types[$i] = 'N';
}
}
}
function adodb_transpose(&$arr, &$newarr, &$hdr, &$fobjs)
{
$oldX = sizeof(reset($arr));
$oldY = sizeof($arr);
if ($hdr) {
$startx = 1;
$hdr = array('Fields');
for ($y = 0; $y < $oldY; $y++) {
$hdr[] = $arr[$y][0];
}
} else
$startx = 0;
for ($x = $startx; $x < $oldX; $x++) {
if ($fobjs) {
$o = $fobjs[$x];
$newarr[] = array($o->name);
} else
$newarr[] = array();
for ($y = 0; $y < $oldY; $y++) {
$newarr[$x-$startx][] = $arr[$y][$x];
}
}
}
// Force key to upper.
// See also http://www.php.net/manual/en/function.array-change-key-case.php
function _array_change_key_case($an_array)
{
if (is_array($an_array)) {
$new_array = array();
foreach($an_array as $key=>$value)
$new_array[strtoupper($key)] = $value;
return $new_array;
}
return $an_array;
}
function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc)
{
if (count($fieldArray) == 0) return 0;
$first = true;
$uSet = '';
if (!is_array($keyCol)) {
$keyCol = array($keyCol);
}
foreach($fieldArray as $k => $v) {
if ($v === null) {
$v = 'NULL';
$fieldArray[$k] = $v;
} else if ($autoQuote && /*!is_numeric($v) /*and strncmp($v,"'",1) !== 0 -- sql injection risk*/ strcasecmp($v,$zthis->null2null)!=0) {
$v = $zthis->qstr($v);
$fieldArray[$k] = $v;
}
if (in_array($k,$keyCol)) continue; // skip UPDATE if is key
if ($first) {
$first = false;
$uSet = "$k=$v";
} else
$uSet .= ",$k=$v";
}
$where = false;
foreach ($keyCol as $v) {
if (isset($fieldArray[$v])) {
if ($where) $where .= ' and '.$v.'='.$fieldArray[$v];
else $where = $v.'='.$fieldArray[$v];
}
}
if ($uSet && $where) {
$update = "UPDATE $table SET $uSet WHERE $where";
$rs = $zthis->Execute($update);
if ($rs) {
if ($zthis->poorAffectedRows) {
/*
The Select count(*) wipes out any errors that the update would have returned.
http://phplens.com/lens/lensforum/msgs.php?id=5696
*/
if ($zthis->ErrorNo()<>0) return 0;
# affected_rows == 0 if update field values identical to old values
# for mysql - which is silly.
$cnt = $zthis->GetOne("select count(*) from $table where $where");
if ($cnt > 0) return 1; // record already exists
} else {
if (($zthis->Affected_Rows()>0)) return 1;
}
} else
return 0;
}
// print "<p>Error=".$this->ErrorNo().'<p>';
$first = true;
foreach($fieldArray as $k => $v) {
if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col
if ($first) {
$first = false;
$iCols = "$k";
$iVals = "$v";
} else {
$iCols .= ",$k";
$iVals .= ",$v";
}
}
$insert = "INSERT INTO $table ($iCols) VALUES ($iVals)";
$rs = $zthis->Execute($insert);
return ($rs) ? 2 : 0;
}
// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM
function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false,
$size=0, $selectAttr='',$compareFields0=true)
{
$hasvalue = false;
if ($multiple or is_array($defstr)) {
if ($size==0) $size=5;
$attr = ' multiple size="'.$size.'"';
if (!strpos($name,'[]')) $name .= '[]';
} else if ($size) $attr = ' size="'.$size.'"';
else $attr ='';
$s = '<select name="'.$name.'"'.$attr.' '.$selectAttr.'>';
if ($blank1stItem)
if (is_string($blank1stItem)) {
$barr = explode(':',$blank1stItem);
if (sizeof($barr) == 1) $barr[] = '';
$s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>";
} else $s .= "\n<option></option>";
if ($zthis->FieldCount() > 1) $hasvalue=true;
else $compareFields0 = true;
$value = '';
$optgroup = null;
$firstgroup = true;
$fieldsize = $zthis->FieldCount();
while(!$zthis->EOF) {
$zval = rtrim(reset($zthis->fields));
if ($blank1stItem && $zval=="") {
$zthis->MoveNext();
continue;
}
if ($fieldsize > 1) {
if (isset($zthis->fields[1]))
$zval2 = rtrim($zthis->fields[1]);
else
$zval2 = rtrim(next($zthis->fields));
}
$selected = ($compareFields0) ? $zval : $zval2;
$group = '';
if ($fieldsize > 2) {
$group = rtrim($zthis->fields[2]);
}
/*
if ($optgroup != $group) {
$optgroup = $group;
if ($firstgroup) {
$firstgroup = false;
$s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
} else {
$s .="\n</optgroup>";
$s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
}
}
*/
if ($hasvalue)
$value = " value='".htmlspecialchars($zval2)."'";
if (is_array($defstr)) {
if (in_array($selected,$defstr))
$s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
else
$s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
}
else {
if (strcasecmp($selected,$defstr)==0)
$s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
else
$s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
}
$zthis->MoveNext();
} // while
// closing last optgroup
if($optgroup != null) {
$s .= "\n</optgroup>";
}
return $s ."\n</select>\n";
}
// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM
function _adodb_getmenu_gp(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false,
$size=0, $selectAttr='',$compareFields0=true)
{
$hasvalue = false;
if ($multiple or is_array($defstr)) {
if ($size==0) $size=5;
$attr = ' multiple size="'.$size.'"';
if (!strpos($name,'[]')) $name .= '[]';
} else if ($size) $attr = ' size="'.$size.'"';
else $attr ='';
$s = '<select name="'.$name.'"'.$attr.' '.$selectAttr.'>';
if ($blank1stItem)
if (is_string($blank1stItem)) {
$barr = explode(':',$blank1stItem);
if (sizeof($barr) == 1) $barr[] = '';
$s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>";
} else $s .= "\n<option></option>";
if ($zthis->FieldCount() > 1) $hasvalue=true;
else $compareFields0 = true;
$value = '';
$optgroup = null;
$firstgroup = true;
$fieldsize = sizeof($zthis->fields);
while(!$zthis->EOF) {
$zval = rtrim(reset($zthis->fields));
if ($blank1stItem && $zval=="") {
$zthis->MoveNext();
continue;
}
if ($fieldsize > 1) {
if (isset($zthis->fields[1]))
$zval2 = rtrim($zthis->fields[1]);
else
$zval2 = rtrim(next($zthis->fields));
}
$selected = ($compareFields0) ? $zval : $zval2;
$group = '';
if (isset($zthis->fields[2])) {
$group = rtrim($zthis->fields[2]);
}
if ($optgroup != $group) {
$optgroup = $group;
if ($firstgroup) {
$firstgroup = false;
$s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
} else {
$s .="\n</optgroup>";
$s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
}
}
if ($hasvalue)
$value = " value='".htmlspecialchars($zval2)."'";
if (is_array($defstr)) {
if (in_array($selected,$defstr))
$s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
else
$s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
}
else {
if (strcasecmp($selected,$defstr)==0)
$s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
else
$s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
}
$zthis->MoveNext();
} // while
// closing last optgroup
if($optgroup != null) {
$s .= "\n</optgroup>";
}
return $s ."\n</select>\n";
}
/*
Count the number of records this sql statement will return by using
query rewriting heuristics...
Does not work with UNIONs, except with postgresql and oracle.
Usage:
$conn->Connect(...);
$cnt = _adodb_getcount($conn, $sql);
*/
function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
{
$qryRecs = 0;
if (!empty($zthis->_nestedSQL) || preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) ||
preg_match('/\s+GROUP\s+BY\s+/is',$sql) ||
preg_match('/\s+UNION\s+/is',$sql)) {
$rewritesql = adodb_strip_order_by($sql);
// ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias
// but this is only supported by oracle and postgresql...
if ($zthis->dataProvider == 'oci8') {
// Allow Oracle hints to be used for query optimization, Chris Wrye
if (preg_match('#/\\*+.*?\\*\\/#', $sql, $hint)) {
$rewritesql = "SELECT ".$hint[0]." COUNT(*) FROM (".$rewritesql.")";
} else
$rewritesql = "SELECT COUNT(*) FROM (".$rewritesql.")";
} else if (strncmp($zthis->databaseType,'postgres',8) == 0 || strncmp($zthis->databaseType,'mysql',5) == 0) {
$rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_";
} else {
$rewritesql = "SELECT COUNT(*) FROM ($rewritesql)";
}
} else {
// now replace SELECT ... FROM with SELECT COUNT(*) FROM
$rewritesql = preg_replace(
'/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql);
// fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails
// with mssql, access and postgresql. Also a good speedup optimization - skips sorting!
// also see http://phplens.com/lens/lensforum/msgs.php?id=12752
$rewritesql = adodb_strip_order_by($rewritesql);
}
if (isset($rewritesql) && $rewritesql != $sql) {
if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[0];
if ($secs2cache) {
// we only use half the time of secs2cache because the count can quickly
// become inaccurate if new records are added
$qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr);
} else {
$qryRecs = $zthis->GetOne($rewritesql,$inputarr);
}
if ($qryRecs !== false) return $qryRecs;
}
//--------------------------------------------
// query rewrite failed - so try slower way...
// strip off unneeded ORDER BY if no UNION
if (preg_match('/\s*UNION\s*/is', $sql)) $rewritesql = $sql;
else $rewritesql = $rewritesql = adodb_strip_order_by($sql);
if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[0];
if ($secs2cache) {
$rstest = $zthis->CacheExecute($secs2cache,$rewritesql,$inputarr);
if (!$rstest) $rstest = $zthis->CacheExecute($secs2cache,$sql,$inputarr);
} else {
$rstest = $zthis->Execute($rewritesql,$inputarr);
if (!$rstest) $rstest = $zthis->Execute($sql,$inputarr);
}
if ($rstest) {
$qryRecs = $rstest->RecordCount();
if ($qryRecs == -1) {
global $ADODB_EXTENSION;
// some databases will return -1 on MoveLast() - change to MoveNext()
if ($ADODB_EXTENSION) {
while(!$rstest->EOF) {
adodb_movenext($rstest);
}
} else {
while(!$rstest->EOF) {
$rstest->MoveNext();
}
}
$qryRecs = $rstest->_currentRow;
}
$rstest->Close();
if ($qryRecs == -1) return 0;
}
return $qryRecs;
}
/*
Code originally from "Cornel G" <conyg@fx.ro>
This code might not work with SQL that has UNION in it
Also if you are using CachePageExecute(), there is a strong possibility that
data will get out of synch. use CachePageExecute() only with tables that
rarely change.
*/
function _adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page,
$inputarr=false, $secs2cache=0)
{
$atfirstpage = false;
$atlastpage = false;
$lastpageno=1;
// If an invalid nrows is supplied,
// we assume a default value of 10 rows per page
if (!isset($nrows) || $nrows <= 0) $nrows = 10;
$qryRecs = false; //count records for no offset
$qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache);
$lastpageno = (int) ceil($qryRecs / $nrows);
$zthis->_maxRecordCount = $qryRecs;
// ***** Here we check whether $page is the last page or
// whether we are trying to retrieve
// a page number greater than the last page number.
if ($page >= $lastpageno) {
$page = $lastpageno;
$atlastpage = true;
}
// If page number <= 1, then we are at the first page
if (empty($page) || $page <= 1) {
$page = 1;
$atfirstpage = true;
}
// We get the data we want
$offset = $nrows * ($page-1);
if ($secs2cache > 0)
$rsreturn = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
else
$rsreturn = $zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
// Before returning the RecordSet, we set the pagination properties we need
if ($rsreturn) {
$rsreturn->_maxRecordCount = $qryRecs;
$rsreturn->rowsPerPage = $nrows;
$rsreturn->AbsolutePage($page);
$rsreturn->AtFirstPage($atfirstpage);
$rsreturn->AtLastPage($atlastpage);
$rsreturn->LastPageNo($lastpageno);
}
return $rsreturn;
}
// Iván Oliva version
function _adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0)
{
$atfirstpage = false;
$atlastpage = false;
if (!isset($page) || $page <= 1) { // If page number <= 1, then we are at the first page
$page = 1;
$atfirstpage = true;
}
if ($nrows <= 0) $nrows = 10; // If an invalid nrows is supplied, we assume a default value of 10 rows per page
// ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than
// the last page number.
$pagecounter = $page + 1;
$pagecounteroffset = ($pagecounter * $nrows) - $nrows;
if ($secs2cache>0) $rstest = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
else $rstest = $zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
if ($rstest) {
while ($rstest && $rstest->EOF && $pagecounter>0) {
$atlastpage = true;
$pagecounter--;
$pagecounteroffset = $nrows * ($pagecounter - 1);
$rstest->Close();
if ($secs2cache>0) $rstest = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
else $rstest = $zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
}
if ($rstest) $rstest->Close();
}
if ($atlastpage) { // If we are at the last page or beyond it, we are going to retrieve it
$page = $pagecounter;
if ($page == 1) $atfirstpage = true; // We have to do this again in case the last page is the same as the first
//... page, that is, the recordset has only 1 page.
}
// We get the data we want
$offset = $nrows * ($page-1);
if ($secs2cache > 0) $rsreturn = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
else $rsreturn = $zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
// Before returning the RecordSet, we set the pagination properties we need
if ($rsreturn) {
$rsreturn->rowsPerPage = $nrows;
$rsreturn->AbsolutePage($page);
$rsreturn->AtFirstPage($atfirstpage);
$rsreturn->AtLastPage($atlastpage);
}
return $rsreturn;
}
function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=2)
{
global $ADODB_QUOTE_FIELDNAMES;
if (!$rs) {
printf(ADODB_BAD_RS,'GetUpdateSQL');
return false;
}
$fieldUpdatedCount = 0;
$arrFields = _array_change_key_case($arrFields);
$hasnumeric = isset($rs->fields[0]);
$setFields = '';
// Loop through all of the fields in the recordset
for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
// Get the field from the recordset
$field = $rs->FetchField($i);
// If the recordset field is one
// of the fields passed in then process.
$upperfname = strtoupper($field->name);
if (adodb_key_exists($upperfname,$arrFields,$force)) {
// If the existing field value in the recordset
// is different from the value passed in then
// go ahead and append the field name and new value to
// the update query.
if ($hasnumeric) $val = $rs->fields[$i];
else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname];
else if (isset($rs->fields[$field->name])) $val = $rs->fields[$field->name];
else if (isset($rs->fields[strtolower($upperfname)])) $val = $rs->fields[strtolower($upperfname)];
else $val = '';
if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) {
// Set the counter for the number of fields that will be updated.
$fieldUpdatedCount++;
// Based on the datatype of the field
// Format the value properly for the database
$type = $rs->MetaType($field->type);
if ($type == 'null') {
$type = 'C';
}
if ((strpos($upperfname,' ') !== false) || ($ADODB_QUOTE_FIELDNAMES)) {
switch (ADODB_QUOTE_FIELDNAMES) {
case 'LOWER':
$fnameq = $zthis->nameQuote.strtolower($field->name).$zthis->nameQuote;break;
case 'NATIVE':
$fnameq = $zthis->nameQuote.$field->name.$zthis->nameQuote;break;
case 'UPPER':
default:
$fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote;break;
}
} else
$fnameq = $upperfname;
// is_null requires php 4.0.4
//********************************************************//
if (is_null($arrFields[$upperfname])
|| (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0)
|| $arrFields[$upperfname] === $zthis->null2null
)
{
switch ($force) {
//case 0:
// //Ignore empty values. This is allready handled in "adodb_key_exists" function.
//break;
case 1:
//Set null
$setFields .= $field->name . " = null, ";
break;
case 2:
//Set empty
$arrFields[$upperfname] = "";
$setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq);
break;
default:
case 3:
//Set the value that was given in array, so you can give both null and empty values
if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === $zthis->null2null) {
$setFields .= $field->name . " = null, ";
} else {
$setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq);
}
break;
}
//********************************************************//
} else {
//we do this so each driver can customize the sql for
//DB specific column types.
//Oracle needs BLOB types to be handled with a returning clause
//postgres has special needs as well
$setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,
$arrFields, $magicq);
}
}
}
}
// If there were any modified fields then build the rest of the update query.
if ($fieldUpdatedCount > 0 || $forceUpdate) {
// Get the table name from the existing query.
if (!empty($rs->tableName)) $tableName = $rs->tableName;
else {
preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);
$tableName = $tableName[1];
}
// Get the full where clause excluding the word "WHERE" from
// the existing query.
preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause);
$discard = false;
// not a good hack, improvements?
if ($whereClause) {
#var_dump($whereClause);
if (preg_match('/\s(ORDER\s.*)/is', $whereClause[1], $discard));
else if (preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard));
else if (preg_match('/\s(FOR UPDATE.*)/is', $whereClause[1], $discard));
else preg_match('/\s.*(\) WHERE .*)/is', $whereClause[1], $discard); # see http://sourceforge.net/tracker/index.php?func=detail&aid=1379638&group_id=42718&atid=433976
} else
$whereClause = array(false,false);
if ($discard)
$whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1]));
$sql = 'UPDATE '.$tableName.' SET '.substr($setFields, 0, -2);
if (strlen($whereClause[1]) > 0)
$sql .= ' WHERE '.$whereClause[1];
return $sql;
} else {
return false;
}
}
function adodb_key_exists($key, &$arr,$force=2)
{
if ($force<=0) {
// the following is the old behaviour where null or empty fields are ignored
return (!empty($arr[$key])) || (isset($arr[$key]) && strlen($arr[$key])>0);
}
if (isset($arr[$key])) return true;
## null check below
if (ADODB_PHPVER >= 0x4010) return array_key_exists($key,$arr);
return false;
}
/**
* There is a special case of this function for the oci8 driver.
* The proper way to handle an insert w/ a blob in oracle requires
* a returning clause with bind variables and a descriptor blob.
*
*
*/
function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$force=2)
{
static $cacheRS = false;
static $cacheSig = 0;
static $cacheCols;
global $ADODB_QUOTE_FIELDNAMES;
$tableName = '';
$values = '';
$fields = '';
$recordSet = null;
$arrFields = _array_change_key_case($arrFields);
$fieldInsertedCount = 0;
if (is_string($rs)) {
//ok we have a table name
//try and get the column info ourself.
$tableName = $rs;
//we need an object for the recordSet
//because we have to call MetaType.
//php can't do a $rsclass::MetaType()
$rsclass = $zthis->rsPrefix.$zthis->databaseType;
$recordSet = new $rsclass(-1,$zthis->fetchMode);
$recordSet->connection = $zthis;
if (is_string($cacheRS) && $cacheRS == $rs) {
$columns = $cacheCols;
} else {
$columns = $zthis->MetaColumns( $tableName );
$cacheRS = $tableName;
$cacheCols = $columns;
}
} else if (is_subclass_of($rs, 'adorecordset')) {
if (isset($rs->insertSig) && is_integer($cacheRS) && $cacheRS == $rs->insertSig) {
$columns = $cacheCols;
} else {
for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++)
$columns[] = $rs->FetchField($i);
$cacheRS = $cacheSig;
$cacheCols = $columns;
$rs->insertSig = $cacheSig++;
}
$recordSet = $rs;
} else {
printf(ADODB_BAD_RS,'GetInsertSQL');
return false;
}
// Loop through all of the fields in the recordset
foreach( $columns as $field ) {
$upperfname = strtoupper($field->name);
if (adodb_key_exists($upperfname,$arrFields,$force)) {
$bad = false;
if ((strpos($upperfname,' ') !== false) || ($ADODB_QUOTE_FIELDNAMES)) {
switch (ADODB_QUOTE_FIELDNAMES) {
case 'LOWER':
$fnameq = $zthis->nameQuote.strtolower($field->name).$zthis->nameQuote;break;
case 'NATIVE':
$fnameq = $zthis->nameQuote.$field->name.$zthis->nameQuote;break;
case 'UPPER':
default:
$fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote;break;
}
} else
$fnameq = $upperfname;
$type = $recordSet->MetaType($field->type);
/********************************************************/
if (is_null($arrFields[$upperfname])
|| (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0)
|| $arrFields[$upperfname] === $zthis->null2null
)
{
switch ($force) {
case 0: // we must always set null if missing
$bad = true;
break;
case 1:
$values .= "null, ";
break;
case 2:
//Set empty
$arrFields[$upperfname] = "";
$values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq,$arrFields, $magicq);
break;
default:
case 3:
//Set the value that was given in array, so you can give both null and empty values
if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === $zthis->null2null) {
$values .= "null, ";
} else {
$values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq, $arrFields, $magicq);
}
break;
} // switch
/*********************************************************/
} else {
//we do this so each driver can customize the sql for
//DB specific column types.
//Oracle needs BLOB types to be handled with a returning clause
//postgres has special needs as well
$values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq,
$arrFields, $magicq);
}
if ($bad) continue;
// Set the counter for the number of fields that will be inserted.
$fieldInsertedCount++;
// Get the name of the fields to insert
$fields .= $fnameq . ", ";
}
}
// If there were any inserted fields then build the rest of the insert query.
if ($fieldInsertedCount <= 0) return false;
// Get the table name from the existing query.
if (!$tableName) {
if (!empty($rs->tableName)) $tableName = $rs->tableName;
else if (preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName))
$tableName = $tableName[1];
else
return false;
}
// Strip off the comma and space on the end of both the fields
// and their values.
$fields = substr($fields, 0, -2);
$values = substr($values, 0, -2);
// Append the fields and their values to the insert query.
return 'INSERT INTO '.$tableName.' ( '.$fields.' ) VALUES ( '.$values.' )';
}
/**
* This private method is used to help construct
* the update/sql which is generated by GetInsertSQL and GetUpdateSQL.
* It handles the string construction of 1 column -> sql string based on
* the column type. We want to do 'safe' handling of BLOBs
*
* @param string the type of sql we are trying to create
* 'I' or 'U'.
* @param string column data type from the db::MetaType() method
* @param string the column name
* @param array the column value
*
* @return string
*
*/
function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $fnameq, $arrFields, $magicq)
{
$sql = '';
// Based on the datatype of the field
// Format the value properly for the database
switch($type) {
case 'B':
//in order to handle Blobs correctly, we need
//to do some magic for Oracle
//we need to create a new descriptor to handle
//this properly
if (!empty($zthis->hasReturningInto)) {
if ($action == 'I') {
$sql = 'empty_blob(), ';
} else {
$sql = $fnameq. '=empty_blob(), ';
}
//add the variable to the returning clause array
//so the user can build this later in
//case they want to add more to it
$zthis->_returningArray[$fname] = ':xx'.$fname.'xx';
} else if (empty($arrFields[$fname])){
if ($action == 'I') {
$sql = 'empty_blob(), ';
} else {
$sql = $fnameq. '=empty_blob(), ';
}
} else {
//this is to maintain compatibility
//with older adodb versions.
$sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false);
}
break;
case "X":
//we need to do some more magic here for long variables
//to handle these correctly in oracle.
//create a safe bind var name
//to avoid conflicts w/ dupes.
if (!empty($zthis->hasReturningInto)) {
if ($action == 'I') {
$sql = ':xx'.$fname.'xx, ';
} else {
$sql = $fnameq.'=:xx'.$fname.'xx, ';
}
//add the variable to the returning clause array
//so the user can build this later in
//case they want to add more to it
$zthis->_returningArray[$fname] = ':xx'.$fname.'xx';
} else {
//this is to maintain compatibility
//with older adodb versions.
$sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false);
}
break;
default:
$sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false);
break;
}
return $sql;
}
function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq, $recurse=true)
{
if ($recurse) {
switch($zthis->dataProvider) {
case 'postgres':
if ($type == 'L') $type = 'C';
break;
case 'oci8':
return _adodb_column_sql_oci8($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq);
}
}
switch($type) {
case "C":
case "X":
case 'B':
$val = $zthis->qstr($arrFields[$fname],$magicq);
break;
case "D":
$val = $zthis->DBDate($arrFields[$fname]);
break;
case "T":
$val = $zthis->DBTimeStamp($arrFields[$fname]);
break;
case "N":
$val = $arrFields[$fname];
if (!is_numeric($val)) $val = str_replace(',', '.', (float)$val);
break;
case "I":
case "R":
$val = $arrFields[$fname];
if (!is_numeric($val)) $val = (integer) $val;
break;
default:
$val = str_replace(array("'"," ","("),"",$arrFields[$fname]); // basic sql injection defence
if (empty($val)) $val = '0';
break;
}
if ($action == 'I') return $val . ", ";
return $fnameq . "=" . $val . ", ";
}
function _adodb_debug_execute(&$zthis, $sql, $inputarr)
{
$ss = '';
if ($inputarr) {
foreach($inputarr as $kk=>$vv) {
if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...';
if (is_null($vv)) $ss .= "($kk=>null) ";
else $ss .= "($kk=>'$vv') ";
}
$ss = "[ $ss ]";
}
$sqlTxt = is_array($sql) ? $sql[0] : $sql;
/*str_replace(', ','##1#__^LF',is_array($sql) ? $sql[0] : $sql);
$sqlTxt = str_replace(',',', ',$sqlTxt);
$sqlTxt = str_replace('##1#__^LF', ', ' ,$sqlTxt);
*/
// check if running from browser or command-line
$inBrowser = isset($_SERVER['HTTP_USER_AGENT']);
$dbt = $zthis->databaseType;
if (isset($zthis->dsnType)) $dbt .= '-'.$zthis->dsnType;
if ($inBrowser) {
if ($ss) {
$ss = '<code>'.htmlspecialchars($ss).'</code>';
}
if ($zthis->debug === -1)
ADOConnection::outp( "<br>\n($dbt): ".htmlspecialchars($sqlTxt)." $ss\n<br>\n",false);
else if ($zthis->debug !== -99)
ADOConnection::outp( "<hr>\n($dbt): ".htmlspecialchars($sqlTxt)." $ss\n<hr>\n",false);
} else {
$ss = "\n ".$ss;
if ($zthis->debug !== -99)
ADOConnection::outp("-----<hr>\n($dbt): ".$sqlTxt." $ss\n-----<hr>\n",false);
}
$qID = $zthis->_query($sql,$inputarr);
/*
Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql
because ErrorNo() calls Execute('SELECT @ERROR'), causing recursion
*/
if ($zthis->databaseType == 'mssql') {
// ErrorNo is a slow function call in mssql, and not reliable in PHP 4.0.6
if($emsg = $zthis->ErrorMsg()) {
if ($err = $zthis->ErrorNo()) {
if ($zthis->debug === -99)
ADOConnection::outp( "<hr>\n($dbt): ".htmlspecialchars($sqlTxt)." $ss\n<hr>\n",false);
ADOConnection::outp($err.': '.$emsg);
}
}
} else if (!$qID) {
if ($zthis->debug === -99)
if ($inBrowser) ADOConnection::outp( "<hr>\n($dbt): ".htmlspecialchars($sqlTxt)." $ss\n<hr>\n",false);
else ADOConnection::outp("-----<hr>\n($dbt): ".$sqlTxt."$ss\n-----<hr>\n",false);
ADOConnection::outp($zthis->ErrorNo() .': '. $zthis->ErrorMsg());
}
if ($zthis->debug === 99) _adodb_backtrace(true,9999,2);
return $qID;
}
# pretty print the debug_backtrace function
function _adodb_backtrace($printOrArr=true,$levels=9999,$skippy=0,$ishtml=null)
{
if (!function_exists('debug_backtrace')) return '';
if ($ishtml === null) $html = (isset($_SERVER['HTTP_USER_AGENT']));
else $html = $ishtml;
$fmt = ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";
$MAXSTRLEN = 128;
$s = ($html) ? '<pre align=left>' : '';
if (is_array($printOrArr)) $traceArr = $printOrArr;
else $traceArr = debug_backtrace();
array_shift($traceArr);
array_shift($traceArr);
$tabs = sizeof($traceArr)-2;
foreach ($traceArr as $arr) {
if ($skippy) {$skippy -= 1; continue;}
$levels -= 1;
if ($levels < 0) break;
$args = array();
for ($i=0; $i < $tabs; $i++) $s .= ($html) ? ' ' : "\t";
$tabs -= 1;
if ($html) $s .= '<font face="Courier New,Courier">';
if (isset($arr['class'])) $s .= $arr['class'].'.';
if (isset($arr['args']))
foreach($arr['args'] as $v) {
if (is_null($v)) $args[] = 'null';
else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
else if (is_object($v)) $args[] = 'Object:'.get_class($v);
else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
else {
$v = (string) @$v;
$str = htmlspecialchars(str_replace(array("\r","\n"),' ',substr($v,0,$MAXSTRLEN)));
if (strlen($v) > $MAXSTRLEN) $str .= '...';
$args[] = $str;
}
}
$s .= $arr['function'].'('.implode(', ',$args).')';
$s .= @sprintf($fmt, $arr['line'],$arr['file'],basename($arr['file']));
$s .= "\n";
}
if ($html) $s .= '</pre>';
if ($printOrArr) print $s;
return $s;
}
/*
function _adodb_find_from($sql)
{
$sql = str_replace(array("\n","\r"), ' ', $sql);
$charCount = strlen($sql);
$inString = false;
$quote = '';
$parentheseCount = 0;
$prevChars = '';
$nextChars = '';
for($i = 0; $i < $charCount; $i++) {
$char = substr($sql,$i,1);
$prevChars = substr($sql,0,$i);
$nextChars = substr($sql,$i+1);
if((($char == "'" || $char == '"' || $char == '`') && substr($prevChars,-1,1) != '\\') && $inString === false) {
$quote = $char;
$inString = true;
}
elseif((($char == "'" || $char == '"' || $char == '`') && substr($prevChars,-1,1) != '\\') && $inString === true && $quote == $char) {
$quote = "";
$inString = false;
}
elseif($char == "(" && $inString === false)
$parentheseCount++;
elseif($char == ")" && $inString === false && $parentheseCount > 0)
$parentheseCount--;
elseif($parentheseCount <= 0 && $inString === false && $char == " " && strtoupper(substr($prevChars,-5,5)) == " FROM")
return $i;
}
}
*/
?>
| gpl-3.0 |
structr/structr | structr-core/src/main/java/org/structr/schema/parser/NumericalPropertyParser.java | 3373 | /*
* Copyright (C) 2010-2021 Structr GmbH
*
* This file is part of Structr <http://structr.org>.
*
* Structr 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.
*
* Structr 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 Structr. If not, see <http://www.gnu.org/licenses/>.
*/
package org.structr.schema.parser;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.structr.common.error.ErrorBuffer;
import org.structr.common.error.FrameworkException;
import org.structr.common.error.InvalidPropertySchemaToken;
import org.structr.core.entity.SchemaNode;
import org.structr.schema.Schema;
/**
*
*
*/
public abstract class NumericalPropertyParser extends PropertySourceGenerator {
private Number lowerBound = null;
private Number upperBound = null;
private boolean lowerExclusive = false;
private boolean upperExclusive = false;
public NumericalPropertyParser(final ErrorBuffer errorBuffer, final String className, final PropertyDefinition params) {
super(errorBuffer, className, params);
}
public abstract Number parseNumber(final ErrorBuffer errorBuffer, final String source, final String which);
@Override
public String getPropertyParameters() {
return "";
}
@Override
public void parseFormatString(final Map<String, SchemaNode> schemaNodes, final Schema entity, final String expression) throws FrameworkException {
boolean error = false;
final String rangeFormatErrorMessage = "Range expression must describe a (possibly open-ended) interval, e.g. [10,99] or ]9,100[ for all two-digit integers";
if (StringUtils.isNotBlank(expression)) {
if ((expression.startsWith("[") || expression.startsWith("]")) && (expression.endsWith("[") || expression.endsWith("]"))) {
final String range = expression.substring(1, expression.length()-1);
final String[] parts = range.split(",+");
if (parts.length == 2) {
lowerBound = parseNumber(getErrorBuffer(), parts[0].trim(), "lower");
upperBound = parseNumber(getErrorBuffer(), parts[1].trim(), "upper");
if (lowerBound == null || upperBound == null) {
error = true;
}
lowerExclusive = expression.startsWith("]");
upperExclusive = expression.endsWith("[");
} else {
error = true;
}
if (!error) {
addGlobalValidator(new Validator("isValid" + getUnqualifiedValueType() + "InRange", getClassName(), getSourcePropertyName(), expression));
}
} else {
error = true;
}
}
if (error) {
reportError(new InvalidPropertySchemaToken(SchemaNode.class.getSimpleName(), source.getPropertyName(), expression, "invalid_range_expression", rangeFormatErrorMessage));
}
}
public Number getLowerBound() {
return lowerBound;
}
public Number getUpperBound() {
return upperBound;
}
public boolean isLowerExclusive() {
return lowerExclusive;
}
public boolean isUpperExclusive() {
return upperExclusive;
}
}
| gpl-3.0 |
OpenCFD/OpenFOAM-1.7.x | src/postProcessing/functionObjects/field/fieldValues/cellSource/cellSourceFunctionObject.H | 1875 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2009-2010 OpenCFD Ltd.
\\/ 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/>.
Typedef
Foam::cellSourceFunctionObject
Description
FunctionObject wrapper around cellSource to allow it to be
created via the functions entry within controlDict.
SourceFiles
cellSourceFunctionObject.C
\*---------------------------------------------------------------------------*/
#ifndef cellSourceFunctionObject_H
#define cellSourceFunctionObject_H
#include "cellSource.H"
#include "OutputFilterFunctionObject.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
typedef OutputFilterFunctionObject<fieldValues::cellSource>
cellSourceFunctionObject;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| gpl-3.0 |
tomours/dolibarr | htdocs/admin/ticketsup.php | 26500 | <?php
/* Copyright (C) 2013-2018 Jean-François FERRY <hello@librethic.io>
* Copyright (C) 2016 Christophe Battarel <christophe@altairis.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 admin/ticketsup.php
* \ingroup ticketsup
* \brief This file is a module setup page
*/
require '../main.inc.php';
require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php";
require_once DOL_DOCUMENT_ROOT."/ticketsup/class/ticketsup.class.php";
require_once DOL_DOCUMENT_ROOT."/core/lib/ticketsup.lib.php";
// Translations
$langs->load("ticketsup");
// Access control
if (!$user->admin) {
accessforbidden();
}
// Parameters
$value = GETPOST('value', 'alpha');
$action = GETPOST('action', 'alpha');
$label = GETPOST('label', 'alpha');
$scandir = GETPOST('scandir', 'alpha');
$type = 'ticketsup';
if ($action == 'updateMask') {
$maskconstticket = GETPOST('maskconstticketsup', 'alpha');
$maskticket = GETPOST('maskticketsup', 'alpha');
if ($maskconstticket) {
$res = dolibarr_set_const($db, $maskconstticket, $maskticket, 'chaine', 0, '', $conf->entity);
}
if (!$res > 0) {
$error++;
}
if (!$error) {
setEventMessage($langs->trans("SetupSaved"));
} else {
setEventMessage($langs->trans("Error"), 'errors');
}
} elseif ($action == 'setmod') {
// TODO Verifier si module numerotation choisi peut etre active
// par appel methode canBeActivated
dolibarr_set_const($db, "TICKETSUP_ADDON", $value, 'chaine', 0, '', $conf->entity);
} elseif ($action == 'setvar') {
include_once DOL_DOCUMENT_ROOT . "/core/lib/files.lib.php";
$notification_email = GETPOST('TICKETS_NOTIFICATION_EMAIL_FROM', 'alpha');
if (!empty($notification_email)) {
$res = dolibarr_set_const($db, 'TICKETS_NOTIFICATION_EMAIL_FROM', $notification_email, 'chaine', 0, '', $conf->entity);
} else {
$res = dolibarr_set_const($db, 'TICKETS_NOTIFICATION_EMAIL_FROM', '', 'chaine', 0, '', $conf->entity);
}
if (!$res > 0) {
$error++;
}
// altairis : differentiate notification email FROM and TO
$notification_email_to = GETPOST('TICKETS_NOTIFICATION_EMAIL_TO', 'alpha');
if (!empty($notification_email_to)) {
$res = dolibarr_set_const($db, 'TICKETS_NOTIFICATION_EMAIL_TO', $notification_email_to, 'chaine', 0, '', $conf->entity);
} else {
$res = dolibarr_set_const($db, 'TICKETS_NOTIFICATION_EMAIL_TO', '', 'chaine', 0, '', $conf->entity);
}
if (!$res > 0) {
$error++;
}
$mail_new_ticket = GETPOST('TICKETS_MESSAGE_MAIL_NEW', 'alpha');
if (!empty($mail_new_ticket)) {
$res = dolibarr_set_const($db, 'TICKETS_MESSAGE_MAIL_NEW', $mail_new_ticket, 'chaine', 0, '', $conf->entity);
} else {
$res = dolibarr_set_const($db, 'TICKETS_MESSAGE_MAIL_NEW', $langs->trans('TicketMessageMailNewText'), 'chaine', 0, '', $conf->entity);
}
if (!$res > 0) {
$error++;
}
$mail_intro = GETPOST('TICKETS_MESSAGE_MAIL_INTRO', 'alpha');
if (!empty($mail_intro)) {
$res = dolibarr_set_const($db, 'TICKETS_MESSAGE_MAIL_INTRO', $mail_intro, 'chaine', 0, '', $conf->entity);
} else {
$res = dolibarr_set_const($db, 'TICKETS_MESSAGE_MAIL_INTRO', $langs->trans('TicketMessageMailIntroText'), 'chaine', 0, '', $conf->entity);
}
if (!$res > 0) {
$error++;
}
$mail_signature = GETPOST('TICKETS_MESSAGE_MAIL_SIGNATURE', 'alpha');
if (!empty($mail_signature)) {
$res = dolibarr_set_const($db, 'TICKETS_MESSAGE_MAIL_SIGNATURE', $mail_signature, 'chaine', 0, '', $conf->entity);
} else {
$res = dolibarr_set_const($db, 'TICKETS_MESSAGE_MAIL_SIGNATURE', $langs->trans('TicketMessageMailSignatureText'), 'chaine', 0, '', $conf->entity);
}
if (!$res > 0) {
$error++;
}
$url_interface = GETPOST('TICKETS_URL_PUBLIC_INTERFACE', 'alpha');
if (!empty($mail_signature)) {
$res = dolibarr_set_const($db, 'TICKETS_URL_PUBLIC_INTERFACE', $url_interface, 'chaine', 0, '', $conf->entity);
} else {
$res = dolibarr_set_const($db, 'TICKETS_URL_PUBLIC_INTERFACE', '', 'chaine', 0, '', $conf->entity);
}
if (!$res > 0) {
$error++;
}
$topic_interface = GETPOST('TICKETS_PUBLIC_INTERFACE_TOPIC', 'alpha');
if (!empty($mail_signature)) {
$res = dolibarr_set_const($db, 'TICKETS_PUBLIC_INTERFACE_TOPIC', $topic_interface, 'chaine', 0, '', $conf->entity);
} else {
$res = dolibarr_set_const($db, 'TICKETS_PUBLIC_INTERFACE_TOPIC', '', 'chaine', 0, '', $conf->entity);
}
if (!$res > 0) {
$error++;
}
$text_home = GETPOST('TICKETS_PUBLIC_TEXT_HOME', 'alpha');
if (!empty($mail_signature)) {
$res = dolibarr_set_const($db, 'TICKETS_PUBLIC_TEXT_HOME', $text_home, 'chaine', 0, '', $conf->entity);
} else {
$res = dolibarr_set_const($db, 'TICKETS_PUBLIC_TEXT_HOME', $langs->trans('TicketPublicInterfaceTextHome'), 'chaine', 0, '', $conf->entity);
}
if (!$res > 0) {
$error++;
}
$text_help = GETPOST('TICKETS_PUBLIC_TEXT_HELP_MESSAGE', 'alpha');
if (!empty($text_help)) {
$res = dolibarr_set_const($db, 'TICKETS_PUBLIC_TEXT_HELP_MESSAGE', $text_help, 'chaine', 0, '', $conf->entity);
} else {
$res = dolibarr_set_const($db, 'TICKETS_PUBLIC_TEXT_HELP_MESSAGE', $langs->trans('TicketPublicPleaseBeAccuratelyDescribe'), 'chaine', 0, '', $conf->entity);
}
if (!$res > 0) {
$error++;
}
}
if ($action == 'setvarother') {
$param_enable_public_interface = GETPOST('TICKETS_ENABLE_PUBLIC_INTERFACE', 'alpha');
$res = dolibarr_set_const($db, 'TICKETS_ENABLE_PUBLIC_INTERFACE', $param_enable_public_interface, 'chaine', 0, '', $conf->entity);
if (!$res > 0) {
$error++;
}
$param_must_exists = GETPOST('TICKETS_EMAIL_MUST_EXISTS', 'alpha');
$res = dolibarr_set_const($db, 'TICKETS_EMAIL_MUST_EXISTS', $param_must_exists, 'chaine', 0, '', $conf->entity);
if (!$res > 0) {
$error++;
}
$param_disable_email = GETPOST('TICKETS_DISABLE_ALL_MAILS', 'alpha');
$res = dolibarr_set_const($db, 'TICKETS_DISABLE_ALL_MAILS', $param_disable_email, 'chaine', 0, '', $conf->entity);
if (!$res > 0) {
$error++;
}
$param_activate_log_by_email = GETPOST('TICKETS_ACTIVATE_LOG_BY_EMAIL', 'alpha');
$res = dolibarr_set_const($db, 'TICKETS_ACTIVATE_LOG_BY_EMAIL', $param_activate_log_by_email, 'chaine', 0, '', $conf->entity);
if (!$res > 0) {
$error++;
}
if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
{
$param_show_module_logo = GETPOST('TICKETS_SHOW_MODULE_LOGO', 'alpha');
$res = dolibarr_set_const($db, 'TICKETS_SHOW_MODULE_LOGO', $param_show_module_logo, 'chaine', 0, '', $conf->entity);
if (!$res > 0) {
$error++;
}
}
if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
{
$param_notification_also_main_addressemail = GETPOST('TICKETS_NOTIFICATION_ALSO_MAIN_ADDRESS', 'alpha');
$res = dolibarr_set_const($db, 'TICKETS_NOTIFICATION_ALSO_MAIN_ADDRESS', $param_notification_also_main_addressemail, 'chaine', 0, '', $conf->entity);
if (!$res > 0) {
$error++;
}
}
$param_limit_view = GETPOST('TICKETS_LIMIT_VIEW_ASSIGNED_ONLY', 'alpha');
$res = dolibarr_set_const($db, 'TICKETS_LIMIT_VIEW_ASSIGNED_ONLY', $param_limit_view, 'chaine', 0, '', $conf->entity);
if (!$res > 0) {
$error++;
}
$param_auto_assign = GETPOST('TICKETS_AUTO_ASSIGN_USER_CREATE', 'alpha');
$res = dolibarr_set_const($db, 'TICKETS_AUTO_ASSIGN_USER_CREATE', $param_auto_assign, 'chaine', 0, '', $conf->entity);
if (!$res > 0) {
$error++;
}
}
/*
* View
*/
$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
$form = new Form($db);
$help_url = "FR:Module_Ticket";
$page_name = "TicketsupSetup";
llxHeader('', $langs->trans($page_name), $help_url);
// Subheader
$linkback = '<a href="' . DOL_URL_ROOT . '/admin/modules.php">' . $langs->trans("BackToModuleList") . '</a>';
print load_fiche_titre($langs->trans($page_name), $linkback, 'title_setup');
// Configuration header
$head = ticketsupAdminPrepareHead();
dol_fiche_head($head, 'settings', $langs->trans("Module56000Name"), -1, "ticketsup");
print $langs->trans("TicketsupSetupDictionaries") . ' : <a href="' . dol_buildpath('/admin/dict.php', 1) . '" >' . dol_buildpath('/admin/dict.php', 2) . '</a><br>';
print $langs->trans("TicketsupPublicAccess") . ' : <a href="' . dol_buildpath('/public/ticketsup/index.php', 1) . '" target="_blank" >' . dol_buildpath('/public/ticketsup/index.php', 2) . '</a>';
dol_fiche_end();
/*
* Projects Numbering model
*/
print_titre($langs->trans("TicketSupNumberingModules"));
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre">';
print '<td width="100">' . $langs->trans("Name") . '</td>';
print '<td>' . $langs->trans("Description") . '</td>';
print '<td>' . $langs->trans("Example") . '</td>';
print '<td align="center" width="60">' . $langs->trans("Activated") . '</td>';
print '<td align="center" width="80">' . $langs->trans("ShortInfo") . '</td>';
print "</tr>\n";
clearstatcache();
foreach ($dirmodels as $reldir) {
$dir = dol_buildpath($reldir . "core/modules/ticketsup/");
if (is_dir($dir)) {
$handle = opendir($dir);
if (is_resource($handle)) {
while (($file = readdir($handle)) !== false) {
if (preg_match('/^(mod_.*)\.php$/i', $file, $reg)) {
$file = $reg[1];
$classname = substr($file, 4);
include_once $dir . $file . '.php';
$module = new $file;
// Show modules according to features level
if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) {
continue;
}
if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) {
continue;
}
if ($module->isEnabled()) {
print '<tr class="oddeven"><td>' . $module->name . "</td><td>\n";
print $module->info();
print '</td>';
// Show example of numbering model
print '<td class="nowrap">';
$tmp = $module->getExample();
if (preg_match('/^Error/', $tmp)) {
print '<div class="error">' . $langs->trans($tmp) . '</div>';
} elseif ($tmp == 'NotConfigured') {
print $langs->trans($tmp);
} else {
print $tmp;
}
print '</td>' . "\n";
print '<td align="center">';
if ($conf->global->TICKETSUP_ADDON == 'mod_' . $classname) {
print img_picto($langs->trans("Activated"), 'switch_on');
} else {
print '<a href="' . $_SERVER["PHP_SELF"] . '?action=setmod&value=mod_' . $classname . '" alt="' . $langs->trans("Default") . '">' . img_picto($langs->trans("Disabled"), 'switch_off') . '</a>';
}
print '</td>';
$ticket = new Ticketsup($db);
$ticket->initAsSpecimen();
// Info
$htmltooltip = '';
$htmltooltip .= '' . $langs->trans("Version") . ': <b>' . $module->getVersion() . '</b><br>';
$nextval = $module->getNextValue($mysoc, $ticket);
if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval
$htmltooltip .= '' . $langs->trans("NextValue") . ': ';
if ($nextval) {
$htmltooltip .= $nextval . '<br>';
} else {
$htmltooltip .= $langs->trans($module->error) . '<br>';
}
}
print '<td align="center">';
print $form->textwithpicto('', $htmltooltip, 1, 0);
print '</td>';
print '</tr>';
}
}
}
closedir($handle);
}
}
}
print '</table><br>';
if (!$conf->use_javascript_ajax) {
print '<form method="post" action="' . $_SERVER['PHP_SELF'] . '" enctype="multipart/form-data" >';
print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
print '<input type="hidden" name="action" value="setvarother">';
}
print_titre($langs->trans("TicketParamPublicInterface"));
print '<table class="noborder" width="100%">';
// Activate public interface
print '<tr class="pair"><td width="70%">' . $langs->trans("TicketsActivatePublicInterface") . '</td>';
print '<td align="left">';
if ($conf->use_javascript_ajax) {
print ajax_constantonoff('TICKETS_ENABLE_PUBLIC_INTERFACE');
} else {
$arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
print $form->selectarray("TICKETS_ENABLE_PUBLIC_INTERFACE", $arrval, $conf->global->TICKETS_ENABLE_PUBLIC_INTERFACE);
}
print '</td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketsActivatePublicInterfaceHelp"), 1, 'help');
print '</td>';
print '</tr>';
// Check if email exists
print '<tr class="pair"><td width="70%">' . $langs->trans("TicketsEmailMustExist") . '</td>';
print '<td align="left">';
if ($conf->use_javascript_ajax) {
print ajax_constantonoff('TICKETS_EMAIL_MUST_EXISTS');
} else {
$arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
print $form->selectarray("TICKETS_EMAIL_MUST_EXISTS", $arrval, $conf->global->TICKETS_EMAIL_MUST_EXISTS);
}
print '</td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketsEmailMustExistHelp"), 1, 'help');
print '</td>';
print '</tr>';
/*if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
{
// Show logo for module
print '<tr class="pair"><td width="70%">' . $langs->trans("TicketsShowModuleLogo") . '</td>';
print '<td align="left">';
if ($conf->use_javascript_ajax) {
print ajax_constantonoff('TICKETS_SHOW_MODULE_LOGO');
} else {
$arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
print $form->selectarray("TICKETS_SHOW_MODULE_LOGO", $arrval, $conf->global->TICKETS_SHOW_MODULE_LOGO);
}
print '</td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketsShowModuleLogoHelp"), 1, 'help');
print '</td>';
print '</tr>';
}*/
// Show logo for company
print '<tr class="pair"><td width="70%">' . $langs->trans("TicketsShowCompanyLogo") . '</td>';
print '<td align="left">';
if ($conf->use_javascript_ajax) {
print ajax_constantonoff('TICKETS_SHOW_COMPANY_LOGO');
} else {
$arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
print $form->selectarray("TICKETS_SHOW_COMPANY_LOGO", $arrval, $conf->global->TICKETS_SHOW_COMPANY_LOGO);
}
print '</td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketsShowCompanyLogoHelp"), 1, 'help');
print '</td>';
print '</tr>';
print '</table><br>';
print_titre($langs->trans("TicketParams"));
print '<table class="noborder" width="100%">';
// Activate email notifications
print '<tr class="pair"><td width="70%">' . $langs->trans("TicketsDisableEmail") . '</td>';
print '<td align="left">';
if ($conf->use_javascript_ajax) {
print ajax_constantonoff('TICKETS_DISABLE_ALL_MAILS');
} else {
$arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
print $form->selectarray("TICKETS_DISABLE_ALL_MAILS", $arrval, $conf->global->TICKETS_DISABLE_ALL_MAILS);
}
print '</td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketsDisableEmailHelp"), 1, 'help');
print '</td>';
print '</tr>';
// Activate log by email
print '<tr class="pair"><td width="70%">' . $langs->trans("TicketsLogEnableEmail") . '</td>';
print '<td align="left">';
if ($conf->use_javascript_ajax) {
print ajax_constantonoff('TICKETS_ACTIVATE_LOG_BY_EMAIL');
} else {
$arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
print $form->selectarray("TICKETS_ACTIVATE_LOG_BY_EMAIL", $arrval, $conf->global->TICKETS_ACTIVATE_LOG_BY_EMAIL);
}
print '</td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketsLogEnableEmailHelp"), 1, 'help');
print '</td>';
print '</tr>';
// Also send to main email address
if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
{
print '<tr class="pair"><td width="70%">' . $langs->trans("TicketsEmailAlsoSendToMainAddress") . '</td>';
print '<td align="left">';
if ($conf->use_javascript_ajax) {
print ajax_constantonoff('TICKETS_NOTIFICATION_ALSO_MAIN_ADDRESS');
} else {
$arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
print $form->selectarray("TICKETS_NOTIFICATION_ALSO_MAIN_ADDRESS", $arrval, $conf->global->TICKETS_NOTIFICATION_ALSO_MAIN_ADDRESS);
}
print '</td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketsEmailAlsoSendToMainAddressHelp"), 1, 'help');
print '</td>';
print '</tr>';
}
// Limiter la vue des tickets à ceux assignés à l'utilisateur
print '<tr class="pair"><td width="70%">' . $langs->trans("TicketsLimitViewAssignedOnly") . '</td>';
print '<td align="left">';
if ($conf->use_javascript_ajax) {
print ajax_constantonoff('TICKETS_LIMIT_VIEW_ASSIGNED_ONLY');
} else {
$arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
print $form->selectarray("TICKETS_LIMIT_VIEW_ASSIGNED_ONLY", $arrval, $conf->global->TICKETS_LIMIT_VIEW_ASSIGNED_ONLY);
}
print '</td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketsLimitViewAssignedOnlyHelp"), 1, 'help');
print '</td>';
print '</tr>';
if (!$conf->use_javascript_ajax) {
print '<tr class="impair"><td colspan="3" align="center"><input type="submit" class="button" value="' . $langs->trans("Save") . '"></td>';
print '</tr>';
}
// Auto assign ticket at user who created it
print '<tr class="pair"><td width="70%">' . $langs->trans("TicketsAutoAssignTicket") . '</td>';
print '<td align="left">';
if ($conf->use_javascript_ajax) {
print ajax_constantonoff('TICKETS_AUTO_ASSIGN_USER_CREATE');
} else {
$arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
print $form->selectarray("TICKETS_AUTO_ASSIGN_USER_CREATE", $arrval, $conf->global->TICKETS_AUTO_ASSIGN_USER_CREATE);
}
print '</td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketsAutoAssignTicketHelp"), 1, 'help');
print '</td>';
print '</tr>';
print '</table><br>';
if (!$conf->use_javascript_ajax) {
print '</form>';
}
// Admin var of module
print_titre($langs->trans("TicketParamMail"));
print '<table class="noborder" width="100%">';
print '<form method="post" action="' . $_SERVER['PHP_SELF'] . '" enctype="multipart/form-data" >';
print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
print '<input type="hidden" name="action" value="setvar">';
print '<tr class="liste_titre">';
print '<td colspan="3">' . $langs->trans("Email") . '</td>';
print "</tr>\n";
if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) {
print '<tr>';
print '<td colspan="3"><div class="info">' . $langs->trans("TicketSupCkEditorEmailNotActivated") . '</div></td>';
print "</tr>\n";
}
// Email d'envoi des notifications
print '<tr class="pair"><td>' . $langs->trans("TicketEmailNotificationFrom") . '</td>';
print '<td align="left">';
print '<input type="text" name="TICKETS_NOTIFICATION_EMAIL_FROM" value="' . $conf->global->TICKETS_NOTIFICATION_EMAIL_FROM . '" size="20" ></td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketEmailNotificationFromHelp"), 1, 'help');
print '</td>';
print '</tr>';
// Email de réception des notifications
print '<tr class="pair"><td>' . $langs->trans("TicketEmailNotificationTo") . '</td>';
print '<td align="left">';
print '<input type="text" name="TICKETS_NOTIFICATION_EMAIL_TO" value="' . (!empty($conf->global->TICKETS_NOTIFICATION_EMAIL_TO) ? $conf->global->TICKETS_NOTIFICATION_EMAIL_TO : $conf->global->TICKETS_NOTIFICATION_EMAIL_FROM) . '" size="20" ></td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketEmailNotificationToHelp"), 1, 'help');
print '</td>';
print '</tr>';
// Texte de création d'un ticket
$mail_mesg_new = $conf->global->TICKETS_MESSAGE_MAIL_NEW ? $conf->global->TICKETS_MESSAGE_MAIL_NEW : $langs->trans('TicketNewEmailBody');
print '<tr><td>' . $langs->trans("TicketNewEmailBodyLabel") . '</label>';
print '</td><td>';
require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
$doleditor = new DolEditor('TICKETS_MESSAGE_MAIL_NEW', $mail_mesg_new, '100%', 120, 'dolibarr_mailings', '', false, true, $conf->global->FCKEDITOR_ENABLE_MAIL, ROWS_2, 70);
$doleditor->Create();
print '</td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketNewEmailBodyHelp"), 1, 'help');
print '</td></tr>';
// Texte d'introduction
$mail_intro = $conf->global->TICKETS_MESSAGE_MAIL_INTRO ? $conf->global->TICKETS_MESSAGE_MAIL_INTRO : $langs->trans('TicketMessageMailIntroText');
print '<tr><td>' . $langs->trans("TicketMessageMailIntroLabelAdmin") . '</label>';
print '</td><td>';
require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
$doleditor = new DolEditor('TICKETS_MESSAGE_MAIL_INTRO', $mail_intro, '100%', 120, 'dolibarr_mailings', '', false, true, $conf->global->FCKEDITOR_ENABLE_MAIL, ROWS_2, 70);
$doleditor->Create();
print '</td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketMessageMailIntroHelpAdmin"), 1, 'help');
print '</td></tr>';
// Texte de signature
$mail_signature = $conf->global->TICKETS_MESSAGE_MAIL_SIGNATURE ? $conf->global->TICKETS_MESSAGE_MAIL_SIGNATURE : $langs->trans('TicketMessageMailSignatureText');
print '<tr><td>' . $langs->trans("TicketMessageMailSignatureLabelAdmin") . '</label>';
print '</td><td>';
require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
$doleditor = new DolEditor('TICKETS_MESSAGE_MAIL_SIGNATURE', $mail_signature, '100%', 120, 'dolibarr_mailings', '', false, true, $conf->global->FCKEDITOR_ENABLE_MAIL, ROWS_2, 70);
$doleditor->Create();
print '</td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketMessageMailSignatureHelpAdmin"), 1, 'help');
print '</td></tr>';
print '<tr class="liste_titre">';
print '<td colspan="3">' . $langs->trans("PublicInterface") . '</td>';
print "</tr>\n";
// Url public interface
$url_interface = $conf->global->TICKETS_URL_PUBLIC_INTERFACE;
print '<tr><td>' . $langs->trans("TicketUrlPublicInterfaceLabelAdmin") . '</label>';
print '</td><td>';
print '<input type="text" name="TICKETS_URL_PUBLIC_INTERFACE" value="' . $conf->global->TICKETS_URL_PUBLIC_INTERFACE . '" size="40" ></td>';
print '</td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketUrlPublicInterfaceHelpAdmin"), 1, 'help');
print '</td></tr>';
// Interface topic
$url_interface = $conf->global->TICKETS_PUBLIC_INTERFACE_TOPIC;
print '<tr><td>' . $langs->trans("TicketPublicInterfaceTopicLabelAdmin") . '</label>';
print '</td><td>';
print '<input type="text" name="TICKETS_PUBLIC_INTERFACE_TOPIC" value="' . $conf->global->TICKETS_PUBLIC_INTERFACE_TOPIC . '" size="40" ></td>';
print '</td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketPublicInterfaceTopicHelp"), 1, 'help');
print '</td></tr>';
// Texte d'accueil homepage
$public_text_home = $conf->global->TICKETS_PUBLIC_TEXT_HOME ? $conf->global->TICKETS_PUBLIC_TEXT_HOME : $langs->trans('TicketPublicInterfaceTextHome');
print '<tr><td>' . $langs->trans("TicketPublicInterfaceTextHomeLabelAdmin") . '</label>';
print '</td><td>';
require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
$doleditor = new DolEditor('TICKETS_PUBLIC_TEXT_HOME', $public_text_home, '100%', 180, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_2, 70);
$doleditor->Create();
print '</td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketPublicInterfaceTextHomeHelpAdmin"), 1, 'help');
print '</td></tr>';
// Texte d'aide à la saisie du message
$public_text_help_message = $conf->global->TICKETS_PUBLIC_TEXT_HELP_MESSAGE ? $conf->global->TICKETS_PUBLIC_TEXT_HELP_MESSAGE : $langs->trans('TicketPublicPleaseBeAccuratelyDescribe');
print '<tr><td>' . $langs->trans("TicketPublicInterfaceTextHelpMessageLabelAdmin") . '</label>';
print '</td><td>';
require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
$doleditor = new DolEditor('TICKETS_PUBLIC_TEXT_HELP_MESSAGE', $public_text_help_message, '100%', 180, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_2, 70);
$doleditor->Create();
print '</td>';
print '<td align="center">';
print $form->textwithpicto('', $langs->trans("TicketPublicInterfaceTextHelpMessageHelpAdmin"), 1, 'help');
print '</td></tr>';
print '<tr class="impair"><td colspan="3" align="center"><input type="submit" class="button" value="' . $langs->trans("Save") . '"></td>';
print '</tr>';
print '</table><br>';
print '</form>';
llxFooter();
$db->close();
| gpl-3.0 |
mhbu50/erpnext | erpnext/patches/v4_2/update_requested_and_ordered_qty.py | 754 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import frappe
def execute():
from erpnext.stock.stock_balance import get_indented_qty, get_ordered_qty, update_bin_qty
count=0
for item_code, warehouse in frappe.db.sql("""select distinct item_code, warehouse from
(select item_code, warehouse from tabBin
union
select item_code, warehouse from `tabStock Ledger Entry`) a"""):
try:
count += 1
update_bin_qty(item_code, warehouse, {
"indented_qty": get_indented_qty(item_code, warehouse),
"ordered_qty": get_ordered_qty(item_code, warehouse)
})
if count % 200 == 0:
frappe.db.commit()
except Exception:
frappe.db.rollback()
| gpl-3.0 |
masroore/db4o | Db4objects.Db4o.Tests/Db4objects.Db4o.Tests/Common/Handlers/ClassHandlerTestCase.cs | 2085 | /* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/. */
using Db4oUnit;
using Db4oUnit.Extensions;
namespace Db4objects.Db4o.Tests.Common.Handlers
{
public class ClassHandlerTestCase : AbstractDb4oTestCase
{
public static void Main(string[] args)
{
new ClassHandlerTestCase().RunSolo();
}
/// <exception cref="System.Exception"></exception>
public virtual void TestStoreObject()
{
var expectedItem = new Item("parent",
new Item("child", null));
Db().Store(expectedItem);
Db().Purge(expectedItem);
var q = Db().Query();
q.Constrain(typeof (Item));
q.Descend("_name").Constrain("parent");
var objectSet = q.Execute();
var readItem = (Item) objectSet.Next();
Assert.AreNotSame(expectedItem, readItem);
AssertAreEqual(expectedItem, readItem);
}
private void AssertAreEqual(Item expectedItem, Item
readItem)
{
Assert.AreEqual(expectedItem._name, readItem._name);
Assert.AreEqual(expectedItem._child._name, readItem._child._name);
}
public class Item
{
public Item _child;
public string _name;
public Item(string name, Item child)
{
_name = name;
_child = child;
}
}
}
} | gpl-3.0 |
jandy-team/jandy | jandy-server/src/main/java/io/jandy/util/api/json/TCommit.java | 632 | package io.jandy.util.api.json;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
/**
* @author JCooky
* @since 2016-12-19
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class TCommit {
@JsonProperty("message")
private String message;
@JsonProperty("committed_at")
private String committedAt;
@JsonProperty("committer_name")
private String committerName;
@JsonProperty("committer_email")
private String committerEmail;
@JsonProperty("sha")
private String sha;
@JsonProperty("id")
private Long id;
}
| gpl-3.0 |
jharding/philanthropist | lib/background/session_manager.js | 2753 | /*globals chrome, URI */
(function() {
// module declaration
var sessionManager = {};
// module dependencies
var logger = {};
var kAmazonUrl = 'http://www.amazon.com';
var kCookieName = 'session-id';
var kMaxTimeBetweenAssociatedVisits = 12 * 60 * 60 * 1000; // 12 hours
var currentSessionId = null;
var sessionMap = {};
// empties session map
sessionManager.clearSessionMap = function() {
sessionMap = {};
};
// returns the current session object
sessionManager.getCurrentSession = function() {
return sessionMap[currentSessionId];
};
// updates session's associated timestamp in session map
sessionManager.associateSession = function(sessionId, associateId) {
var now = (new Date()).getTime();
sessionMap[sessionId] = {
lastAssociatedVisit: now,
associateId: associateId
};
};
// gets passed callback cause of the async nature of the chrome API
// the arguments passed to the passed in callback are determined
// by the last associated visit within the current session
sessionManager.registerCurrentSession = function(callback) {
chrome.cookies.get({
url: kAmazonUrl,
name: kCookieName
},
function(cookie) {
if (cookie) {
currentSessionId = cookie.value;
var sessionId = currentSessionId;
var session = sessionMap[sessionId];
if (!session) {
session = sessionMap[sessionId] = {
lastAssociatedVisit: 0,
associateId: null
};
}
var now = (new Date()).getTime();
var isAssociated = (session.lastAssociatedVisit +
kMaxTimeBetweenAssociatedVisits) > now;
// call the callback, passing the session object for
// the current session
callback({
id: sessionId,
isAssociated: isAssociated,
lastAssociatedVisit: session.lastAssociatedVisit,
associateId: session.associateId
});
}
// no cookie means no session
else {
logger.warn('session-id cookie is not accessible');
callback(null);
}
});
};
sessionManager.init = function() {
logger = window.philanthropist.logger;
};
// exposing session manager module
window.philanthropist = window.philanthropist || {};
window.philanthropist.sessionManager = sessionManager;
})();
| gpl-3.0 |
bjakja/Kainote | Thirdparty/wxWidgets/src/common/datetimefmt.cpp | 75252 | ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/datetimefmt.cpp
// Purpose: wxDateTime formatting & parsing code
// Author: Vadim Zeitlin
// Modified by:
// Created: 11.05.99
// RCS-ID: $Id$
// Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
// parts of code taken from sndcal library by Scott E. Lee:
//
// Copyright 1993-1995, Scott E. Lee, all rights reserved.
// Permission granted to use, copy, modify, distribute and sell
// so long as the above copyright and this permission statement
// are retained in all copies.
//
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if !defined(wxUSE_DATETIME) || wxUSE_DATETIME
#ifndef WX_PRECOMP
#ifdef __WINDOWS__
#include "wx/msw/wrapwin.h"
#endif
#include "wx/string.h"
#include "wx/log.h"
#include "wx/intl.h"
#include "wx/stopwatch.h" // for wxGetLocalTimeMillis()
#include "wx/module.h"
#include "wx/crt.h"
#endif // WX_PRECOMP
#include "wx/thread.h"
#include <ctype.h>
#ifdef __WINDOWS__
#include <winnls.h>
#ifndef __WXWINCE__
#include <locale.h>
#endif
#endif
#include "wx/datetime.h"
#include "wx/time.h"
// ============================================================================
// implementation of wxDateTime
// ============================================================================
// ----------------------------------------------------------------------------
// helpers shared between datetime.cpp and datetimefmt.cpp
// ----------------------------------------------------------------------------
extern void InitTm(struct tm& tm);
extern wxString CallStrftime(const wxString& format, const tm* tm);
// ----------------------------------------------------------------------------
// constants (see also datetime.cpp)
// ----------------------------------------------------------------------------
static const int DAYS_PER_WEEK = 7;
static const int HOURS_PER_DAY = 24;
static const int SEC_PER_MIN = 60;
static const int MIN_PER_HOUR = 60;
// ----------------------------------------------------------------------------
// parsing helpers
// ----------------------------------------------------------------------------
namespace
{
// all the functions below taking non-const wxString::const_iterator p advance
// it until the end of the match
// scans all digits (but no more than len) and returns the resulting number
bool GetNumericToken(size_t len,
wxString::const_iterator& p,
const wxString::const_iterator& end,
unsigned long *number)
{
size_t n = 1;
wxString s;
while ( p != end && wxIsdigit(*p) )
{
s += *p++;
if ( len && ++n > len )
break;
}
return !s.empty() && s.ToULong(number);
}
// scans all alphabetic characters and returns the resulting string
wxString
GetAlphaToken(wxString::const_iterator& p,
const wxString::const_iterator& end)
{
wxString s;
while ( p != end && wxIsalpha(*p) )
{
s += *p++;
}
return s;
}
enum
{
DateLang_English = 1,
DateLang_Local = 2
};
// return the month if the string is a month name or Inv_Month otherwise
//
// flags can contain wxDateTime::Name_Abbr/Name_Full or both of them and lang
// can be either DateLang_Local (default) to interpret string as a localized
// month name or DateLang_English to parse it as a standard English name or
// their combination to interpret it in any way
wxDateTime::Month
GetMonthFromName(wxString::const_iterator& p,
const wxString::const_iterator& end,
int flags,
int lang)
{
const wxString::const_iterator pOrig = p;
const wxString name = GetAlphaToken(p, end);
if ( name.empty() )
return wxDateTime::Inv_Month;
wxDateTime::Month mon;
for ( mon = wxDateTime::Jan; mon < wxDateTime::Inv_Month; wxNextMonth(mon) )
{
// case-insensitive comparison either one of or with both abbreviated
// and not versions
if ( flags & wxDateTime::Name_Full )
{
if ( lang & DateLang_English )
{
if ( name.CmpNoCase(wxDateTime::GetEnglishMonthName(mon,
wxDateTime::Name_Full)) == 0 )
break;
}
if ( lang & DateLang_Local )
{
if ( name.CmpNoCase(wxDateTime::GetMonthName(mon,
wxDateTime::Name_Full)) == 0 )
break;
}
}
if ( flags & wxDateTime::Name_Abbr )
{
if ( lang & DateLang_English )
{
if ( name.CmpNoCase(wxDateTime::GetEnglishMonthName(mon,
wxDateTime::Name_Abbr)) == 0 )
break;
}
if ( lang & DateLang_Local )
{
// some locales (e.g. French one) use periods for the
// abbreviated month names but it's never part of name so
// compare it specially
wxString nameAbbr = wxDateTime::GetMonthName(mon,
wxDateTime::Name_Abbr);
const bool hasPeriod = *nameAbbr.rbegin() == '.';
if ( hasPeriod )
nameAbbr.erase(nameAbbr.end() - 1);
if ( name.CmpNoCase(nameAbbr) == 0 )
{
if ( hasPeriod )
{
// skip trailing period if it was part of the match
if ( *p == '.' )
++p;
else // no match as no matching period
continue;
}
break;
}
}
}
}
if ( mon == wxDateTime::Inv_Month )
p = pOrig;
return mon;
}
// return the weekday if the string is a weekday name or Inv_WeekDay otherwise
//
// flags and lang parameters have the same meaning as for GetMonthFromName()
// above
wxDateTime::WeekDay
GetWeekDayFromName(wxString::const_iterator& p,
const wxString::const_iterator& end,
int flags, int lang)
{
const wxString::const_iterator pOrig = p;
const wxString name = GetAlphaToken(p, end);
if ( name.empty() )
return wxDateTime::Inv_WeekDay;
wxDateTime::WeekDay wd;
for ( wd = wxDateTime::Sun; wd < wxDateTime::Inv_WeekDay; wxNextWDay(wd) )
{
if ( flags & wxDateTime::Name_Full )
{
if ( lang & DateLang_English )
{
if ( name.CmpNoCase(wxDateTime::GetEnglishWeekDayName(wd,
wxDateTime::Name_Full)) == 0 )
break;
}
if ( lang & DateLang_Local )
{
if ( name.CmpNoCase(wxDateTime::GetWeekDayName(wd,
wxDateTime::Name_Full)) == 0 )
break;
}
}
if ( flags & wxDateTime::Name_Abbr )
{
if ( lang & DateLang_English )
{
if ( name.CmpNoCase(wxDateTime::GetEnglishWeekDayName(wd,
wxDateTime::Name_Abbr)) == 0 )
break;
}
if ( lang & DateLang_Local )
{
if ( name.CmpNoCase(wxDateTime::GetWeekDayName(wd,
wxDateTime::Name_Abbr)) == 0 )
break;
}
}
}
if ( wd == wxDateTime::Inv_WeekDay )
p = pOrig;
return wd;
}
// parses string starting at given iterator using the specified format and,
// optionally, a fall back format (and optionally another one... but it stops
// there, really)
//
// if unsuccessful, returns invalid wxDateTime without changing p; otherwise
// advance p to the end of the match and returns wxDateTime containing the
// results of the parsing
wxDateTime
ParseFormatAt(wxString::const_iterator& p,
const wxString::const_iterator& end,
const wxString& fmt,
// FIXME-VC6: using wxString() instead of wxEmptyString in the
// line below results in error C2062: type 'class
// wxString (__cdecl *)(void)' unexpected
const wxString& fmtAlt = wxEmptyString)
{
const wxString str(p, end);
wxString::const_iterator endParse;
wxDateTime dt;
// Use a default date outside of the DST period to avoid problems with
// parsing the time differently depending on the today's date (which is used
// as the fall back date if none is explicitly specified).
static const wxDateTime dtDef(1, wxDateTime::Jan, 2012);
if ( dt.ParseFormat(str, fmt, dtDef, &endParse) ||
(!fmtAlt.empty() && dt.ParseFormat(str, fmtAlt, dtDef, &endParse)) )
{
p += endParse - str.begin();
}
//else: all formats failed
return dt;
}
} // anonymous namespace
// ----------------------------------------------------------------------------
// wxDateTime to/from text representations
// ----------------------------------------------------------------------------
wxString wxDateTime::Format(const wxString& formatp, const TimeZone& tz) const
{
wxCHECK_MSG( !formatp.empty(), wxEmptyString,
wxT("NULL format in wxDateTime::Format") );
wxString format = formatp;
#ifdef __WXOSX__
format.Replace("%c",wxLocale::GetInfo(wxLOCALE_DATE_TIME_FMT));
format.Replace("%x",wxLocale::GetInfo(wxLOCALE_SHORT_DATE_FMT));
format.Replace("%X",wxLocale::GetInfo(wxLOCALE_TIME_FMT));
#endif
// we have to use our own implementation if the date is out of range of
// strftime() or if we use non standard specifiers (notice that "%z" is
// special because it is de facto standard under Unix but is not supported
// under Windows)
#ifdef wxHAS_STRFTIME
time_t time = GetTicks();
if ( (time != (time_t)-1) && !wxStrstr(format, wxT("%l"))
#ifdef __WINDOWS__
&& !wxStrstr(format, wxT("%z"))
#endif
)
{
// use strftime()
struct tm tmstruct;
struct tm *tm;
if ( tz.GetOffset() == -wxGetTimeZone() )
{
// we are working with local time
tm = wxLocaltime_r(&time, &tmstruct);
// should never happen
wxCHECK_MSG( tm, wxEmptyString, wxT("wxLocaltime_r() failed") );
}
else
{
time += (int)tz.GetOffset();
#if defined(__VMS__) || defined(__WATCOMC__) // time is unsigned so avoid warning
int time2 = (int) time;
if ( time2 >= 0 )
#else
if ( time >= 0 )
#endif
{
tm = wxGmtime_r(&time, &tmstruct);
// should never happen
wxCHECK_MSG( tm, wxEmptyString, wxT("wxGmtime_r() failed") );
}
else
{
tm = (struct tm *)NULL;
}
}
if ( tm )
{
return CallStrftime(format, tm);
}
}
//else: use generic code below
#endif // wxHAS_STRFTIME
// we only parse ANSI C format specifications here, no POSIX 2
// complications, no GNU extensions but we do add support for a "%l" format
// specifier allowing to get the number of milliseconds
Tm tm = GetTm(tz);
// used for calls to strftime() when we only deal with time
struct tm tmTimeOnly;
memset(&tmTimeOnly, 0, sizeof(tmTimeOnly));
tmTimeOnly.tm_hour = tm.hour;
tmTimeOnly.tm_min = tm.min;
tmTimeOnly.tm_sec = tm.sec;
tmTimeOnly.tm_mday = 1; // any date will do, use 1976-01-01
tmTimeOnly.tm_mon = 0;
tmTimeOnly.tm_year = 76;
tmTimeOnly.tm_isdst = 0; // no DST, we adjust for tz ourselves
wxString tmp, res, fmt;
for ( wxString::const_iterator p = format.begin(); p != format.end(); ++p )
{
if ( *p != wxT('%') )
{
// copy as is
res += *p;
continue;
}
// set the default format
switch ( (*++p).GetValue() )
{
case wxT('Y'): // year has 4 digits
case wxT('z'): // time zone as well
fmt = wxT("%04d");
break;
case wxT('j'): // day of year has 3 digits
case wxT('l'): // milliseconds have 3 digits
fmt = wxT("%03d");
break;
case wxT('w'): // week day as number has only one
fmt = wxT("%d");
break;
default:
// it's either another valid format specifier in which case
// the format is "%02d" (for all the rest) or we have the
// field width preceding the format in which case it will
// override the default format anyhow
fmt = wxT("%02d");
}
bool restart = true;
while ( restart )
{
restart = false;
// start of the format specification
switch ( (*p).GetValue() )
{
case wxT('a'): // a weekday name
case wxT('A'):
// second parameter should be true for abbreviated names
res += GetWeekDayName(tm.GetWeekDay(),
*p == wxT('a') ? Name_Abbr : Name_Full);
break;
case wxT('b'): // a month name
case wxT('B'):
res += GetMonthName(tm.mon,
*p == wxT('b') ? Name_Abbr : Name_Full);
break;
case wxT('c'): // locale default date and time representation
case wxT('x'): // locale default date representation
#ifdef wxHAS_STRFTIME
//
// the problem: there is no way to know what do these format
// specifications correspond to for the current locale.
//
// the solution: use a hack and still use strftime(): first
// find the YEAR which is a year in the strftime() range (1970
// - 2038) whose Jan 1 falls on the same week day as the Jan 1
// of the real year. Then make a copy of the format and
// replace all occurrences of YEAR in it with some unique
// string not appearing anywhere else in it, then use
// strftime() to format the date in year YEAR and then replace
// YEAR back by the real year and the unique replacement
// string back with YEAR. Notice that "all occurrences of YEAR"
// means all occurrences of 4 digit as well as 2 digit form!
//
// the bugs: we assume that neither of %c nor %x contains any
// fields which may change between the YEAR and real year. For
// example, the week number (%U, %W) and the day number (%j)
// will change if one of these years is leap and the other one
// is not!
{
// find the YEAR: normally, for any year X, Jan 1 of the
// year X + 28 is the same weekday as Jan 1 of X (because
// the weekday advances by 1 for each normal X and by 2
// for each leap X, hence by 5 every 4 years or by 35
// which is 0 mod 7 every 28 years) but this rule breaks
// down if there are years between X and Y which are
// divisible by 4 but not leap (i.e. divisible by 100 but
// not 400), hence the correction.
int yearReal = GetYear(tz);
int mod28 = yearReal % 28;
// be careful to not go too far - we risk to leave the
// supported range
int year;
if ( mod28 < 10 )
{
year = 1988 + mod28; // 1988 == 0 (mod 28)
}
else
{
year = 1970 + mod28 - 10; // 1970 == 10 (mod 28)
}
int nCentury = year / 100,
nCenturyReal = yearReal / 100;
// need to adjust for the years divisble by 400 which are
// not leap but are counted like leap ones if we just take
// the number of centuries in between for nLostWeekDays
int nLostWeekDays = (nCentury - nCenturyReal) -
(nCentury / 4 - nCenturyReal / 4);
// we have to gain back the "lost" weekdays: note that the
// effect of this loop is to not do anything to
// nLostWeekDays (which we won't use any more), but to
// (indirectly) set the year correctly
while ( (nLostWeekDays % 7) != 0 )
{
nLostWeekDays += year++ % 4 ? 1 : 2;
}
// finally move the year below 2000 so that the 2-digit
// year number can never match the month or day of the
// month when we do the replacements below
if ( year >= 2000 )
year -= 28;
wxASSERT_MSG( year >= 1970 && year < 2000,
wxT("logic error in wxDateTime::Format") );
// use strftime() to format the same date but in supported
// year
//
// NB: we assume that strftime() doesn't check for the
// date validity and will happily format the date
// corresponding to Feb 29 of a non leap year (which
// may happen if yearReal was leap and year is not)
struct tm tmAdjusted;
InitTm(tmAdjusted);
tmAdjusted.tm_hour = tm.hour;
tmAdjusted.tm_min = tm.min;
tmAdjusted.tm_sec = tm.sec;
tmAdjusted.tm_wday = tm.GetWeekDay();
tmAdjusted.tm_yday = GetDayOfYear();
tmAdjusted.tm_mday = tm.mday;
tmAdjusted.tm_mon = tm.mon;
tmAdjusted.tm_year = year - 1900;
tmAdjusted.tm_isdst = 0; // no DST, already adjusted
wxString str = CallStrftime(*p == wxT('c') ? wxT("%c")
: wxT("%x"),
&tmAdjusted);
// now replace the replacement year with the real year:
// notice that we have to replace the 4 digit year with
// a unique string not appearing in strftime() output
// first to prevent the 2 digit year from matching any
// substring of the 4 digit year (but any day, month,
// hours or minutes components should be safe because
// they are never in 70-99 range)
wxString replacement("|");
while ( str.find(replacement) != wxString::npos )
replacement += '|';
str.Replace(wxString::Format("%d", year),
replacement);
str.Replace(wxString::Format("%d", year % 100),
wxString::Format("%d", yearReal % 100));
str.Replace(replacement,
wxString::Format("%d", yearReal));
res += str;
}
#else // !wxHAS_STRFTIME
// Use "%m/%d/%y %H:%M:%S" format instead
res += wxString::Format(wxT("%02d/%02d/%04d %02d:%02d:%02d"),
tm.mon+1,tm.mday, tm.year, tm.hour, tm.min, tm.sec);
#endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
break;
case wxT('d'): // day of a month (01-31)
res += wxString::Format(fmt, tm.mday);
break;
case wxT('H'): // hour in 24h format (00-23)
res += wxString::Format(fmt, tm.hour);
break;
case wxT('I'): // hour in 12h format (01-12)
{
// 24h -> 12h, 0h -> 12h too
int hour12 = tm.hour > 12 ? tm.hour - 12
: tm.hour ? tm.hour : 12;
res += wxString::Format(fmt, hour12);
}
break;
case wxT('j'): // day of the year
res += wxString::Format(fmt, GetDayOfYear(tz));
break;
case wxT('l'): // milliseconds (NOT STANDARD)
res += wxString::Format(fmt, GetMillisecond(tz));
break;
case wxT('m'): // month as a number (01-12)
res += wxString::Format(fmt, tm.mon + 1);
break;
case wxT('M'): // minute as a decimal number (00-59)
res += wxString::Format(fmt, tm.min);
break;
case wxT('p'): // AM or PM string
#ifdef wxHAS_STRFTIME
res += CallStrftime(wxT("%p"), &tmTimeOnly);
#else // !wxHAS_STRFTIME
res += (tmTimeOnly.tm_hour > 12) ? wxT("pm") : wxT("am");
#endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
break;
case wxT('S'): // second as a decimal number (00-61)
res += wxString::Format(fmt, tm.sec);
break;
case wxT('U'): // week number in the year (Sunday 1st week day)
res += wxString::Format(fmt, GetWeekOfYear(Sunday_First, tz));
break;
case wxT('W'): // week number in the year (Monday 1st week day)
res += wxString::Format(fmt, GetWeekOfYear(Monday_First, tz));
break;
case wxT('w'): // weekday as a number (0-6), Sunday = 0
res += wxString::Format(fmt, tm.GetWeekDay());
break;
// case wxT('x'): -- handled with "%c"
case wxT('X'): // locale default time representation
// just use strftime() to format the time for us
#ifdef wxHAS_STRFTIME
res += CallStrftime(wxT("%X"), &tmTimeOnly);
#else // !wxHAS_STRFTIME
res += wxString::Format(wxT("%02d:%02d:%02d"),tm.hour, tm.min, tm.sec);
#endif // wxHAS_STRFTIME/!wxHAS_STRFTIME
break;
case wxT('y'): // year without century (00-99)
res += wxString::Format(fmt, tm.year % 100);
break;
case wxT('Y'): // year with century
res += wxString::Format(fmt, tm.year);
break;
case wxT('z'): // time zone as [-+]HHMM
{
int ofs = tz.GetOffset();
if ( ofs < 0 )
{
res += '-';
ofs = -ofs;
}
else
{
res += '+';
}
// Converts seconds to HHMM representation.
res += wxString::Format(fmt,
100*(ofs/3600) + (ofs/60)%60);
}
break;
case wxT('Z'): // timezone name
#ifdef wxHAS_STRFTIME
res += CallStrftime(wxT("%Z"), &tmTimeOnly);
#endif
break;
default:
// is it the format width?
for ( fmt.clear();
*p == wxT('-') || *p == wxT('+') ||
*p == wxT(' ') || wxIsdigit(*p);
++p )
{
fmt += *p;
}
if ( !fmt.empty() )
{
// we've only got the flags and width so far in fmt
fmt.Prepend(wxT('%'));
fmt.Append(wxT('d'));
restart = true;
break;
}
// no, it wasn't the width
wxFAIL_MSG(wxT("unknown format specifier"));
// fall through and just copy it nevertheless
case wxT('%'): // a percent sign
res += *p;
break;
case 0: // the end of string
wxFAIL_MSG(wxT("missing format at the end of string"));
// just put the '%' which was the last char in format
res += wxT('%');
break;
}
}
}
return res;
}
// this function parses a string in (strict) RFC 822 format: see the section 5
// of the RFC for the detailed description, but briefly it's something of the
// form "Sat, 18 Dec 1999 00:48:30 +0100"
//
// this function is "strict" by design - it must reject anything except true
// RFC822 time specs.
bool
wxDateTime::ParseRfc822Date(const wxString& date, wxString::const_iterator *end)
{
const wxString::const_iterator pEnd = date.end();
wxString::const_iterator p = date.begin();
// 1. week day
const wxDateTime::WeekDay
wd = GetWeekDayFromName(p, pEnd, Name_Abbr, DateLang_English);
if ( wd == Inv_WeekDay )
return false;
//else: ignore week day for now, we could also check that it really
// corresponds to the specified date
// 2. separating comma
if ( *p++ != ',' || *p++ != ' ' )
return false;
// 3. day number
if ( !wxIsdigit(*p) )
return false;
wxDateTime_t day = (wxDateTime_t)(*p++ - '0');
if ( wxIsdigit(*p) )
{
day *= 10;
day = (wxDateTime_t)(day + (*p++ - '0'));
}
if ( *p++ != ' ' )
return false;
// 4. month name
const Month mon = GetMonthFromName(p, pEnd, Name_Abbr, DateLang_English);
if ( mon == Inv_Month )
return false;
if ( *p++ != ' ' )
return false;
// 5. year
if ( !wxIsdigit(*p) )
return false;
int year = *p++ - '0';
if ( !wxIsdigit(*p) ) // should have at least 2 digits in the year
return false;
year *= 10;
year += *p++ - '0';
// is it a 2 digit year (as per original RFC 822) or a 4 digit one?
if ( wxIsdigit(*p) )
{
year *= 10;
year += *p++ - '0';
if ( !wxIsdigit(*p) )
{
// no 3 digit years please
return false;
}
year *= 10;
year += *p++ - '0';
}
if ( *p++ != ' ' )
return false;
// 6. time in hh:mm:ss format with seconds being optional
if ( !wxIsdigit(*p) )
return false;
wxDateTime_t hour = (wxDateTime_t)(*p++ - '0');
if ( !wxIsdigit(*p) )
return false;
hour *= 10;
hour = (wxDateTime_t)(hour + (*p++ - '0'));
if ( *p++ != ':' )
return false;
if ( !wxIsdigit(*p) )
return false;
wxDateTime_t min = (wxDateTime_t)(*p++ - '0');
if ( !wxIsdigit(*p) )
return false;
min *= 10;
min += (wxDateTime_t)(*p++ - '0');
wxDateTime_t sec = 0;
if ( *p == ':' )
{
p++;
if ( !wxIsdigit(*p) )
return false;
sec = (wxDateTime_t)(*p++ - '0');
if ( !wxIsdigit(*p) )
return false;
sec *= 10;
sec += (wxDateTime_t)(*p++ - '0');
}
if ( *p++ != ' ' )
return false;
// 7. now the interesting part: the timezone
int offset = 0; // just to suppress warnings
if ( *p == '-' || *p == '+' )
{
// the explicit offset given: it has the form of hhmm
bool plus = *p++ == '+';
if ( !wxIsdigit(*p) || !wxIsdigit(*(p + 1)) )
return false;
// hours
offset = MIN_PER_HOUR*(10*(*p - '0') + (*(p + 1) - '0'));
p += 2;
if ( !wxIsdigit(*p) || !wxIsdigit(*(p + 1)) )
return false;
// minutes
offset += 10*(*p - '0') + (*(p + 1) - '0');
if ( !plus )
offset = -offset;
p += 2;
}
else // not numeric
{
// the symbolic timezone given: may be either military timezone or one
// of standard abbreviations
if ( !*(p + 1) )
{
// military: Z = UTC, J unused, A = -1, ..., Y = +12
static const int offsets[26] =
{
//A B C D E F G H I J K L M
-1, -2, -3, -4, -5, -6, -7, -8, -9, 0, -10, -11, -12,
//N O P R Q S T U V W Z Y Z
+1, +2, +3, +4, +5, +6, +7, +8, +9, +10, +11, +12, 0
};
if ( *p < wxT('A') || *p > wxT('Z') || *p == wxT('J') )
return false;
offset = offsets[*p++ - 'A'];
}
else
{
// abbreviation
const wxString tz(p, date.end());
if ( tz == wxT("UT") || tz == wxT("UTC") || tz == wxT("GMT") )
offset = 0;
else if ( tz == wxT("AST") )
offset = AST - GMT0;
else if ( tz == wxT("ADT") )
offset = ADT - GMT0;
else if ( tz == wxT("EST") )
offset = EST - GMT0;
else if ( tz == wxT("EDT") )
offset = EDT - GMT0;
else if ( tz == wxT("CST") )
offset = CST - GMT0;
else if ( tz == wxT("CDT") )
offset = CDT - GMT0;
else if ( tz == wxT("MST") )
offset = MST - GMT0;
else if ( tz == wxT("MDT") )
offset = MDT - GMT0;
else if ( tz == wxT("PST") )
offset = PST - GMT0;
else if ( tz == wxT("PDT") )
offset = PDT - GMT0;
else
return false;
p += tz.length();
}
// make it minutes
offset *= MIN_PER_HOUR;
}
// the spec was correct, construct the date from the values we found
Set(day, mon, year, hour, min, sec);
MakeFromTimezone(TimeZone::Make(offset*SEC_PER_MIN));
if ( end )
*end = p;
return true;
}
const char* wxDateTime::ParseRfc822Date(const char* date)
{
wxString::const_iterator end;
wxString dateStr(date);
if ( !ParseRfc822Date(dateStr, &end) )
return NULL;
return date + dateStr.IterOffsetInMBStr(end);
}
const wchar_t* wxDateTime::ParseRfc822Date(const wchar_t* date)
{
wxString::const_iterator end;
wxString dateStr(date);
if ( !ParseRfc822Date(dateStr, &end) )
return NULL;
return date + (end - dateStr.begin());
}
bool
wxDateTime::ParseFormat(const wxString& date,
const wxString& format,
const wxDateTime& dateDef,
wxString::const_iterator *endParse)
{
wxCHECK_MSG( !format.empty(), false, "format can't be empty" );
wxCHECK_MSG( endParse, false, "end iterator pointer must be specified" );
wxString str;
unsigned long num;
// what fields have we found?
bool haveWDay = false,
haveYDay = false,
haveDay = false,
haveMon = false,
haveYear = false,
haveHour = false,
haveMin = false,
haveSec = false,
haveMsec = false;
bool hourIsIn12hFormat = false, // or in 24h one?
isPM = false; // AM by default
bool haveTimeZone = false;
// and the value of the items we have (init them to get rid of warnings)
wxDateTime_t msec = 0,
sec = 0,
min = 0,
hour = 0;
WeekDay wday = Inv_WeekDay;
wxDateTime_t yday = 0,
mday = 0;
wxDateTime::Month mon = Inv_Month;
int year = 0;
long timeZone = 0; // time zone in seconds as expected in Tm structure
wxString::const_iterator input = date.begin();
const wxString::const_iterator end = date.end();
for ( wxString::const_iterator fmt = format.begin(); fmt != format.end(); ++fmt )
{
if ( *fmt != wxT('%') )
{
if ( wxIsspace(*fmt) )
{
// a white space in the format string matches 0 or more white
// spaces in the input
while ( input != end && wxIsspace(*input) )
{
input++;
}
}
else // !space
{
// any other character (not whitespace, not '%') must be
// matched by itself in the input
if ( input == end || *input++ != *fmt )
{
// no match
return false;
}
}
// done with this format char
continue;
}
// start of a format specification
// parse the optional width
size_t width = 0;
while ( wxIsdigit(*++fmt) )
{
width *= 10;
width += *fmt - '0';
}
// the default widths for the various fields
if ( !width )
{
switch ( (*fmt).GetValue() )
{
case wxT('Y'): // year has 4 digits
width = 4;
break;
case wxT('j'): // day of year has 3 digits
case wxT('l'): // milliseconds have 3 digits
width = 3;
break;
case wxT('w'): // week day as number has only one
width = 1;
break;
default:
// default for all other fields
width = 2;
}
}
// then the format itself
switch ( (*fmt).GetValue() )
{
case wxT('a'): // a weekday name
case wxT('A'):
{
wday = GetWeekDayFromName
(
input, end,
*fmt == 'a' ? Name_Abbr : Name_Full,
DateLang_Local
);
if ( wday == Inv_WeekDay )
{
// no match
return false;
}
}
haveWDay = true;
break;
case wxT('b'): // a month name
case wxT('B'):
{
mon = GetMonthFromName
(
input, end,
*fmt == 'b' ? Name_Abbr : Name_Full,
DateLang_Local
);
if ( mon == Inv_Month )
{
// no match
return false;
}
}
haveMon = true;
break;
case wxT('c'): // locale default date and time representation
{
wxDateTime dt;
#if wxUSE_INTL
const wxString
fmtDateTime = wxLocale::GetInfo(wxLOCALE_DATE_TIME_FMT);
if ( !fmtDateTime.empty() )
dt = ParseFormatAt(input, end, fmtDateTime);
#endif // wxUSE_INTL
if ( !dt.IsValid() )
{
// also try the format which corresponds to ctime()
// output (i.e. the "C" locale default)
dt = ParseFormatAt(input, end, wxS("%a %b %d %H:%M:%S %Y"));
}
if ( !dt.IsValid() )
{
// and finally also the two generic date/time formats
dt = ParseFormatAt(input, end, wxS("%x %X"), wxS("%X %x"));
}
if ( !dt.IsValid() )
return false;
const Tm tm = dt.GetTm();
hour = tm.hour;
min = tm.min;
sec = tm.sec;
year = tm.year;
mon = tm.mon;
mday = tm.mday;
haveDay = haveMon = haveYear =
haveHour = haveMin = haveSec = true;
}
break;
case wxT('d'): // day of a month (01-31)
case 'e': // day of a month (1-31) (GNU extension)
if ( !GetNumericToken(width, input, end, &num) ||
(num > 31) || (num < 1) )
{
// no match
return false;
}
// we can't check whether the day range is correct yet, will
// do it later - assume ok for now
haveDay = true;
mday = (wxDateTime_t)num;
break;
case wxT('H'): // hour in 24h format (00-23)
if ( !GetNumericToken(width, input, end, &num) || (num > 23) )
{
// no match
return false;
}
haveHour = true;
hour = (wxDateTime_t)num;
break;
case wxT('I'): // hour in 12h format (01-12)
if ( !GetNumericToken(width, input, end, &num) ||
!num || (num > 12) )
{
// no match
return false;
}
haveHour = true;
hourIsIn12hFormat = true;
hour = (wxDateTime_t)(num % 12); // 12 should be 0
break;
case wxT('j'): // day of the year
if ( !GetNumericToken(width, input, end, &num) ||
!num || (num > 366) )
{
// no match
return false;
}
haveYDay = true;
yday = (wxDateTime_t)num;
break;
case wxT('l'): // milliseconds (0-999)
if ( !GetNumericToken(width, input, end, &num) )
return false;
haveMsec = true;
msec = (wxDateTime_t)num;
break;
case wxT('m'): // month as a number (01-12)
if ( !GetNumericToken(width, input, end, &num) ||
!num || (num > 12) )
{
// no match
return false;
}
haveMon = true;
mon = (Month)(num - 1);
break;
case wxT('M'): // minute as a decimal number (00-59)
if ( !GetNumericToken(width, input, end, &num) ||
(num > 59) )
{
// no match
return false;
}
haveMin = true;
min = (wxDateTime_t)num;
break;
case wxT('p'): // AM or PM string
{
wxString am, pm;
GetAmPmStrings(&am, &pm);
// we can never match %p in locales which don't use AM/PM
if ( am.empty() || pm.empty() )
return false;
const size_t pos = input - date.begin();
if ( date.compare(pos, pm.length(), pm) == 0 )
{
isPM = true;
input += pm.length();
}
else if ( date.compare(pos, am.length(), am) == 0 )
{
input += am.length();
}
else // no match
{
return false;
}
}
break;
case wxT('r'): // time as %I:%M:%S %p
{
wxDateTime dt;
if ( !dt.ParseFormat(wxString(input, end),
wxS("%I:%M:%S %p"), &input) )
return false;
haveHour = haveMin = haveSec = true;
const Tm tm = dt.GetTm();
hour = tm.hour;
min = tm.min;
sec = tm.sec;
}
break;
case wxT('R'): // time as %H:%M
{
const wxDateTime
dt = ParseFormatAt(input, end, wxS("%H:%M"));
if ( !dt.IsValid() )
return false;
haveHour =
haveMin = true;
const Tm tm = dt.GetTm();
hour = tm.hour;
min = tm.min;
}
break;
case wxT('S'): // second as a decimal number (00-61)
if ( !GetNumericToken(width, input, end, &num) ||
(num > 61) )
{
// no match
return false;
}
haveSec = true;
sec = (wxDateTime_t)num;
break;
case wxT('T'): // time as %H:%M:%S
{
const wxDateTime
dt = ParseFormatAt(input, end, wxS("%H:%M:%S"));
if ( !dt.IsValid() )
return false;
haveHour =
haveMin =
haveSec = true;
const Tm tm = dt.GetTm();
hour = tm.hour;
min = tm.min;
sec = tm.sec;
}
break;
case wxT('w'): // weekday as a number (0-6), Sunday = 0
if ( !GetNumericToken(width, input, end, &num) ||
(wday > 6) )
{
// no match
return false;
}
haveWDay = true;
wday = (WeekDay)num;
break;
case wxT('x'): // locale default date representation
{
#if wxUSE_INTL
wxString
fmtDate = wxLocale::GetInfo(wxLOCALE_SHORT_DATE_FMT),
fmtDateAlt = wxLocale::GetInfo(wxLOCALE_LONG_DATE_FMT);
#else // !wxUSE_INTL
wxString fmtDate, fmtDateAlt;
#endif // wxUSE_INTL/!wxUSE_INTL
if ( fmtDate.empty() )
{
if ( IsWestEuropeanCountry(GetCountry()) ||
GetCountry() == Russia )
{
fmtDate = wxS("%d/%m/%Y");
fmtDateAlt = wxS("%m/%d/%Y");
}
else // assume USA
{
fmtDate = wxS("%m/%d/%Y");
fmtDateAlt = wxS("%d/%m/%Y");
}
}
wxDateTime
dt = ParseFormatAt(input, end, fmtDate, fmtDateAlt);
if ( !dt.IsValid() )
{
// try with short years too
fmtDate.Replace("%Y","%y");
fmtDateAlt.Replace("%Y","%y");
dt = ParseFormatAt(input, end, fmtDate, fmtDateAlt);
if ( !dt.IsValid() )
return false;
}
const Tm tm = dt.GetTm();
haveDay =
haveMon =
haveYear = true;
year = tm.year;
mon = tm.mon;
mday = tm.mday;
}
break;
case wxT('X'): // locale default time representation
{
#if wxUSE_INTL
wxString fmtTime = wxLocale::GetInfo(wxLOCALE_TIME_FMT),
fmtTimeAlt;
#else // !wxUSE_INTL
wxString fmtTime, fmtTimeAlt;
#endif // wxUSE_INTL/!wxUSE_INTL
if ( fmtTime.empty() )
{
// try to parse what follows as "%H:%M:%S" and, if this
// fails, as "%I:%M:%S %p" - this should catch the most
// common cases
fmtTime = "%T";
fmtTimeAlt = "%r";
}
const wxDateTime
dt = ParseFormatAt(input, end, fmtTime, fmtTimeAlt);
if ( !dt.IsValid() )
return false;
haveHour =
haveMin =
haveSec = true;
const Tm tm = dt.GetTm();
hour = tm.hour;
min = tm.min;
sec = tm.sec;
}
break;
case wxT('y'): // year without century (00-99)
if ( !GetNumericToken(width, input, end, &num) ||
(num > 99) )
{
// no match
return false;
}
haveYear = true;
// TODO should have an option for roll over date instead of
// hard coding it here
year = (num > 30 ? 1900 : 2000) + (wxDateTime_t)num;
break;
case wxT('Y'): // year with century
if ( !GetNumericToken(width, input, end, &num) )
{
// no match
return false;
}
haveYear = true;
year = (wxDateTime_t)num;
break;
case wxT('z'):
{
// check that we have something here at all
if ( input == end )
return false;
// and then check that it's either plus or minus sign
bool minusFound;
if ( *input == wxT('-') )
minusFound = true;
else if ( *input == wxT('+') )
minusFound = false;
else
return false; // no match
// here should follow 4 digits HHMM
++input;
unsigned long tzHourMin;
if ( !GetNumericToken(4, input, end, &tzHourMin) )
return false; // no match
const unsigned hours = tzHourMin / 100;
const unsigned minutes = tzHourMin % 100;
if ( hours > 12 || minutes > 59 )
return false; // bad format
timeZone = 3600*hours + 60*minutes;
if ( minusFound )
timeZone = -timeZone;
haveTimeZone = true;
}
break;
case wxT('Z'): // timezone name
// FIXME: currently we just ignore everything that looks like a
// time zone here
GetAlphaToken(input, end);
break;
case wxT('%'): // a percent sign
if ( input == end || *input++ != wxT('%') )
{
// no match
return false;
}
break;
case 0: // the end of string
wxFAIL_MSG(wxT("unexpected format end"));
// fall through
default: // not a known format spec
return false;
}
}
// format matched, try to construct a date from what we have now
Tm tmDef;
if ( dateDef.IsValid() )
{
// take this date as default
tmDef = dateDef.GetTm();
}
else if ( IsValid() )
{
// if this date is valid, don't change it
tmDef = GetTm();
}
else
{
// no default and this date is invalid - fall back to Today()
tmDef = Today().GetTm();
}
Tm tm = tmDef;
// set the date
if ( haveMon )
{
tm.mon = mon;
}
if ( haveYear )
{
tm.year = year;
}
// TODO we don't check here that the values are consistent, if both year
// day and month/day were found, we just ignore the year day and we
// also always ignore the week day
if ( haveDay )
{
if ( mday > GetNumberOfDays(tm.mon, tm.year) )
return false;
tm.mday = mday;
}
else if ( haveYDay )
{
if ( yday > GetNumberOfDays(tm.year) )
return false;
Tm tm2 = wxDateTime(1, Jan, tm.year).SetToYearDay(yday).GetTm();
tm.mon = tm2.mon;
tm.mday = tm2.mday;
}
// deal with AM/PM
if ( haveHour && hourIsIn12hFormat && isPM )
{
// translate to 24hour format
hour += 12;
}
//else: either already in 24h format or no translation needed
// set the time
if ( haveHour )
{
tm.hour = hour;
}
if ( haveMin )
{
tm.min = min;
}
if ( haveSec )
{
tm.sec = sec;
}
if ( haveMsec )
tm.msec = msec;
Set(tm);
// If a time zone was specified and it is not the local time zone, we need
// to shift the time accordingly.
//
// Note that avoiding the call to MakeFromTimeZone is necessary to avoid
// DST problems.
if ( haveTimeZone && timeZone != -wxGetTimeZone() )
MakeFromTimezone(timeZone);
// finally check that the week day is consistent -- if we had it
if ( haveWDay && GetWeekDay() != wday )
return false;
*endParse = input;
return true;
}
const char*
wxDateTime::ParseFormat(const char* date,
const wxString& format,
const wxDateTime& dateDef)
{
wxString::const_iterator end;
wxString dateStr(date);
if ( !ParseFormat(dateStr, format, dateDef, &end) )
return NULL;
return date + dateStr.IterOffsetInMBStr(end);
}
const wchar_t*
wxDateTime::ParseFormat(const wchar_t* date,
const wxString& format,
const wxDateTime& dateDef)
{
wxString::const_iterator end;
wxString dateStr(date);
if ( !ParseFormat(dateStr, format, dateDef, &end) )
return NULL;
return date + (end - dateStr.begin());
}
bool
wxDateTime::ParseDateTime(const wxString& date, wxString::const_iterator *end)
{
wxCHECK_MSG( end, false, "end iterator pointer must be specified" );
wxDateTime
dtDate,
dtTime;
wxString::const_iterator
endTime,
endDate,
endBoth;
// If we got a date in the beginning, see if there is a time specified
// after the date
if ( dtDate.ParseDate(date, &endDate) )
{
// Skip spaces, as the ParseTime() function fails on spaces
while ( endDate != date.end() && wxIsspace(*endDate) )
++endDate;
const wxString timestr(endDate, date.end());
if ( !dtTime.ParseTime(timestr, &endTime) )
return false;
endBoth = endDate + (endTime - timestr.begin());
}
else // no date in the beginning
{
// check if we have a time followed by a date
if ( !dtTime.ParseTime(date, &endTime) )
return false;
while ( endTime != date.end() && wxIsspace(*endTime) )
++endTime;
const wxString datestr(endTime, date.end());
if ( !dtDate.ParseDate(datestr, &endDate) )
return false;
endBoth = endTime + (endDate - datestr.begin());
}
Set(dtDate.GetDay(), dtDate.GetMonth(), dtDate.GetYear(),
dtTime.GetHour(), dtTime.GetMinute(), dtTime.GetSecond(),
dtTime.GetMillisecond());
*end = endBoth;
return true;
}
const char* wxDateTime::ParseDateTime(const char* date)
{
wxString::const_iterator end;
wxString dateStr(date);
if ( !ParseDateTime(dateStr, &end) )
return NULL;
return date + dateStr.IterOffsetInMBStr(end);
}
const wchar_t* wxDateTime::ParseDateTime(const wchar_t* date)
{
wxString::const_iterator end;
wxString dateStr(date);
if ( !ParseDateTime(dateStr, &end) )
return NULL;
return date + (end - dateStr.begin());
}
bool
wxDateTime::ParseDate(const wxString& date, wxString::const_iterator *end)
{
wxCHECK_MSG( end, false, "end iterator pointer must be specified" );
// this is a simplified version of ParseDateTime() which understands only
// "today" (for wxDate compatibility) and digits only otherwise (and not
// all esoteric constructions ParseDateTime() knows about)
const wxString::const_iterator pBegin = date.begin();
const wxString::const_iterator pEnd = date.end();
wxString::const_iterator p = pBegin;
while ( p != pEnd && wxIsspace(*p) )
p++;
// some special cases
static struct
{
const char *str;
int dayDiffFromToday;
} literalDates[] =
{
{ wxTRANSLATE("today"), 0 },
{ wxTRANSLATE("yesterday"), -1 },
{ wxTRANSLATE("tomorrow"), 1 },
};
const size_t lenRest = pEnd - p;
for ( size_t n = 0; n < WXSIZEOF(literalDates); n++ )
{
const wxString dateStr = wxGetTranslation(literalDates[n].str);
size_t len = dateStr.length();
if ( len > lenRest )
continue;
const wxString::const_iterator pEnd = p + len;
if ( wxString(p, pEnd).CmpNoCase(dateStr) == 0 )
{
// nothing can follow this, so stop here
p = pEnd;
int dayDiffFromToday = literalDates[n].dayDiffFromToday;
*this = Today();
if ( dayDiffFromToday )
{
*this += wxDateSpan::Days(dayDiffFromToday);
}
*end = pEnd;
return true;
}
}
// We try to guess what we have here: for each new (numeric) token, we
// determine if it can be a month, day or a year. Of course, there is an
// ambiguity as some numbers may be days as well as months, so we also
// have the ability to back track.
// what do we have?
bool haveDay = false, // the months day?
haveWDay = false, // the day of week?
haveMon = false, // the month?
haveYear = false; // the year?
bool monWasNumeric = false; // was month specified as a number?
// and the value of the items we have (init them to get rid of warnings)
WeekDay wday = Inv_WeekDay;
wxDateTime_t day = 0;
wxDateTime::Month mon = Inv_Month;
int year = 0;
// tokenize the string
while ( p != pEnd )
{
// skip white space and date delimiters
if ( wxStrchr(".,/-\t\r\n ", *p) )
{
++p;
continue;
}
// modify copy of the iterator as we're not sure if the next token is
// still part of the date at all
wxString::const_iterator pCopy = p;
// we can have either alphabetic or numeric token, start by testing if
// it's the latter
unsigned long val;
if ( GetNumericToken(10 /* max length */, pCopy, pEnd, &val) )
{
// guess what this number is
bool isDay = false,
isMonth = false,
isYear = false;
if ( !haveMon && val > 0 && val <= 12 )
{
// assume it is month
isMonth = true;
}
else // not the month
{
if ( haveDay )
{
// this can only be the year
isYear = true;
}
else // may be either day or year
{
// use a leap year if we don't have the year yet to allow
// dates like 2/29/1976 which would be rejected otherwise
wxDateTime_t max_days = (wxDateTime_t)(
haveMon
? GetNumberOfDays(mon, haveYear ? year : 1976)
: 31
);
// can it be day?
if ( (val == 0) || (val > (unsigned long)max_days) )
{
// no
isYear = true;
}
else // yes, suppose it's the day
{
isDay = true;
}
}
}
if ( isYear )
{
if ( haveYear )
break;
haveYear = true;
year = (wxDateTime_t)val;
}
else if ( isDay )
{
if ( haveDay )
break;
haveDay = true;
day = (wxDateTime_t)val;
}
else if ( isMonth )
{
haveMon = true;
monWasNumeric = true;
mon = (Month)(val - 1);
}
}
else // not a number
{
// be careful not to overwrite the current mon value
Month mon2 = GetMonthFromName
(
pCopy, pEnd,
Name_Full | Name_Abbr,
DateLang_Local | DateLang_English
);
if ( mon2 != Inv_Month )
{
// it's a month
if ( haveMon )
{
// but we already have a month - maybe we guessed wrong
// when we had interpreted that numeric value as a month
// and it was the day number instead?
if ( haveDay || !monWasNumeric )
break;
// assume we did and change our mind: reinterpret the month
// value as a day (notice that there is no need to check
// that it is valid as month values are always < 12, but
// the days are counted from 1 unlike the months)
day = (wxDateTime_t)(mon + 1);
haveDay = true;
}
mon = mon2;
haveMon = true;
}
else // not a valid month name
{
WeekDay wday2 = GetWeekDayFromName
(
pCopy, pEnd,
Name_Full | Name_Abbr,
DateLang_Local | DateLang_English
);
if ( wday2 != Inv_WeekDay )
{
// a week day
if ( haveWDay )
break;
wday = wday2;
haveWDay = true;
}
else // not a valid weekday name
{
// try the ordinals
static const char *const ordinals[] =
{
wxTRANSLATE("first"),
wxTRANSLATE("second"),
wxTRANSLATE("third"),
wxTRANSLATE("fourth"),
wxTRANSLATE("fifth"),
wxTRANSLATE("sixth"),
wxTRANSLATE("seventh"),
wxTRANSLATE("eighth"),
wxTRANSLATE("ninth"),
wxTRANSLATE("tenth"),
wxTRANSLATE("eleventh"),
wxTRANSLATE("twelfth"),
wxTRANSLATE("thirteenth"),
wxTRANSLATE("fourteenth"),
wxTRANSLATE("fifteenth"),
wxTRANSLATE("sixteenth"),
wxTRANSLATE("seventeenth"),
wxTRANSLATE("eighteenth"),
wxTRANSLATE("nineteenth"),
wxTRANSLATE("twentieth"),
// that's enough - otherwise we'd have problems with
// composite (or not) ordinals
};
size_t n;
for ( n = 0; n < WXSIZEOF(ordinals); n++ )
{
const wxString ord = wxGetTranslation(ordinals[n]);
const size_t len = ord.length();
if ( date.compare(p - pBegin, len, ord) == 0 )
{
p += len;
break;
}
}
if ( n == WXSIZEOF(ordinals) )
{
// stop here - something unknown
break;
}
// it's a day
if ( haveDay )
{
// don't try anything here (as in case of numeric day
// above) - the symbolic day spec should always
// precede the month/year
break;
}
haveDay = true;
day = (wxDateTime_t)(n + 1);
}
}
}
// advance iterator past a successfully parsed token
p = pCopy;
}
// either no more tokens or the scan was stopped by something we couldn't
// parse - in any case, see if we can construct a date from what we have
if ( !haveDay && !haveWDay )
return false;
if ( haveWDay && (haveMon || haveYear || haveDay) &&
!(haveDay && haveMon && haveYear) )
{
// without adjectives (which we don't support here) the week day only
// makes sense completely separately or with the full date
// specification (what would "Wed 1999" mean?)
return false;
}
if ( !haveWDay && haveYear && !(haveDay && haveMon) )
{
// may be we have month and day instead of day and year?
if ( haveDay && !haveMon )
{
if ( day <= 12 )
{
// exchange day and month
mon = (wxDateTime::Month)(day - 1);
// we're in the current year then
if ( (year > 0) && (year <= (int)GetNumberOfDays(mon, Inv_Year)) )
{
day = (wxDateTime_t)year;
haveMon = true;
haveYear = false;
}
//else: no, can't exchange, leave haveMon == false
}
}
if ( !haveMon )
return false;
}
if ( !haveMon )
{
mon = GetCurrentMonth();
}
if ( !haveYear )
{
year = GetCurrentYear();
}
if ( haveDay )
{
// normally we check the day above but the check is optimistic in case
// we find the day before its month/year so we have to redo it now
if ( day > GetNumberOfDays(mon, year) )
return false;
Set(day, mon, year);
if ( haveWDay )
{
// check that it is really the same
if ( GetWeekDay() != wday )
return false;
}
}
else // haveWDay
{
*this = Today();
SetToWeekDayInSameWeek(wday);
}
*end = p;
return true;
}
const char* wxDateTime::ParseDate(const char* date)
{
wxString::const_iterator end;
wxString dateStr(date);
if ( !ParseDate(dateStr, &end) )
return NULL;
return date + dateStr.IterOffsetInMBStr(end);
}
const wchar_t* wxDateTime::ParseDate(const wchar_t* date)
{
wxString::const_iterator end;
wxString dateStr(date);
if ( !ParseDate(dateStr, &end) )
return NULL;
return date + (end - dateStr.begin());
}
bool
wxDateTime::ParseTime(const wxString& time, wxString::const_iterator *end)
{
wxCHECK_MSG( end, false, "end iterator pointer must be specified" );
// first try some extra things
static const struct
{
const char *name;
wxDateTime_t hour;
} stdTimes[] =
{
{ wxTRANSLATE("noon"), 12 },
{ wxTRANSLATE("midnight"), 00 },
// anything else?
};
for ( size_t n = 0; n < WXSIZEOF(stdTimes); n++ )
{
const wxString timeString = wxGetTranslation(stdTimes[n].name);
if ( timeString.CmpNoCase(wxString(time, timeString.length())) == 0 )
{
// casts required by DigitalMars
Set(stdTimes[n].hour, wxDateTime_t(0), wxDateTime_t(0));
if ( end )
*end = time.begin() + timeString.length();
return true;
}
}
// try all time formats we may think about in the order from longest to
// shortest
static const char *const timeFormats[] =
{
"%I:%M:%S %p", // 12hour with AM/PM
"%H:%M:%S", // could be the same or 24 hour one so try it too
"%I:%M %p", // 12hour with AM/PM but without seconds
"%H:%M", // and a possibly 24 hour version without seconds
"%X", // possibly something from above or maybe something
// completely different -- try it last
// TODO: parse timezones
};
for ( size_t nFmt = 0; nFmt < WXSIZEOF(timeFormats); nFmt++ )
{
if ( ParseFormat(time, timeFormats[nFmt], end) )
return true;
}
return false;
}
const char* wxDateTime::ParseTime(const char* date)
{
wxString::const_iterator end;
wxString dateStr(date);
if ( !ParseTime(dateStr, &end) )
return NULL;
return date + dateStr.IterOffsetInMBStr(end);
}
const wchar_t* wxDateTime::ParseTime(const wchar_t* date)
{
wxString::const_iterator end;
wxString dateStr(date);
if ( !ParseTime(dateStr, &end) )
return NULL;
return date + (end - dateStr.begin());
}
// ----------------------------------------------------------------------------
// Workdays and holidays support
// ----------------------------------------------------------------------------
bool wxDateTime::IsWorkDay(Country WXUNUSED(country)) const
{
return !wxDateTimeHolidayAuthority::IsHoliday(*this);
}
// ============================================================================
// wxDateSpan
// ============================================================================
wxDateSpan WXDLLIMPEXP_BASE operator*(int n, const wxDateSpan& ds)
{
wxDateSpan ds1(ds);
return ds1.Multiply(n);
}
// ============================================================================
// wxTimeSpan
// ============================================================================
wxTimeSpan WXDLLIMPEXP_BASE operator*(int n, const wxTimeSpan& ts)
{
return wxTimeSpan(ts).Multiply(n);
}
// this enum is only used in wxTimeSpan::Format() below but we can't declare
// it locally to the method as it provokes an internal compiler error in egcs
// 2.91.60 when building with -O2
enum TimeSpanPart
{
Part_Week,
Part_Day,
Part_Hour,
Part_Min,
Part_Sec,
Part_MSec
};
// not all strftime(3) format specifiers make sense here because, for example,
// a time span doesn't have a year nor a timezone
//
// Here are the ones which are supported (all of them are supported by strftime
// as well):
// %H hour in 24 hour format
// %M minute (00 - 59)
// %S second (00 - 59)
// %% percent sign
//
// Also, for MFC CTimeSpan compatibility, we support
// %D number of days
//
// And, to be better than MFC :-), we also have
// %E number of wEeks
// %l milliseconds (000 - 999)
wxString wxTimeSpan::Format(const wxString& format) const
{
// we deal with only positive time spans here and just add the sign in
// front for the negative ones
if ( IsNegative() )
{
wxString str(Negate().Format(format));
return "-" + str;
}
wxCHECK_MSG( !format.empty(), wxEmptyString,
wxT("NULL format in wxTimeSpan::Format") );
wxString str;
str.Alloc(format.length());
// Suppose we have wxTimeSpan ts(1 /* hour */, 2 /* min */, 3 /* sec */)
//
// Then, of course, ts.Format("%H:%M:%S") must return "01:02:03", but the
// question is what should ts.Format("%S") do? The code here returns "3273"
// in this case (i.e. the total number of seconds, not just seconds % 60)
// because, for me, this call means "give me entire time interval in
// seconds" and not "give me the seconds part of the time interval"
//
// If we agree that it should behave like this, it is clear that the
// interpretation of each format specifier depends on the presence of the
// other format specs in the string: if there was "%H" before "%M", we
// should use GetMinutes() % 60, otherwise just GetMinutes() &c
// we remember the most important unit found so far
TimeSpanPart partBiggest = Part_MSec;
for ( wxString::const_iterator pch = format.begin(); pch != format.end(); ++pch )
{
wxChar ch = *pch;
if ( ch == wxT('%') )
{
// the start of the format specification of the printf() below
wxString fmtPrefix(wxT('%'));
// the number
long n;
// the number of digits for the format string, 0 if unused
unsigned digits = 0;
ch = *++pch; // get the format spec char
switch ( ch )
{
default:
wxFAIL_MSG( wxT("invalid format character") );
// fall through
case wxT('%'):
str += ch;
// skip the part below switch
continue;
case wxT('D'):
n = GetDays();
if ( partBiggest < Part_Day )
{
n %= DAYS_PER_WEEK;
}
else
{
partBiggest = Part_Day;
}
break;
case wxT('E'):
partBiggest = Part_Week;
n = GetWeeks();
break;
case wxT('H'):
n = GetHours();
if ( partBiggest < Part_Hour )
{
n %= HOURS_PER_DAY;
}
else
{
partBiggest = Part_Hour;
}
digits = 2;
break;
case wxT('l'):
n = GetMilliseconds().ToLong();
if ( partBiggest < Part_MSec )
{
n %= 1000;
}
//else: no need to reset partBiggest to Part_MSec, it is
// the least significant one anyhow
digits = 3;
break;
case wxT('M'):
n = GetMinutes();
if ( partBiggest < Part_Min )
{
n %= MIN_PER_HOUR;
}
else
{
partBiggest = Part_Min;
}
digits = 2;
break;
case wxT('S'):
n = GetSeconds().ToLong();
if ( partBiggest < Part_Sec )
{
n %= SEC_PER_MIN;
}
else
{
partBiggest = Part_Sec;
}
digits = 2;
break;
}
if ( digits )
{
fmtPrefix << wxT("0") << digits;
}
str += wxString::Format(fmtPrefix + wxT("ld"), n);
}
else
{
// normal character, just copy
str += ch;
}
}
return str;
}
#endif // wxUSE_DATETIME
| gpl-3.0 |
PFgimenez/PhD | src/preferences/heuristiques/simple/HeuristiqueEntropieNormalisee.java | 1553 | package preferences.heuristiques.simple;
import java.util.Map;
/* (C) Copyright 2016, Gimenez Pierre-François
*
* 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/>.
*/
/**
* Heuristique = entropie normalisée
* @author Pierre-François Gimenez
*
*/
public class HeuristiqueEntropieNormalisee implements HeuristiqueOrdre
{
@Override
public double computeHeuristique(Map<String, Integer> nbExemples) {
double nbExemplesTotal = 0;
for(Integer nb : nbExemples.values())
nbExemplesTotal += nb;
double entropie = 0;
for(Integer nb : nbExemples.values())
if(nb != 0)
entropie -= nb/nbExemplesTotal * Math.log(nb/nbExemplesTotal);
// Normalisation de l'entropie entre 0 et 1 (afin de pouvoir comparer les entropies de variables au nombre de modalité différents)
// System.out.println(entropie+" "+entropie/Math.log(nbExemples.size()));
entropie /= Math.log(nbExemples.size());
return entropie;
}
}
| gpl-3.0 |
foodcoop1040/foodsoft | spec/models/user_spec.rb | 2550 | require_relative '../spec_helper'
describe User do
it 'is correctly created' do
user = create :user,
nick: 'johnnydoe', first_name: 'Johnny', last_name: 'DoeBar',
email: 'johnnydoe@foodcoop.test', phone: '+1234567890'
expect(user.nick).to eq('johnnydoe')
expect(user.first_name).to eq('Johnny')
expect(user.last_name).to eq('DoeBar')
expect(user.name).to eq('Johnny DoeBar')
expect(user.email).to eq('johnnydoe@foodcoop.test')
expect(user.phone).to eq('+1234567890')
end
describe 'does not have the role' do
let(:user) { create :user }
it 'admin' do expect(user.role_admin?).to be_falsey end
it 'finance' do expect(user.role_finance?).to be_falsey end
it 'article_meta' do expect(user.role_article_meta?).to be_falsey end
it 'suppliers' do expect(user.role_suppliers?).to be_falsey end
it 'orders' do expect(user.role_orders?).to be_falsey end
end
describe do
let(:user) { create :user, password: 'blahblah' }
it 'can authenticate with correct password' do
expect(User.authenticate(user.nick, 'blahblah')).to be_truthy
end
it 'can not authenticate with incorrect password' do
expect(User.authenticate(user.nick, 'foobar')).to be_nil
end
it 'can not authenticate with nil nick' do
expect(User.authenticate(nil, 'blahblah')).to be_nil
end
it 'can not authenticate with nil password' do
expect(User.authenticate(user.nick, nil)).to be_nil
end
it 'can not set a password without matching confirmation' do
user.password = 'abcdefghij'
user.password_confirmation = 'foobarxyz'
expect(user).to be_invalid
end
it 'can set a password with matching confirmation' do
user.password = 'abcdefghij'
user.password_confirmation = 'abcdefghij'
expect(user).to be_valid
end
it 'has a unique nick' do
expect(build(:user, nick: user.nick, email: "x-#{user.email}")).to be_invalid
end
it 'has a unique email' do
expect(build(:user, email: "#{user.email}")).to be_invalid
end
it 'can authenticate using email address' do
expect(User.authenticate(user.email, 'blahblah')).to be_truthy
end
it 'can authenticate when there is no nick' do
user.nick = nil
expect(user).to be_valid
expect(User.authenticate(user.email, 'blahblah')).to be_truthy
end
end
describe 'admin' do
let(:user) { create :admin }
it 'default admin role' do expect(user.role_admin?).to be_truthy end
end
end
| gpl-3.0 |
censam/open_cart | multilanguage/OC-Europa-1-5-1-3-9.part01/upload/admin/language/polski/module/store.php | 1363 | <?php
/**
* OpenCart 1.5.1.1 Polskie Tłumaczenie
*
* This script is protected by copyright. It's use, copying, modification
* and distribution without written consent of the author is prohibited.
*
*
* @category OpenCart
* @package OpenCart
* @author Krzysztof Kardasz <krzysztof.kardasz@gmail.com>
* @copyright Copyright (c) 2011 Krzysztof Kardasz
* @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU Lesser General Public
* @version 1.5.1.1 $Id: store.php 3 2011-08-29 11:09:52Z krzysztof.kardasz $
* @link http://opencart-polish.googlecode.com
* @link http://opencart-polish.googlecode.com/svn/branches/1.5.x/
*/
// Heading
$_['heading_title'] = 'Sklep';
// Text
$_['text_module'] = 'Moduły';
$_['text_success'] = 'Sukces: Zmiany modułu sklep zostały zapisane!';
$_['text_content_top'] = 'Góra strony';
$_['text_content_bottom'] = 'Dół strony';
$_['text_column_left'] = 'Lewa kolumna';
$_['text_column_right'] = 'Prawa kolumna';
// Entry
$_['entry_admin'] = 'Tylko administratorzy:';
$_['entry_layout'] = 'Szablon:';
$_['entry_position'] = 'Pozycja:';
$_['entry_status'] = 'Status:';
$_['entry_sort_order'] = 'Kolejność sortowania:';
// Error
$_['error_permission'] = 'Uwaga: Nie masz uprawnień do modyfikacji modułu sklepu!';
?> | gpl-3.0 |
dmitry-vlasov/mdl | src/nstd/type/traits/indicator/nstd_type_traits_indicator_Null.hpp | 1249 | /*****************************************************************************/
/* Project name: nstd - non-standard library */
/* File name: nstd_type_traits_indicator_Null.hpp */
/* Description: Null type indicator */
/* Copyright: (c) 2006-2009 Dmitri Vlasov */
/* Author: Dmitri Yurievich Vlasov, Novosibirsk, Russia */
/* Email: vlasov at academ.org */
/* URL: http://mathdevlanguage.sourceforge.net */
/* Modified by: */
/* License: GNU General Public License Version 3 */
/*****************************************************************************/
#pragma once
#include "type/constant/nstd_type_constant.hpp"
namespace nstd {
namespace type {
namespace traits {
namespace indicator {
/****************************
* Null type
****************************/
template<class T>
struct Null {
enum { result = false };
};
template<>
struct Null<type :: Null> {
enum { result = true };
};
}
}
}
}
| gpl-3.0 |
CalgaryCommunityTeams/2015RobotCode | src/edu/first/util/TextFiles.java | 3167 | package edu.first.util;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
/**
* A set of utility methods to manipulate text files. Behavior of IO is
* documented in Javadocs.
*
* @since May 14 13
* @author Joel Gallant
*/
public final class TextFiles {
// cannot be subclassed or instantiated
private TextFiles() throws IllegalAccessException {
throw new IllegalAccessException();
}
/**
* Returns the text that is currently in a text file. Does not assume ".txt"
* ending, so file type must be added manually.
*
* All IO error are caught and logged <i>inside</i> of this method, as they
* are assumed to be things that are unaccountable for (hardware issues).
*
* If an IO error occurs, this method returns null. That is the only
* occasion that this method will return null, so it is safe to assume that
* null means an error occurred.
*
* @param file file to get text from
* @return contents of that file
* @throws java.io.IOException when reading causes an error
* @throws NullPointerException when file name is null
*/
public static String getTextFromFile(File file) throws IOException {
if (file == null) {
throw new NullPointerException();
}
try {
return new String(Files.readAllBytes(file.toPath()));
} catch (IOException ex) {
throw ex;
}
}
/**
* Writes the text as the full text file. Everything else is deleted.
*
* @param file file to write to
* @param msg text to set the file to
* @throws java.io.IOException when writing causes an error
*/
public static void writeAsFile(File file, String msg) throws IOException {
write(file, msg, false);
}
/**
* Writes the text at the very end of the file.
*
* @param file file to write to
* @param msg text to add to the end of the file
* @throws java.io.IOException when writing causes an error
*/
public static void appendToFile(File file, String msg) throws IOException {
write(file, msg, true);
}
/**
* Writes the text to a new line at the end of the file.
*
* @param file file to write to
* @param msg text to add to the end of the file
* @throws java.io.IOException when writing causes an error
*/
public static void appendToNewLine(File file, String msg) throws IOException {
appendToFile(file, "\n" + msg);
}
private static void write(File f, String m, boolean append) throws IOException {
FileWriter fw = null;
try {
fw = new FileWriter(f, append);
fw.write(m);
fw.close();
} catch (IOException ex) {
throw ex;
} finally {
try {
if (fw != null) {
fw.close();
}
} catch (IOException ex) {
throw ex;
}
}
}
}
| gpl-3.0 |
epfl-lara/leon | src/unit-test/scala/leon/purescala/ArrayQuantifiersInstantiation.scala | 897 | /* Copyright 2009-2015 EPFL, Lausanne */
package leon
package purescala
import leon.purescala.Common._
import leon.purescala.Definitions._
import leon.purescala.Types._
import leon.purescala.Expressions._
import leon.purescala.TreeNormalizations._
class ArrayQuantifiersInstantiationSuite extends LeonTestSuite with ExpressionsBuilder {
val arr = FreshIdentifier("arr", ArrayType(IntegerType)).toVariable
val elId = FreshIdentifier("el", IntegerType)
val allPos = ArrayForall(arr,
InfiniteIntegerLiteral(0), ArrayLength(arr),
Lambda(Seq(ValDef(elId)), GreaterEquals(elId.toVariable, InfiniteIntegerLiteral(0)))
)
val kId = FreshIdentifier("k", IntegerType)
val oneNeg = LessThan(ArraySelect(arr, kId.toVariable), InfiniteIntegerLiteral(0))
test("test") {
ArrayQuantifiersInstantiation.instantiate(And(allPos, oneNeg))
}
}
| gpl-3.0 |
aelred/mindmapsdb | grakn-test/src/test/java/ai/grakn/graphs/NguyenGraph.java | 4122 | /*
* Grakn - A Distributed Semantic Database
* Copyright (C) 2016 Grakn Labs Limited
*
* Grakn is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Grakn is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>.
*/
package ai.grakn.graphs;
import ai.grakn.GraknGraph;
import ai.grakn.GraknGraphFactory;
import ai.grakn.concept.ConceptId;
import ai.grakn.concept.EntityType;
import ai.grakn.concept.RelationType;
import ai.grakn.concept.RoleType;
import ai.grakn.concept.TypeName;
import java.util.function.Consumer;
public class NguyenGraph extends TestGraph {
private final static TypeName key = TypeName.of("index");
private final static String gqlFile = "nguyen-test.gql";
private final int n;
public NguyenGraph(int n){
this.n = n;
}
public static Consumer<GraknGraph> get(int n) {
return new NguyenGraph(n).build();
}
@Override
public Consumer<GraknGraph> build(){
return (GraknGraph graph) -> {
loadFromFile(graph, gqlFile);
buildExtensionalDB(graph, n);
};
}
private void buildExtensionalDB(GraknGraph graph, int n) {
RoleType Rfrom = graph.getRoleType("R-rA");
RoleType Rto = graph.getRoleType("R-rB");
RoleType Qfrom = graph.getRoleType("Q-rA");
RoleType Qto = graph.getRoleType("Q-rB");
RoleType Pfrom = graph.getRoleType("P-rA");
RoleType Pto = graph.getRoleType("P-rB");
EntityType entity = graph.getEntityType("entity2");
EntityType aEntity = graph.getEntityType("a-entity");
EntityType bEntity = graph.getEntityType("b-entity");
RelationType R = graph.getRelationType("R");
RelationType P = graph.getRelationType("P");
RelationType Q = graph.getRelationType("Q");
ConceptId cId = putEntity(graph, "c", entity, key).getId();
ConceptId dId = putEntity(graph, "d", entity, key).getId();
ConceptId eId = putEntity(graph, "e", entity, key).getId();
ConceptId[] aInstancesIds = new ConceptId[n+2];
ConceptId[] bInstancesIds = new ConceptId[n+2];
aInstancesIds[n+1] = putEntity(graph, "a" + (n+1), aEntity, key).getId();
for(int i = 0 ; i <= n ;i++) {
aInstancesIds[i] = putEntity(graph, "a" + i, aEntity, key).getId();
bInstancesIds[i] = putEntity(graph, "b" + i, bEntity, key).getId();
}
R.addRelation()
.putRolePlayer(Rfrom, graph.getConcept(dId))
.putRolePlayer(Rto, graph.getConcept(eId));
P.addRelation()
.putRolePlayer(Pfrom, graph.getConcept(cId))
.putRolePlayer(Pto, graph.getConcept(dId));
Q.addRelation()
.putRolePlayer(Qfrom, graph.getConcept(eId))
.putRolePlayer(Qto, graph.getConcept(aInstancesIds[0]));
for(int i = 0 ; i <= n ;i++){
P.addRelation()
.putRolePlayer(Pfrom, graph.getConcept(bInstancesIds[i]))
.putRolePlayer(Pto, graph.getConcept(cId));
P.addRelation()
.putRolePlayer(Pfrom, graph.getConcept(cId))
.putRolePlayer(Pto, graph.getConcept(bInstancesIds[i]));
Q.addRelation()
.putRolePlayer(Qfrom, graph.getConcept(aInstancesIds[i]))
.putRolePlayer(Qto, graph.getConcept(bInstancesIds[i]));
Q.addRelation()
.putRolePlayer(Qfrom, graph.getConcept(bInstancesIds[i]))
.putRolePlayer(Qto, graph.getConcept(aInstancesIds[i+1]));
}
}
}
| gpl-3.0 |
AlexIIL/AlexIILLib-DEPRECATED | src/main/java/alexiil/mods/lib/item/IChangingItemString.java | 527 | package alexiil.mods.lib.item;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
public interface IChangingItemString {
/** @param i
* The item to get a string from
* @param player
* The player, BEWARE! this player is client side, so will not have any of the NBT the exists on the
* server
* @return A localized string to be displayed to the player. */
String[] getString(ItemStack i, EntityPlayer player);
}
| gpl-3.0 |
calamares/calamares | src/libcalamaresui/modulesystem/PythonQtViewModule.cpp | 5915 | /* === This file is part of Calamares - <https://calamares.io> ===
*
* SPDX-FileCopyrightText: 2016 Teo Mrnjavac <teo@kde.org>
* SPDX-FileCopyrightText: 2018 Adriaan de Groot <groot@kde.org>
* SPDX-FileCopyrightText: 2018 Raul Rodrigo Segura <raurodse@gmail.com>
* SPDX-License-Identifier: GPL-3.0-or-later
*
* Calamares is Free Software: see the License-Identifier above.
*
*/
#include "PythonQtViewModule.h"
#include "CalamaresConfig.h"
#include "GlobalStorage.h"
#include "JobQueue.h"
#include "ViewManager.h"
#include "utils/Logger.h"
#include "viewpages/PythonQtGlobalStorageWrapper.h"
#include "viewpages/PythonQtUtilsWrapper.h"
#include "viewpages/PythonQtViewStep.h"
#include "viewpages/ViewStep.h"
#include <PythonQt.h>
#include <PythonQt_QtAll.h>
#include <QDir>
#include <QPointer>
static QPointer< GlobalStorage > s_gs = nullptr;
static QPointer< Utils > s_utils = nullptr;
namespace Calamares
{
Module::Type
PythonQtViewModule::type() const
{
return Module::Type::View;
}
Module::Interface
PythonQtViewModule::interface() const
{
return Module::Interface::PythonQt;
}
void
PythonQtViewModule::loadSelf()
{
if ( !m_scriptFileName.isEmpty() )
{
if ( PythonQt::self() == nullptr )
{
if ( Py_IsInitialized() )
PythonQt::init( PythonQt::IgnoreSiteModule | PythonQt::RedirectStdOut
| PythonQt::PythonAlreadyInitialized );
else
{
PythonQt::init();
}
PythonQt_QtAll::init();
cDebug() << "Initializing PythonQt bindings."
<< "This should only happen once.";
//TODO: register classes here into the PythonQt environment, like this:
//PythonQt::self()->registerClass( &PythonQtViewStep::staticMetaObject,
// "calamares" );
// We only do the following to force PythonQt to create a submodule
// "calamares" for us to put our static objects in
PythonQt::self()->registerClass( &::GlobalStorage::staticMetaObject, "calamares" );
// Get a PythonQtObjectPtr to the PythonQt.calamares submodule
PythonQtObjectPtr pqtm = PythonQt::priv()->pythonQtModule();
PythonQtObjectPtr cala = PythonQt::self()->lookupObject( pqtm, "calamares" );
// Prepare GlobalStorage object, in module PythonQt.calamares
if ( !s_gs )
{
s_gs = new ::GlobalStorage( Calamares::JobQueue::instance()->globalStorage() );
}
cala.addObject( "global_storage", s_gs );
// Prepare Utils object, in module PythonQt.calamares
if ( !s_utils )
{
s_utils = new ::Utils( Calamares::JobQueue::instance()->globalStorage() );
}
cala.addObject( "utils", s_utils );
// Append configuration object, in module PythonQt.calamares
cala.addVariable( "configuration", m_configurationMap );
// Basic stdout/stderr handling
QObject::connect( PythonQt::self(), &PythonQt::pythonStdOut, []( const QString& message ) {
cDebug() << "PythonQt OUT>" << message;
} );
QObject::connect( PythonQt::self(), &PythonQt::pythonStdErr, []( const QString& message ) {
cDebug() << "PythonQt ERR>" << message;
} );
}
QDir workingDir( m_workingPath );
if ( !workingDir.exists() )
{
cDebug() << "Invalid working directory" << m_workingPath << "for module" << name();
return;
}
QString fullPath = workingDir.absoluteFilePath( m_scriptFileName );
QFileInfo scriptFileInfo( fullPath );
if ( !scriptFileInfo.isReadable() )
{
cDebug() << "Invalid main script file path" << fullPath << "for module" << name();
return;
}
// Construct empty Python module with the given name
PythonQtObjectPtr cxt = PythonQt::self()->createModuleFromScript( name() );
if ( cxt.isNull() )
{
cDebug() << "Cannot load PythonQt context from file" << fullPath << "for module" << name();
return;
}
static const QLatin1String calamares_module_annotation(
"_calamares_module_typename = ''\n"
"def calamares_module(viewmodule_type):\n"
" global _calamares_module_typename\n"
" _calamares_module_typename = viewmodule_type.__name__\n"
" return viewmodule_type\n" );
// Load in the decorator
PythonQt::self()->evalScript( cxt, calamares_module_annotation );
// Load the module
PythonQt::self()->evalFile( cxt, fullPath );
m_viewStep = new PythonQtViewStep( cxt );
cDebug() << "PythonQtViewModule loading self for instance" << instanceKey() << "\nPythonQtViewModule at address"
<< this << "\nViewStep at address" << m_viewStep;
m_viewStep->setModuleInstanceKey( instanceKey() );
m_viewStep->setConfigurationMap( m_configurationMap );
ViewManager::instance()->addViewStep( m_viewStep );
m_loaded = true;
cDebug() << "PythonQtViewModule" << instanceKey() << "loading complete.";
}
}
JobList
PythonQtViewModule::jobs() const
{
return m_viewStep->jobs();
}
void
PythonQtViewModule::initFrom( const QVariantMap& moduleDescriptor )
{
QDir directory( location() );
m_workingPath = directory.absolutePath();
if ( !moduleDescriptor.value( "script" ).toString().isEmpty() )
{
m_scriptFileName = moduleDescriptor.value( "script" ).toString();
}
}
PythonQtViewModule::PythonQtViewModule()
: Module()
{
}
PythonQtViewModule::~PythonQtViewModule() {}
} // namespace Calamares
| gpl-3.0 |
felinoidthekeratincoated/landwalkers | src/EventHandler.hh | 3343 | #ifndef EVENTHANDLER_HH
#define EVENTHANDLER_HH
#include <vector>
#include <SDL2/SDL.h>
// forward declare
class WindowHandler;
class Player;
class Inventory;
class Hotbar;
class World;
struct MouseBox;
struct StatBar;
class Menu;
class DroppedItem;
/* A struct to hold information about which keys do what. This is so that
later the player can change these settings. */
struct KeySettings {
// Which keys are for movement
std::vector<SDL_Scancode> leftKeys, rightKeys, upKeys, downKeys, jumpKeys;
// Keys to open the inventory and whatever opens along with it
std::vector<SDL_Scancode> inventoryKeys;
// 24 keys to select a hotbar slot
std::vector<SDL_Scancode> hotbarKeys;
/* Keys to toss items onto the ground. */
std::vector<SDL_Scancode> tossKeys;
};
/* A class to handle events such as keyboard input or mouse movement. */
class EventHandler {
// Which keys do what
KeySettings keySettings;
// Whether the player is trying to move in some direction
bool left, right, up, down, jump;
// Veriables to keep track of the one jump per key press rule
bool isJumping;
bool hasJumped; // as in, since the last time the key was pressed
// The state of the mouse
bool isLeftButtonDown;
bool isRightButtonDown;
bool wasLeftButtonDown;
bool wasRightButtonDown;
// For when the button is pressed and released multiple times in a frame
int leftClicks;
int rightClicks;
// To move by one pixel at a time, in the vertical direction
// This currently only exists for debugging
int move; // TODO: remove
// Helper functions
// Tell whether a scancode is in a vector
bool isIn(SDL_Scancode key, std::vector<SDL_Scancode> keys);
// Tell whether a vector has a key that's being held down
bool isHeld(const Uint8 *state, std::vector<SDL_Scancode> keys);
public:
// Update a single mouse box
bool updateBox(MouseBox &box);
// Change the bool values of a MouseBox vector so they know whether they
// were clicked
// Return true if the mouse clicked any of the boxes
bool updateMouseBoxes(std::vector<MouseBox> &mouseBoxes);
// Update the mouseboxes of an inventory
// Return true if the mouse clicked any of the boxes
bool updateInventoryClickBoxes(Inventory &inventory);
// Constructor
EventHandler();
// Access methods
KeySettings getKeySettings();
void setKeySettings(KeySettings &newSettings); // non-ideal name
// Handle events
void windowEvent(const SDL_Event &event, bool &isFocused,
WindowHandler &window);
// Update the state of the mouse
void mouseEvent(const SDL_Event &event);
// Do whatever should be done when a mouse event happens
void useMouse(Player &player, World &world);
// Do whatever should be done when a key is pressed or released
void keyEvent(const SDL_Event &event, Player &player,
std::vector<DroppedItem *> &drops);
// Do stuff for keys being held down
void updateKeys(const Uint8 *state);
// Tell the Player what its trying to do
void updatePlayer(Player &player);
// Update the menu's mouseboxes
void updateMenu(Menu &menu);
// Do all the stuff that needs to be done every frame
void update(World &world);
};
#endif
| gpl-3.0 |
fmreina/20162-INE5424-Agrupamento2-Tema1.1-ComponentesDeControleEAutomacao-17 | ine5424/src/machine/pc/timer_test.cc | 1067 | // EPOS PC_Timer Test Program
#include <utility/ostream.h>
#include <machine.h>
#include <display.h>
#include <timer.h>
using namespace EPOS;
OStream cout;
void handler()
{
static int elapsed;
int lin, col;
Display::position(&lin, &col);
Display::position(0, 60 + Machine::cpu_id() * 2);
Display::putc((elapsed++ % 10) + 48);
Display::position(lin, col);
}
int main()
{
cout << "PC_Timer test" << endl;
User_Timer timer(10000, handler);
for(int i = 0; i < 10000; i++);
cout << "count = " << timer.read() << "" << endl;
for(int i = 0; i < 10000; i++);
cout << "count = " << timer.read() << "" << endl;
for(int i = 0; i < 10000; i++);
cout << "count = " << timer.read() << "" << endl;
for(int i = 0; i < 10000; i++);
cout << "count = " << timer.read() << "" << endl;
for(int i = 0; i < 10000; i++);
cout << "count = " << timer.read() << "" << endl;
for(int i = 0; i < 10000; i++);
cout << "count = " << timer.read() << "" << endl;
cout << "The End!" << endl;
return 0;
}
| gpl-3.0 |
justmedude/librenms | includes/html/modal/alert_schedule.inc.php | 18859 | <?php
/*
* LibreNMS
*
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
*
* 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. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
if (\Auth::user()->hasGlobalAdmin()) {
?>
<div class="modal fade bs-example-modal-sm" id="schedule-maintenance" tabindex="-1" role="dialog" aria-labelledby="Create" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h5 class="modal-title" id="Create">Create maintenance</h5>
</div>
<div class="modal-body">
<form method="post" role="form" id="sched-form" class="form-horizontal schedule-maintenance-form">
<?php echo csrf_field() ?>
<input type="hidden" name="schedule_id" id="schedule_id">
<input type="hidden" name="type" id="type" value="schedule-maintenance">
<input type="hidden" name="sub_type" id="sub_type" value="new-maintenance">
<div class="row">
<div class="col-md-12">
<span id="response"></span>
</div>
</div>
<div class="form-group">
<label for="title" class="col-sm-4 control-label">Title <exp>*</exp>: </label>
<div class="col-sm-8">
<input type="text" class="form-control" id="title" name="title" placeholder="Maintenance title">
</div>
</div>
<div class="form-group">
<label for="notes" class="col-sm-4 control-label">Notes: </label>
<div class="col-sm-8">
<textarea class="form-control" id="notes" name="notes" placeholder="Maintenance notes"></textarea>
</div>
</div>
<div class="form-group">
<label for="recurring" class="col-sm-4 control-label">Recurring <strong class="text-danger">*</strong>: </label>
<div class="col-sm-8">
<input type="checkbox" id="recurring" name="recurring" data-size="small" data-on-text="Yes" data-off-text="No" onChange="recurring_switch();" value=0 />
</div>
</div>
<div id="norecurringgroup">
<div class="form-group">
<label for="start" class="col-sm-4 control-label">Start <exp>*</exp>: </label>
<div class="col-sm-8">
<input type="text" class="form-control date" id="start" name="start" value="" data-date-format="YYYY-MM-DD HH:mm">
</div>
</div>
<div class="form-group">
<label for="end" class="col-sm-4 control-label">End <exp>*</exp>: </label>
<div class="col-sm-8">
<input type="text" class="form-control date" id="end" name="end" value="" data-date-format="YYYY-MM-DD HH:mm">
</div>
</div>
</div>
<div id="recurringgroup" style="display:none;">
<div class="form-group">
<label for="start_recurring_dt" class="col-sm-4 control-label">Start date <exp>*</exp>: </label>
<div class="col-sm-8">
<input type="text" class="form-control date" id="start_recurring_dt" name="start_recurring_dt" value="" data-date-format="YYYY-MM-DD">
</div>
</div>
<div class="form-group">
<label for="end_recurring_dt" class="col-sm-4 control-label">End date: </label>
<div class="col-sm-8">
<input type="text" class="form-control date" id="end_recurring_dt" name="end_recurring_dt" value="" data-date-format="YYYY-MM-DD">
</div>
</div>
<div class="form-group">
<label for="start_recurring_hr" class="col-sm-4 control-label">Start hour <exp>*</exp>: </label>
<div class="col-sm-8">
<input type="text" class="form-control date" id="start_recurring_hr" name="start_recurring_hr" value="" data-date-format="HH:mm">
</div>
</div>
<div class="form-group">
<label for="end_recurring_hr" class="col-sm-4 control-label">End hour <exp>*</exp>: </label>
<div class="col-sm-8">
<input type="text" class="form-control date" id="end_recurring_hr" name="end_recurring_hr" value="" data-date-format="HH:mm">
</div>
</div>
<div class="form-group">
<label for="recurring_day" class="col-sm-4 control-label">Only on weekday: </label>
<div class="col-sm-8">
<div style="float: left;"><label><input type="checkbox" style="width: 20px;" class="form-control" id="recurring_day" name="recurring_day[]" value="1" />Mo</label></div>
<div style="float: left;padding-left: 20px;"><label><input type="checkbox" style="width: 20px;" class="form-control" id="recurring_day" name="recurring_day[]" value="2" />Tu</label></div>
<div style="float: left;padding-left: 20px;"><label><input type="checkbox" style="width: 20px;" class="form-control" id="recurring_day" name="recurring_day[]" value="3" />We</label></div>
<div style="float: left;padding-left: 20px;"><label><input type="checkbox" style="width: 20px;" class="form-control" id="recurring_day" name="recurring_day[]" value="4" />Th</label></div>
<div style="float: left;padding-left: 20px;"><label><input type="checkbox" style="width: 20px;" class="form-control" id="recurring_day" name="recurring_day[]" value="5" />Fr</label></div>
<div style="float: left;padding-left: 20px;"><label><input type="checkbox" style="width: 20px;" class="form-control" id="recurring_day" name="recurring_day[]" value="6" />Sa</label></div>
<div style="float: left;padding-left: 20px;"><label><input type="checkbox" style="width: 20px;" class="form-control" id="recurring_day" name="recurring_day[]" value="0" />Su</label></div>
</div>
</div>
</div>
<div class="form-group">
<label for='maps' class='col-sm-4 control-label'>Map To <exp>*</exp>: </label>
<div class="col-sm-8">
<select id="maps" name="maps[]" class="form-control" multiple="multiple"></select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
<button class="btn btn-success" type="submit" name="sched-submit" id="sched-submit" value="save">Schedule maintenance</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
$('#schedule-maintenance').on('hide.bs.modal', function (event) {
$('#maps').val(null).trigger('change');
$('#schedule_id').val('');
$('#title').val('');
$('#notes').val('');
$('#recurring').val('');
$('#start').val(moment().format('YYYY-MM-DD HH:mm')).data("DateTimePicker").maxDate(false).minDate(moment());
$('#end').val(moment().add(1, 'hour').format('YYYY-MM-DD HH:mm')).data("DateTimePicker").maxDate(false).minDate(moment());
var $startRecurringDt = $('#start_recurring_dt');
$startRecurringDt.val('').data("DateTimePicker").maxDate(false).minDate(moment());
var $endRecurringDt = $('#end_recurring_dt');
$endRecurringDt.data("DateTimePicker").date(moment()).maxDate(false).minDate(moment());
$endRecurringDt.val('');
$startRecurringDt.data("DateTimePicker").maxDate(false);
$('#start_recurring_hr').val('').data("DateTimePicker").minDate(false).maxDate(false);
$('#end_recurring_hr').val('').data("DateTimePicker").minDate(false).maxDate(false);
$('#recurring_day').prop('checked', false);
$("#recurring").bootstrapSwitch('state', false);
$('#recurring').val(0);
$('#norecurringgroup').show();
$('#recurringgroup').hide();
$('#schedulemodal-alert').remove();
});
$('#schedule-maintenance').on('show.bs.modal', function (event) {
var schedule_id = $('#schedule_id').val();
if (schedule_id > 0) {
$.ajax({
type: "POST",
url: "ajax_form.php",
data: { type: "schedule-maintenance", sub_type: "parse-maintenance", schedule_id: schedule_id },
dataType: "json",
success: function(output) {
var maps = $('#maps');
var selected = [];
$.each ( output['targets'], function( key, item ) {
// create options if they don't exist
if (maps.find("option[value='" + item.id + "']").length === 0) {
var newOption = new Option(item.text, item.id, true, true);
maps.append(newOption);
}
selected.push(item.id);
});
maps.val(selected).trigger('change');
$('#title').val(output['title']);
$('#notes').val(output['notes']);
if (output['recurring'] == 0){
var start = $('#start').data("DateTimePicker");
if (output['start']) {
start.minDate(output['start']);
}
start.date(output['start']);
$('#end').data("DateTimePicker").date(output['end']);
$('#norecurringgroup').show();
$('#recurringgroup').hide();
$('#start_recurring_dt').val('');
$('#end_recurring_dt').val('');
$('#start_recurring_hr').val('');
$('#end_recurring_hr').val('');
$('#recurring_day').prop('checked', false);
$("#recurring").bootstrapSwitch('state', false);
$('#recurring').val(0);
}else{
var start_recurring_dt = $('#start_recurring_dt').data("DateTimePicker");
if (output['start_recurring_dt']) {
start_recurring_dt.minDate(output['start_recurring_dt']);
}
start_recurring_dt.date(output['start_recurring_dt']);
$('#end_recurring_dt').data("DateTimePicker").date(output['end_recurring_dt']);
var start_recurring_hr = $('#start_recurring_hr').data("DateTimePicker");
if (output['start_recurring_dt']) {
start_recurring_dt.minDate(output['start_recurring_dt']);
}
start_recurring_hr.date(output['start_recurring_hr']);
$('#end_recurring_hr').data("DateTimePicker").date(output['end_recurring_hr']);
$("#recurring").bootstrapSwitch('state', true);
$('#recurring').val(1);
var recdayupd = output['recurring_day'];
if (recdayupd){
var arrayrecdayupd = recdayupd.split(',');
$.each(arrayrecdayupd, function(indexcheckedday, checkedday){
$("input[name='recurring_day[]'][value="+checkedday+"]").prop('checked', true);
});
}else{
$('#recurring_day').prop('checked', false);
}
$('#norecurringgroup').hide();
$('#recurringgroup').show();
$('#start').val('');
$('#end').val('');
}
}
});
}
});
function recurring_switch() {
if (document.getElementById("recurring").checked){
$('#norecurringgroup').hide();
$('#recurringgroup').show();
$('#recurring').val(1);
}else{
$('#norecurringgroup').show();
$('#recurringgroup').hide();
$('#recurring').val(0);
}
};
$('#sched-submit').click('', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "ajax_form.php",
data: $('form.schedule-maintenance-form').serialize(),
dataType: "json",
success: function(data){
if(data.status == 'ok') {
$("#message").html('<div id="schedulemsg" class="alert alert-info"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+data.message+'</div>');
window.setTimeout(function() { $('#schedulemsg').fadeOut().slideUp(); } , 5000);
$("#schedule-maintenance").modal('hide');
$("#schedulemodal-alert").remove();
$("#alert-schedule").bootgrid('reload');
} else {
$("#response").html('<div id="schedulemodal-alert" class="alert alert-danger">'+data.message+'</div>');
}
},
error: function(){
$("#response").html('<div id="schedulemodal-alert" class="alert alert-danger">An error occurred.</div>');
}
});
});
$("#maps").select2({
width: '100%',
placeholder: "Devices, Groups or Locations",
ajax: {
url: 'ajax_list.php',
delay: 250,
data: function (params) {
return {
type: 'devices_groups_locations',
search: params.term
};
}
}
});
$(function () {
$("#start").datetimepicker({
defaultDate: moment(),
minDate: moment().format('YYYY-MM-DD'),
icons: {
time: 'fa fa-clock-o',
date: 'fa fa-calendar',
up: 'fa fa-chevron-up',
down: 'fa fa-chevron-down',
previous: 'fa fa-chevron-left',
next: 'fa fa-chevron-right',
today: 'fa fa-calendar-check-o',
clear: 'fa fa-trash-o',
close: 'fa fa-close'
}
});
$("#end").datetimepicker({
defaultDate: moment().add(1, 'hour'),
minDate: moment().format('YYYY-MM-DD'),
icons: {
time: 'fa fa-clock-o',
date: 'fa fa-calendar',
up: 'fa fa-chevron-up',
down: 'fa fa-chevron-down',
previous: 'fa fa-chevron-left',
next: 'fa fa-chevron-right',
today: 'fa fa-calendar-check-o',
clear: 'fa fa-trash-o',
close: 'fa fa-close'
}
});
$("#start").on("dp.change", function (e) {
$("#end").data("DateTimePicker").minDate(e.date);
});
$("#end").on("dp.change", function (e) {
$("#start").data("DateTimePicker").maxDate(e.date);
});
$("#start_recurring_dt").datetimepicker({
defaultDate: moment(),
minDate: moment().format('YYYY-MM-DD'),
icons: {
time: 'fa fa-clock-o',
date: 'fa fa-calendar',
up: 'fa fa-chevron-up',
down: 'fa fa-chevron-down',
previous: 'fa fa-chevron-left',
next: 'fa fa-chevron-right',
today: 'fa fa-calendar-check-o',
clear: 'fa fa-trash-o',
close: 'fa fa-close'
}
});
$("#end_recurring_dt").datetimepicker({
minDate: moment().format('YYYY-MM-DD'),
icons: {
time: 'fa fa-clock-o',
date: 'fa fa-calendar',
up: 'fa fa-chevron-up',
down: 'fa fa-chevron-down',
previous: 'fa fa-chevron-left',
next: 'fa fa-chevron-right',
today: 'fa fa-calendar-check-o',
clear: 'fa fa-trash-o',
close: 'fa fa-close'
}
});
$("#start_recurring_dt").on("dp.change", function (e) {
var $endRecurringDt = $("#end_recurring_dt");
var val = $endRecurringDt.val();
$endRecurringDt.data("DateTimePicker").minDate(e.date);
// work around annoying event interaction
if (!val) {
$endRecurringDt.val('');
$("#start_recurring_dt").data("DateTimePicker").maxDate(false);
}
});
$("#end_recurring_dt").on("dp.change", function (e) {
$("#start_recurring_dt").data("DateTimePicker").maxDate(e.date);
});
$("#start_recurring_hr").datetimepicker({
icons: {
time: 'fa fa-clock-o',
date: 'fa fa-calendar',
up: 'fa fa-chevron-up',
down: 'fa fa-chevron-down',
previous: 'fa fa-chevron-left',
next: 'fa fa-chevron-right',
today: 'fa fa-calendar-check-o',
clear: 'fa fa-trash-o',
close: 'fa fa-close'
}
});
$("#end_recurring_hr").datetimepicker({
icons: {
time: 'fa fa-clock-o',
date: 'fa fa-calendar',
up: 'fa fa-chevron-up',
down: 'fa fa-chevron-down',
previous: 'fa fa-chevron-left',
next: 'fa fa-chevron-right',
today: 'fa fa-calendar-check-o',
clear: 'fa fa-trash-o',
close: 'fa fa-close'
}
});
$("#start_recurring_hr").on("dp.change", function (e) {
$("#end_recurring_hr").data("DateTimePicker").minDate(e.date);
});
$("#end_recurring_hr").on("dp.change", function (e) {
$("#start_recurring_hr").data("DateTimePicker").maxDate(e.date);
});
});
$("[name='recurring']").bootstrapSwitch();
</script>
<?php
}
| gpl-3.0 |
mhmli/helpers | wordpress/class.wordpress_database.php | 888 | <?php
/*
database functions for wordpress
*/
class wordpress_db {
function is_tree($pid){
// is the current page a subpage of page id $pid?
// mhm 2010
$anc = get_post_ancestors($GLOBALS['post']->ID);
foreach($anc as $ancestor):
if(is_page() && $ancestor == $pid):
return true;
endif;
endforeach;
if(is_page()&&(is_page($pid))):
return true; // we're at the page or at a sub page
else:
return false; // we're elsewhere
endif;
}
function get_tag_id($tag_name) {
$taxarray = is_term($tag_name, 'post_tag');
return $taxarray["term_id"];
}//get_tag_id
function wp_get_parent_slug($postID){
// 2008-11-18 | 2013-03-14 mhm
$parentpost = $wpdb->get_row('SELECT post_name FROM '.$GLOBALS['wpdb']->posts.' WHERE ID='.$GLOBALS['post']->parent_post);
return $parentpost ? $parentpost->post_name : false;
}//wp_get_parent_slug
}//end class | gpl-3.0 |
OpenFOAM/OpenFOAM-5.x | src/regionModels/surfaceFilmModels/thermoSingleLayer/thermoSingleLayerI.H | 4340 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2017 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/>.
\*---------------------------------------------------------------------------*/
#include "thermoSingleLayer.H"
#include "filmRadiationModel.H"
#include "heatTransferModel.H"
#include "phaseChangeModel.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace regionModels
{
namespace surfaceFilmModels
{
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
inline const SLGThermo& thermoSingleLayer::thermo() const
{
return thermo_;
}
inline tmp<scalarField> thermoSingleLayer::hs
(
const scalarField& T,
const label patchi
) const
{
const scalarField& Cp = Cp_.boundaryField()[patchi];
return Cp*(T - Tref.value());
}
inline tmp<volScalarField> thermoSingleLayer::hs
(
const volScalarField& T
) const
{
return tmp<volScalarField>
(
new volScalarField
(
IOobject
(
"hs(" + T.name() + ")",
time().timeName(),
regionMesh(),
IOobject::NO_READ,
IOobject::NO_WRITE
),
Cp_*(T - Tref)
)
);
}
inline tmp<volScalarField> thermoSingleLayer::T
(
const volScalarField& hs
) const
{
tmp<volScalarField> tT
(
new volScalarField
(
IOobject
(
"T(" + hs.name() + ")",
time().timeName(),
regionMesh(),
IOobject::NO_READ,
IOobject::NO_WRITE
),
hs/Cp_ + Tref
)
);
tT.ref().min(Tmax_);
tT.ref().max(Tmin_);
return tT;
}
inline const volScalarField& thermoSingleLayer::hsSp() const
{
return hsSp_;
}
inline const volScalarField& thermoSingleLayer::hsSpPrimary() const
{
return hsSpPrimary_;
}
inline const volScalarField& thermoSingleLayer::TPrimary() const
{
return TPrimary_;
}
inline const PtrList<volScalarField>& thermoSingleLayer::YPrimary() const
{
return YPrimary_;
}
inline const heatTransferModel& thermoSingleLayer::htcs() const
{
return htcs_();
}
inline const heatTransferModel& thermoSingleLayer::htcw() const
{
return htcw_();
}
inline const phaseChangeModel& thermoSingleLayer::phaseChange() const
{
return phaseChange_();
}
inline const filmRadiationModel& thermoSingleLayer::radiation() const
{
return radiation_();
}
inline tmp<scalarField> thermoSingleLayer::Qconvw(const label patchi) const
{
const scalarField htc(htcw_->h()().boundaryField()[patchi]);
const scalarField& Tp = T_.boundaryField()[patchi];
const scalarField& Twp = Tw_.boundaryField()[patchi];
return htc*(Tp - Twp);
}
inline tmp<scalarField> thermoSingleLayer::Qconvp(const label patchi) const
{
const scalarField htc(htcs_->h()().boundaryField()[patchi]);
const scalarField& Tp = T_.boundaryField()[patchi];
const scalarField& Tpp = TPrimary_.boundaryField()[patchi];
return htc*(Tp - Tpp);
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace surfaceFilmModels
} // End namespace regionModels
} // End namespace Foam
// ************************************************************************* //
| gpl-3.0 |
donald-w/Anki-Android | lint-rules/src/test/java/com/ichi2/anki/lint/rules/DirectDateInstantiationTest.java | 4736 | package com.ichi2.anki.lint.rules;
import org.intellij.lang.annotations.Language;
import org.junit.Test;
import static com.android.tools.lint.checks.infrastructure.TestFile.JavaTestFile.create;
import static com.android.tools.lint.checks.infrastructure.TestLintTask.lint;
import static org.junit.Assert.assertTrue;
public class DirectDateInstantiationTest {
@Language("JAVA")
private final String stubDate = " \n" +
"package java.util; \n" +
" \n" +
"public class Date { \n" +
" \n" +
" public Date() { \n" +
" \n" +
" } \n" +
" public Date(long time) { \n" +
" \n" +
" } \n" +
"} \n";
@Language("JAVA")
private final String javaFileToBeTested = " \n" +
"package com.ichi2.anki.lint.rules; \n" +
" \n" +
"import java.util.Date; \n" +
" \n" +
"public class TestJavaClass { \n" +
" \n" +
" public static void main(String[] args) { \n" +
" Date d = new Date(); \n" +
" } \n" +
"} \n";
@Language("JAVA")
private final String javaFileWithTime = " \n" +
"package com.ichi2.anki.lint.rules; \n" +
" \n" +
"import java.util.Date; \n" +
" \n" +
"public abstract class Time { \n" +
" \n" +
" public static void main(String[] args) { \n" +
" Date d = new Date(); \n" +
" } \n" +
"} \n";
@Language("JAVA")
private final String javaFileUsingDateWithLong = " \n" +
"package com.ichi2.anki.lint.rules; \n" +
" \n" +
"import java.util.Date; \n" +
" \n" +
"public class TestJavaClass { \n" +
" \n" +
" public static void main(String[] args) { \n" +
" Date d = new Date(1L); \n" +
" } \n" +
"} \n";
@Test
public void showsErrorsForInvalidUsage() {
lint().
allowMissingSdk().
allowCompilationErrors()
.files(create(stubDate), create(javaFileToBeTested))
.issues(DirectDateInstantiation.ISSUE)
.run()
.expectErrorCount(1)
.check(output -> {
assertTrue(output.contains(DirectDateInstantiation.ID));
assertTrue(output.contains(DirectDateInstantiation.DESCRIPTION));
});
}
@Test
public void allowsUsageInTimeClass() {
lint().
allowMissingSdk().
allowCompilationErrors()
.files(create(stubDate), create(javaFileWithTime))
.issues(DirectDateInstantiation.ISSUE)
.run()
.expectClean();
}
@Test
public void allowsUsageWithLongValue() {
lint().
allowMissingSdk().
allowCompilationErrors()
.files(create(stubDate), create(javaFileUsingDateWithLong))
.issues(DirectDateInstantiation.ISSUE)
.run()
.expectClean();
}
}
| gpl-3.0 |
khozzy/pyalcs | lcs/strategies/action_planning/goal_sequence_searcher.py | 11083 | from typing import List, Optional, Tuple
from lcs import Perception
from lcs.agents.acs2 import Classifier
from lcs.agents.acs2.ClassifiersList import ClassifiersList
class GoalSequenceSearcher:
def __init__(self):
self.forward_classifiers = []
self.backward_classifiers = []
self.forward_perceptions = []
self.backward_perceptions = []
def search_goal_sequence(self,
reliable_classifiers: ClassifiersList,
start: Perception,
goal: Perception) -> list:
"""
Searches a path from start to goal using a bidirectional method in the
environmental model (i.e. the list of reliable classifiers).
Parameters
----------
reliable_classifiers
list of reliable classifiers
start: Perception
goal: Perception
Returns
-------
list
sequence of actions
"""
if len(reliable_classifiers) < 1:
return []
max_depth = 6
forward_size = 1
backward_size = 1
forward_point = 0
backward_point = 0
action_sequence = None
self.forward_classifiers.clear()
self.backward_classifiers.clear()
self.forward_perceptions.clear()
self.backward_perceptions.clear()
self.forward_perceptions.append(Perception(start))
self.backward_perceptions.append(Perception(goal))
for depth in range(0, max_depth):
# forward step
action_sequence, forward_size_new = \
self._search_one_forward_step(reliable_classifiers,
forward_size, forward_point)
forward_point = forward_size
forward_size = forward_size_new
if action_sequence is not None:
return action_sequence
# backwards step
action_sequence, backward_size_new = \
self._search_one_backward_step(reliable_classifiers,
backward_size, backward_point)
backward_point = backward_size
backward_size = backward_size_new
if action_sequence is not None:
return action_sequence
# depth limit was reached -> return empty action sequence
return []
def _search_one_forward_step(self,
reliable_classifiers: ClassifiersList,
forward_size: int,
forward_point: int) -> Tuple[Optional[list],
int]:
"""
Searches one step forward in the reliable_classifiers classifier list.
Returns None if nothing was found so far, a sequence with a -1 element
if the search failed completely
(which is the case if the allowed array size of 10000 is reached),
or the sequence if one was found.
:param reliable_classifiers: ClassifiersList
:param forward_size: int
:param forward_point: int
:return: act sequence and new forward_size
"""
size = forward_size
for i in range(forward_point, forward_size):
match_forward = reliable_classifiers. \
form_match_set(situation=self.forward_perceptions[i])
for match_set_element in match_forward:
anticipation = match_set_element. \
get_best_anticipation(self.forward_perceptions[i])
if self.get_state_idx(self.forward_perceptions,
anticipation) is None:
# state not detected forward -> search in backwards
backward_sequence_idx = self. \
get_state_idx(self.backward_perceptions,
anticipation)
if backward_sequence_idx is None:
# state neither detected backwards
self.forward_perceptions.append(anticipation)
self.forward_classifiers.append(
self._form_new_classifiers(
self.forward_classifiers, i,
match_set_element))
size += 1
if size > 10001:
# logging.debug("Arrays are full")
return [], size
else:
# sequence found
return self._form_sequence_forwards(
i, backward_sequence_idx, match_set_element), size
return None, size
def _search_one_backward_step(self,
reliable_classifiers: ClassifiersList,
backward_size: int,
backward_point: int) -> Tuple[Optional[list],
int]:
"""
Searches one step backward in the reliable_classifiers classifiers list
Returns None if nothing was found so far, a sequence with a -1 element
if the search failed completely
(which is the case if the allowed array size of 10000 is reached),
or the sequence if one was found.
:param reliable_classifiers: ClassifiersList
:param backward_size: int
:param backward_point: int
:return: act sequence and new backward_size
"""
size = backward_size
for i in range(backward_point, backward_size):
match_backward = reliable_classifiers.form_match_set_backwards(
situation=self.backward_perceptions[i])
for match_set_el in match_backward:
anticipation = match_set_el. \
get_backwards_anticipation(self.backward_perceptions[i])
if anticipation is not None and self. \
get_state_idx(self.backward_perceptions,
anticipation) is None:
# Backwards anticipation was formable but
# not detected backwards
forward_sequence_idx = self.\
get_state_idx(self.forward_perceptions,
anticipation)
if forward_sequence_idx is None:
self.backward_perceptions.append(anticipation)
self.backward_classifiers.append(
self._form_new_classifiers(
self.backward_classifiers, i, match_set_el))
size += 1
if size > 10001:
# logging.debug("Arrays are full")
return [], size
else:
return self._form_sequence_backwards(
i, forward_sequence_idx, match_set_el), size
return None, size
@staticmethod
def _form_new_classifiers(classifiers_lists: List[ClassifiersList],
i: int,
match_set_el: Classifier) -> ClassifiersList:
"""
Executes actions after sequence was not detected.
:param classifiers_lists: list of ClassifiersLists
:param i: int
:param match_set_el: Classifier
:return: new size of classifiers
"""
if i > 0:
new_classifiers = ClassifiersList()
new_classifiers.extend(classifiers_lists[i - 1])
else:
new_classifiers = ClassifiersList()
new_classifiers.append(match_set_el)
return new_classifiers
def _form_sequence_forwards(self, i: int,
backward_sequence_idx: int,
match_set_el: Classifier) -> list:
"""
Forms sequence when it was found forwards.
:param i:
:param backward_sequence_idx:
:param match_set_el: Classifier
:return: act sequence
"""
# count sequence size
sequence_size = 0
if i > 0:
sequence_size += len(self.forward_classifiers[i - 1])
if backward_sequence_idx > 0:
sequence_size += len(self.backward_classifiers[
backward_sequence_idx - 1])
sequence_size += 1
# construct sequence
act_seq: list = [-1] * sequence_size
j = 0
if i > 0:
for j, cl in enumerate(self.forward_classifiers[i - 1]):
act_seq[len(self.forward_classifiers[i - 1]) - j - 1] \
= cl.action
j += 1
act_seq[j] = match_set_el.action
j += 1
if backward_sequence_idx > 0:
for k, cl in enumerate(self.backward_classifiers[
backward_sequence_idx - 1]):
act_seq[k + j] = cl.action
return act_seq
def _form_sequence_backwards(self, i: int,
forward_sequence_idx: int,
match_set_el: Classifier) -> list:
"""
Forms sequence when it was found backwards.
:param i: int
:param forward_sequence_idx: int
:param match_set_el: Classifier
:return: act sequence
"""
# count sequence size
sequence_size = 0
if i > 0:
sequence_size += len(self.backward_classifiers[i - 1])
if forward_sequence_idx > 0:
sequence_size += len(
self.forward_classifiers[forward_sequence_idx - 1])
sequence_size += 1
# construct sequence
act_seq: list = [-1] * sequence_size
j = 0
if forward_sequence_idx > 0:
for j, cl in enumerate(self.forward_classifiers[
forward_sequence_idx - 1]):
act_seq[len(self.forward_classifiers[
forward_sequence_idx - 1]) - j - 1] = cl.action
j += 1
act_seq[j] = match_set_el.action
j += 1
if i > 0:
for k, cl in enumerate(self.backward_classifiers[i - 1]):
act_seq[k + j] = cl.action
return act_seq
@staticmethod
def get_state_idx(perceptions: List[Perception],
state: Perception) -> Optional[int]:
"""
Returns the position of state in list of perception.
Parameters
----------
perceptions: List[Perception]
list of perceptions
state: Perception
sought perception
Returns
-------
Optional[int]
Position of perception, None if perception was not found
"""
try:
return perceptions.index(state)
except ValueError:
return None
| gpl-3.0 |
censam/open_cart | multilanguage/OC-Europa-1-5-1-3-9.part01/upload/catalog/language/serbian/account/transaction.php | 414 | <?php
// Heading
$_['heading_title'] = 'Vaše transakcije';
// Column
$_['column_date_added'] = 'Datum dodavanja';
$_['column_description'] = 'Opis';
$_['column_amount'] = 'Iznos (%s)';
// Text
$_['text_account'] = 'Nalog';
$_['text_transaction'] = 'Vaše transakcije';
$_['text_total'] = 'Vaše trenutno stanje je:';
$_['text_empty'] = 'Nemate evidentiranih transakcija!';
?> | gpl-3.0 |
davisc/django-osgeo-importer | osgeo_importer/tasks.py | 3670 | import os
import shutil
from osgeo_importer.models import UploadFile
import celery
from osgeo_importer.views import OSGEO_IMPORTER
import logging
from geonode.celery_app import app
from osgeo_importer.models import UploadLayer, UploadException
from django.conf import settings
logger = logging.getLogger(__name__)
class ExceptionLoggingTask(celery.Task):
def on_failure(self, exc, task_id, args, kwargs, einfo):
celery.Task.on_failure(self, exc, task_id, args, kwargs, einfo)
msg = '{}(args={}, kwargs={}): {}\n{}'.format(task_id, args, kwargs, einfo, exc)
logger.debug(msg)
@app.task(base=ExceptionLoggingTask, bind=True)
def add(a, b):
logger.info('{} + {} = {}'.format(a, b, a + b))
return a + b
class RecordImportStateTask(ExceptionLoggingTask):
def on_failure(self, exc, task_id, args, kwargs, einfo):
ExceptionLoggingTask.on_failure(self, exc, task_id, args, kwargs, einfo)
logger.info('Layer import task failed, recording UploadLayer.import_status')
configuration_options = kwargs['configuration_options']
ulid = configuration_options['upload_layer_id']
try:
ul = UploadLayer.objects.get(id=ulid)
UploadException.objects.create(error=exc,
verbose_traceback=einfo,
task_id=task_id, upload_layer=ul)
except UploadLayer.DoesNotExist:
msg = 'Got invalid UploadLayer id: {}'.format(ulid)
logger.error(msg)
raise
ul.import_status = 'FAILURE'
ul.save()
def on_success(self, retval, task_id, args, kwargs):
configuration_options = kwargs['configuration_options']
ExceptionLoggingTask.on_success(self, retval, task_id, args, kwargs)
ulid = configuration_options['upload_layer_id']
try:
ul = UploadLayer.objects.get(id=ulid)
except UploadLayer.DoesNotExist:
msg = 'Got invalid UploadLayer id: {}'.format(ulid)
logger.error(msg)
raise
logger.info('Layer import task successful, recording UploadLayer.import_status')
ul.import_status = 'SUCCESS'
ul.save()
try:
import_task_soft_time_limit = settings.IMPORT_TASK_SOFT_TIME_LIMIT
except AttributeError:
import_task_soft_time_limit = 90
@app.task(base=RecordImportStateTask, soft_time_limit=import_task_soft_time_limit, bind=True)
def import_object(self, upload_file_id, configuration_options=None, request_cookies=None, request_user=None):
"""
Imports a file into GeoNode.
:param configuration_options: List of configuration objects for each layer that is being imported.
"""
logger.info('Starting import_object() task for layer "{}"'.format(configuration_options.get('layer_name', 'n/a')))
ulid = configuration_options['upload_layer_id']
try:
ul = UploadLayer.objects.get(id=ulid)
except UploadLayer.DoesNotExist:
msg = 'Got invalid UploadLayer id: {}'.format(ulid)
logger.error(msg)
raise
ul.task_id = self.request.id
ul.import_status = 'PENDING'
ul.save()
upload_file = UploadFile.objects.get(id=upload_file_id)
logger.info('Creating importer')
gi = OSGEO_IMPORTER(upload_file.file.path, upload_file=upload_file)
logger.info('Calling importer.handle()')
gi.handle(configuration_options=configuration_options, request_cookies=request_cookies, request_user=request_user)
return
@app.task(base=ExceptionLoggingTask)
def remove_path(path):
"""
Removes a path using shutil.rmtree.
"""
if os.path.exists(path):
shutil.rmtree(path)
| gpl-3.0 |
Sebbyastian/openfaction | shared/CKillableObject.cpp | 789 | /*****************************************************************************
*
* PROJECT: Open Faction
* LICENSE: See LICENSE in the top level directory
* FILE: shared/CKillableObject.cpp
* PURPOSE: Base class for all objects with life
* DEVELOPERS: Rafal Harabien
*
*****************************************************************************/
#include "CKillableObject.h"
SDamageInfo SDamageInfo::Default;
CKillableObject::CKillableObject(EElementType Type, CLevel *pLevel, unsigned nUid):
CObject(Type, pLevel, nUid), m_fLife(100.0f) {}
void CKillableObject::Damage(float fDmg, SDamageInfo &DmgInfo)
{
if(m_fLife > 0.0f && fDmg > 0.0f)
{
if(fDmg < m_fLife)
m_fLife -= fDmg;
else
Kill(DmgInfo);
}
}
| gpl-3.0 |
vanan08/android-browser-cmcsoft | src/org/cmc/utils/Constants.java | 6300 | /*
* CMC Browser for Android
*
* Copyright (C) 2010 J. Devauchelle and contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.cmc.utils;
import org.cmc.R;
import android.content.Context;
/**
* Defines constants.
*/
public class Constants {
public static final String EXTRA_ID_NEW_TAB = "EXTRA_ID_NEW_TAB";
public static final String EXTRA_ID_URL = "EXTRA_ID_URL";
public static final String EXTRA_ID_BOOKMARK_ID = "EXTRA_ID_BOOKMARK_ID";
public static final String EXTRA_ID_BOOKMARK_URL = "EXTRA_ID_BOOKMARK_URL";
public static final String EXTRA_ID_BOOKMARK_TITLE = "EXTRA_ID_BOOKMARK_TITLE";
public static final String EXTRA_SAVED_URL = "EXTRA_SAVED_URL";
public static final int BOOKMARK_THUMBNAIL_WIDTH_FACTOR = 70;
public static final int BOOKMARK_THUMBNAIL_HEIGHT_FACTOR = 60;
/**
* Specials urls.
*/
public static final String URL_ABOUT_BLANK = "about:blank";
public static final String URL_ABOUT_START = "about:start";
public static final String URL_ACTION_SEARCH = "action:search?q=";
public static final String URL_GOOGLE_MOBILE_VIEW = "http://www.google.com/gwt/x?u=%s";
public static final String URL_GOOGLE_MOBILE_VIEW_NO_FORMAT = "http://www.google.com/gwt/x?u=";
/**
* Search urls.
*/
public static String URL_SEARCH_GOOGLE = "http://www.google.com/search?ie=UTF-8&sourceid=navclient&gfns=1&q=%s";
public static String URL_SEARCH_WIKIPEDIA = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
/**
* User agents.
*/
public static String USER_AGENT_DEFAULT = "";
public static String USER_AGENT_DESKTOP = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7";
/**
* Preferences.
*/
public static final String PREFERENCES_GENERAL_HOME_PAGE = "GeneralHomePage";
public static final String PREFERENCES_GENERAL_SEARCH_URL = "GeneralSearchUrl";
public static final String PREFERENCES_GENERAL_SWITCH_TABS_METHOD = "GeneralSwitchTabMethod";
public static final String PREFERENCES_GENERAL_BARS_DURATION = "GeneralBarsDuration";
public static final String PREFERENCES_GENERAL_BUBBLE_POSITION = "GeneralBubblePosition";
public static final String PREFERENCES_SHOW_FULL_SCREEN = "GeneralFullScreen";
public static final String PREFERENCES_GENERAL_HIDE_TITLE_BARS = "GeneralHideTitleBars";
public static final String PREFERENCES_SHOW_TOAST_ON_TAB_SWITCH = "GeneralShowToastOnTabSwitch";
public static final String PREFERENCES_UI_VOLUME_KEYS_BEHAVIOUR = "GeneralVolumeKeysBehaviour";
public static final String PREFERENCES_DEFAULT_ZOOM_LEVEL = "DefaultZoomLevel";
public static final String PREFERENCES_BROWSER_HISTORY_SIZE = "BrowserHistorySize";
public static final String PREFERENCES_BROWSER_ENABLE_JAVASCRIPT = "BrowserEnableJavascript";
public static final String PREFERENCES_BROWSER_ENABLE_IMAGES = "BrowserEnableImages";
public static final String PREFERENCES_BROWSER_USE_WIDE_VIEWPORT = "BrowserUseWideViewPort";
public static final String PREFERENCES_BROWSER_LOAD_WITH_OVERVIEW = "BrowserLoadWithOverview";
public static final String PREFERENCES_BROWSER_ENABLE_FORM_DATA = "BrowserEnableFormData";
public static final String PREFERENCES_BROWSER_ENABLE_PASSWORDS = "BrowserEnablePasswords";
public static final String PREFERENCES_BROWSER_ENABLE_COOKIES = "BrowserEnableCookies";
public static final String PREFERENCES_BROWSER_USER_AGENT = "BrowserUserAgent";
public static final String PREFERENCES_BROWSER_ENABLE_PLUGINS_ECLAIR = "BrowserEnablePluginsEclair";
public static final String PREFERENCES_BROWSER_ENABLE_PROXY_SETTINGS = "BrowserEnableProxySettings";
public static final String PREFERENCES_BROWSER_ENABLE_PLUGINS = "BrowserEnablePlugins";
public static final String PREFERENCES_BROWSER_RESTORE_LAST_PAGE = "PREFERENCES_BROWSER_RESTORE_LAST_PAGE";
public static final String PREFERENCES_PRIVACY_CLEAR_CACHE_ON_EXIT = "PrivacyClearCacheOnExit";
public static final String PREFERENCES_ADBLOCKER_ENABLE = "AdBlockerEnable";
public static final String PREFERENCES_BOOKMARKS_SORT_MODE = "BookmarksSortMode";
public static final String PREFERENCES_LAST_VERSION_CODE = "LastVersionCode";
public static final String PREFERENCES_START_PAGE_SHOW_SEARCH = "StartPageEnableSearch";
public static final String PREFERENCES_START_PAGE_SHOW_BOOKMARKS = "StartPageEnableBookmarks";
public static final String PREFERENCES_START_PAGE_SHOW_HISTORY = "StartPageEnableHistory";
public static final String PREFERENCES_START_PAGE_BOOKMARKS_LIMIT = "StartPageBookmarksLimit";
public static final String PREFERENCES_START_PAGE_HISTORY_LIMIT = "StartPageHistoryLimit";
public static final String PREFERENCE_USE_WEAVE = "PREFERENCE_USE_WEAVE";
public static final String PREFERENCE_WEAVE_SERVER = "PREFERENCE_WEAVE_SERVER";
public static final String PREFERENCE_WEAVE_USERNAME = "PREFERENCE_WEAVE_USERNAME";
public static final String PREFERENCE_WEAVE_PASSWORD = "PREFERENCE_WEAVE_PASSWORD";
public static final String PREFERENCE_WEAVE_KEY = "PREFERENCE_WEAVE_KEY";
public static final String PREFERENCE_WEAVE_LAST_SYNC_DATE = "PREFERENCE_WEAVE_LAST_SYNC_DATE";
public static final String WEAVE_AUTH_TOKEN_SCHEME = "{\"secret\":\"%s\",\"password\":\"%s\",\"username\":\"%s\",\"server\":\"%s\"}";
public static final String WEAVE_DEFAULT_SERVER = "https://auth.services.mozilla.com/";
public static final String PREFERENCE_BOOKMARKS_DATABASE = "PREFERENCE_BOOKMARKS_DATABASE";
/**
* Methods.
*/
/**
* Initialize the search url "constants", which depends on the user local.
* @param context The current context.
*/
public static void initializeConstantsFromResources(Context context) {
URL_SEARCH_GOOGLE = context.getResources().getString(R.string.Constants_SearchUrlGoogle);
URL_SEARCH_WIKIPEDIA = context.getResources().getString(R.string.Constants_SearchUrlWikipedia);
}
}
| gpl-3.0 |
manifestcreative/woocommerce | includes/class-wc-api.php | 11668 | <?php
/**
* WooCommerce API
*
* Handles WC-API endpoint requests.
*
* @author WooThemes
* @category API
* @package WooCommerce/API
* @since 2.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* API class.
*/
class WC_API extends WC_Legacy_API {
/**
* Setup class.
*
* @since 2.0
*/
public function __construct() {
parent::__construct();
// Add query vars.
add_filter( 'query_vars', array( $this, 'add_query_vars' ), 0 );
// Register API endpoints.
add_action( 'init', array( $this, 'add_endpoint' ), 0 );
// Handle wc-api endpoint requests.
add_action( 'parse_request', array( $this, 'handle_api_requests' ), 0 );
// Ensure payment gateways are initialized in time for API requests.
add_action( 'woocommerce_api_request', array( 'WC_Payment_Gateways', 'instance' ), 0 );
// WP REST API.
$this->rest_api_init();
}
/**
* Add new query vars.
*
* @since 2.0
* @param array $vars Query vars.
* @return string[]
*/
public function add_query_vars( $vars ) {
$vars = parent::add_query_vars( $vars );
$vars[] = 'wc-api';
return $vars;
}
/**
* WC API for payment gateway IPNs, etc.
*
* @since 2.0
*/
public static function add_endpoint() {
parent::add_endpoint();
add_rewrite_endpoint( 'wc-api', EP_ALL );
}
/**
* API request - Trigger any API requests.
*
* @since 2.0
* @version 2.4
*/
public function handle_api_requests() {
global $wp;
if ( ! empty( $_GET['wc-api'] ) ) { // WPCS: input var okay, CSRF ok.
$wp->query_vars['wc-api'] = sanitize_key( wp_unslash( $_GET['wc-api'] ) ); // WPCS: input var okay, CSRF ok.
}
// wc-api endpoint requests.
if ( ! empty( $wp->query_vars['wc-api'] ) ) {
// Buffer, we won't want any output here.
ob_start();
// No cache headers.
wc_nocache_headers();
// Clean the API request.
$api_request = strtolower( wc_clean( $wp->query_vars['wc-api'] ) );
// Trigger generic action before request hook.
do_action( 'woocommerce_api_request', $api_request );
// Is there actually something hooked into this API request? If not trigger 400 - Bad request.
status_header( has_action( 'woocommerce_api_' . $api_request ) ? 200 : 400 );
// Trigger an action which plugins can hook into to fulfill the request.
do_action( 'woocommerce_api_' . $api_request );
// Done, clear buffer and exit.
ob_end_clean();
die( '-1' );
}
}
/**
* Init WP REST API.
*
* @since 2.6.0
*/
private function rest_api_init() {
// REST API was included starting WordPress 4.4.
if ( ! class_exists( 'WP_REST_Server' ) ) {
return;
}
$this->rest_api_includes();
// Init REST API routes.
add_action( 'rest_api_init', array( $this, 'register_rest_routes' ), 10 );
}
/**
* Include REST API classes.
*
* @since 2.6.0
*/
private function rest_api_includes() {
// Exception handler.
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-exception.php' );
// Authentication.
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-authentication.php' );
// Abstract controllers.
include_once( dirname( __FILE__ ) . '/abstracts/abstract-wc-rest-controller.php' );
include_once( dirname( __FILE__ ) . '/abstracts/abstract-wc-rest-posts-controller.php' );
include_once( dirname( __FILE__ ) . '/abstracts/abstract-wc-rest-crud-controller.php' );
include_once( dirname( __FILE__ ) . '/abstracts/abstract-wc-rest-terms-controller.php' );
include_once( dirname( __FILE__ ) . '/abstracts/abstract-wc-rest-shipping-zones-controller.php' );
include_once( dirname( __FILE__ ) . '/abstracts/abstract-wc-settings-api.php' );
// REST API v1 controllers.
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-coupons-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-customer-downloads-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-customers-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-orders-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-order-notes-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-order-refunds-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-product-attribute-terms-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-product-attributes-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-product-categories-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-product-reviews-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-product-shipping-classes-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-product-tags-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-products-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-report-sales-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-report-top-sellers-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-reports-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-tax-classes-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-taxes-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-webhook-deliveries-controller.php' );
include_once( dirname( __FILE__ ) . '/api/v1/class-wc-rest-webhooks-controller.php' );
// Legacy v2 code.
include_once( dirname( __FILE__ ) . '/api/legacy/class-wc-rest-legacy-coupons-controller.php' );
include_once( dirname( __FILE__ ) . '/api/legacy/class-wc-rest-legacy-orders-controller.php' );
include_once( dirname( __FILE__ ) . '/api/legacy/class-wc-rest-legacy-products-controller.php' );
// REST API v2 controllers.
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-coupons-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-customer-downloads-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-customers-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-orders-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-network-orders-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-order-notes-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-order-refunds-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-product-attribute-terms-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-product-attributes-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-product-categories-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-product-reviews-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-product-shipping-classes-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-product-tags-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-products-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-product-variations-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-report-sales-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-report-top-sellers-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-reports-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-settings-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-setting-options-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-shipping-zones-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-shipping-zone-locations-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-shipping-zone-methods-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-tax-classes-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-taxes-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-webhook-deliveries-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-webhooks-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-system-status-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-system-status-tools-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-shipping-methods-controller.php' );
include_once( dirname( __FILE__ ) . '/api/class-wc-rest-payment-gateways-controller.php' );
}
/**
* Register REST API routes.
*
* @since 2.6.0
*/
public function register_rest_routes() {
// Register settings to the REST API.
$this->register_wp_admin_settings();
$controllers = array(
// v1 controllers.
'WC_REST_Coupons_V1_Controller',
'WC_REST_Customer_Downloads_V1_Controller',
'WC_REST_Customers_V1_Controller',
'WC_REST_Order_Notes_V1_Controller',
'WC_REST_Order_Refunds_V1_Controller',
'WC_REST_Orders_V1_Controller',
'WC_REST_Product_Attribute_Terms_V1_Controller',
'WC_REST_Product_Attributes_V1_Controller',
'WC_REST_Product_Categories_V1_Controller',
'WC_REST_Product_Reviews_V1_Controller',
'WC_REST_Product_Shipping_Classes_V1_Controller',
'WC_REST_Product_Tags_V1_Controller',
'WC_REST_Products_V1_Controller',
'WC_REST_Report_Sales_V1_Controller',
'WC_REST_Report_Top_Sellers_V1_Controller',
'WC_REST_Reports_V1_Controller',
'WC_REST_Tax_Classes_V1_Controller',
'WC_REST_Taxes_V1_Controller',
'WC_REST_Webhook_Deliveries_V1_Controller',
'WC_REST_Webhooks_V1_Controller',
// v2 controllers.
'WC_REST_Coupons_Controller',
'WC_REST_Customer_Downloads_Controller',
'WC_REST_Customers_Controller',
'WC_REST_Network_Orders_Controller',
'WC_REST_Order_Notes_Controller',
'WC_REST_Order_Refunds_Controller',
'WC_REST_Orders_Controller',
'WC_REST_Product_Attribute_Terms_Controller',
'WC_REST_Product_Attributes_Controller',
'WC_REST_Product_Categories_Controller',
'WC_REST_Product_Reviews_Controller',
'WC_REST_Product_Shipping_Classes_Controller',
'WC_REST_Product_Tags_Controller',
'WC_REST_Products_Controller',
'WC_REST_Product_Variations_Controller',
'WC_REST_Report_Sales_Controller',
'WC_REST_Report_Top_Sellers_Controller',
'WC_REST_Reports_Controller',
'WC_REST_Settings_Controller',
'WC_REST_Setting_Options_Controller',
'WC_REST_Shipping_Zones_Controller',
'WC_REST_Shipping_Zone_Locations_Controller',
'WC_REST_Shipping_Zone_Methods_Controller',
'WC_REST_Tax_Classes_Controller',
'WC_REST_Taxes_Controller',
'WC_REST_Webhook_Deliveries_Controller',
'WC_REST_Webhooks_Controller',
'WC_REST_System_Status_Controller',
'WC_REST_System_Status_Tools_Controller',
'WC_REST_Shipping_Methods_Controller',
'WC_REST_Payment_Gateways_Controller',
);
foreach ( $controllers as $controller ) {
$this->$controller = new $controller();
$this->$controller->register_routes();
}
}
/**
* Register WC settings from WP-API to the REST API.
*
* @since 3.0.0
*/
public function register_wp_admin_settings() {
$pages = WC_Admin_Settings::get_settings_pages();
foreach ( $pages as $page ) {
new WC_Register_WP_Admin_Settings( $page, 'page' );
}
$emails = WC_Emails::instance();
foreach ( $emails->get_emails() as $email ) {
new WC_Register_WP_Admin_Settings( $email, 'email' );
}
}
}
| gpl-3.0 |
syboor/openimsce | openims/libs/tinymce/jscripts/tiny_mce/plugins/pie/editor_plugin_src.js | 2650 | (function() {
// Load plugin specific language pack
tinymce.PluginManager.requireLangPack('pie');
tinymce.create('tinymce.plugins.piePlugin', {
/**
* Initializes the plugin, this will be executed after the plugin has been created.
* This call is done before the editor instance has finished it's initialization so use the onInit event
* of the editor instance to intercept that event.
*
* @param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
* @param {string} url Absolute URL to where the plugin is located.
*/
init : function(ed, url) {
// Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mcepie');
ed.addCommand('mcepie', function() {
ed.windowManager.open({
file : url + '/bin/pie.php',
width : 800 + ed.getLang('pie.delta_width', 0),
height : 800 + ed.getLang('pie.delta_height', 0),
inline : 1
}, {
plugin_url : url, // Plugin absolute URL
some_custom_arg : 'custom arg' // Custom argument
});
});
// Register pie button
ed.addButton('pie', {
title : 'pie.desc',
cmd : 'mcepie',
image : url + '/img/pie.gif'
});
// Add a node change handler, selects the button in the UI when a image is selected
ed.onNodeChange.add(function(ed, cm, n) {
cm.setActive('pie', n.nodeName == 'IMG');
});
var myvalue = get_src_param('IMG');
document.write('myvalue');
},
/**
* Creates control instances based in the incomming name. This method is normally not
* needed since the addButton method of the tinymce.Editor class is a more easy way of adding buttons
* but you sometimes need to create more complex controls like listboxes, split buttons etc then this
* method can be used to create those.
*
* @param {String} n Name of the control to create.
* @param {tinymce.ControlManager} cm Control manager to use inorder to create new control.
* @return {tinymce.ui.Control} New control instance or null if no control was created.
*/
createControl : function(n, cm) {
return null;
},
/**
* Returns information about the plugin as a name/value array.
* The current keys are longname, author, authorurl, infourl and version.
*
* @return {Object} Name/value array containing information about the plugin.
*/
getInfo : function() {
return {
longname : 'pie plugin',
author : 'OpenSesame ICT',
authorurl : 'http://www.opensesameict.com',
infourl : 'http://phpimageeditor.se',
version : "1.0"
};
}
});
// Register plugin
tinymce.PluginManager.add('pie', tinymce.plugins.piePlugin);
})(); | gpl-3.0 |
boydjd/openfisma | library/Zend/Tool/Project/Context/Zf/ApplicationConfigFile.php | 7985 | <?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_Tool
* @subpackage Framework
* @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$
*/
/**
* @see Zend_Tool_Project_Context_Filesystem_File
*/
// require_once 'Zend/Tool/Project/Context/Filesystem/File.php';
/**
* This class is the front most class for utilizing Zend_Tool_Project
*
* A profile is a hierarchical set of resources that keep track of
* items within a specific project.
*
* @category Zend
* @package Zend_Tool
* @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_Tool_Project_Context_Zf_ApplicationConfigFile extends Zend_Tool_Project_Context_Filesystem_File
{
/**
* @var string
*/
protected $_filesystemName = 'application.ini';
/**
* @var string
*/
protected $_content = null;
/**
* getName()
*
* @return string
*/
public function getName()
{
return 'ApplicationConfigFile';
}
/**
* init()
*
* @return Zend_Tool_Project_Context_Zf_ApplicationConfigFile
*/
public function init()
{
$this->_type = $this->_resource->getAttribute('type');
parent::init();
return $this;
}
/**
* getPersistentAttributes()
*
* @return array
*/
public function getPersistentAttributes()
{
return array('type' => $this->_type);
}
/**
* getContents()
*
* @return string
*/
public function getContents()
{
if ($this->_content === null) {
if (file_exists($this->getPath())) {
$this->_content = file_get_contents($this->getPath());
} else {
$this->_content = $this->_getDefaultContents();
}
}
return $this->_content;
}
public function getAsZendConfig($section = 'production')
{
return new Zend_Config_Ini($this->getPath(), $section);
}
/**
* addStringItem()
*
* @param string $key
* @param string $value
* @param string $section
* @param bool $quoteValue
* @return Zend_Tool_Project_Context_Zf_ApplicationConfigFile
*/
public function addStringItem($key, $value, $section = 'production', $quoteValue = true)
{
// null quote value means to auto-detect
if ($quoteValue === null) {
$quoteValue = preg_match('#[\"\']#', $value) ? false : true;
}
if ($quoteValue == true) {
$value = '"' . $value . '"';
}
$contentLines = preg_split('#[\n\r]#', $this->getContents());
$newLines = array();
$insideSection = false;
foreach ($contentLines as $contentLineIndex => $contentLine) {
if ($insideSection === false && preg_match('#^\[' . $section . '#', $contentLine)) {
$insideSection = true;
}
$newLines[] = $contentLine;
if ($insideSection) {
// if its blank, or a section heading
if (isset($contentLines[$contentLineIndex + 1]{0}) && $contentLines[$contentLineIndex + 1]{0} == '[') {
$newLines[] = $key . ' = ' . $value;
$insideSection = null;
} else if (!isset($contentLines[$contentLineIndex + 1])){
$newLines[] = $key . ' = ' . $value;
$insideSection = null;
}
}
}
$this->_content = implode("\n", $newLines);
return $this;
}
/**
*
* @param array $item
* @param string $section
* @param bool $quoteValue
* @return Zend_Tool_Project_Context_Zf_ApplicationConfigFile
*/
public function addItem($item, $section = 'production', $quoteValue = true)
{
$stringItems = array();
$stringValues = array();
$configKeyNames = array();
$rii = new RecursiveIteratorIterator(
new RecursiveArrayIterator($item),
RecursiveIteratorIterator::SELF_FIRST
);
$lastDepth = 0;
// loop through array structure recursively to create proper keys
foreach ($rii as $name => $value) {
$lastDepth = $rii->getDepth();
if (is_array($value)) {
array_push($configKeyNames, $name);
} else {
$stringItems[] = implode('.', $configKeyNames) . '.' . $name;
$stringValues[] = $value;
}
}
foreach ($stringItems as $stringItemIndex => $stringItem) {
$this->addStringItem($stringItem, $stringValues[$stringItemIndex], $section, $quoteValue);
}
return $this;
}
public function removeStringItem($key, $section = 'production')
{
$contentLines = file($this->getPath());
$newLines = array();
$insideSection = false;
foreach ($contentLines as $contentLineIndex => $contentLine) {
if ($insideSection === false && preg_match('#^\[' . $section . '#', $contentLine)) {
$insideSection = true;
}
if ($insideSection) {
// if its blank, or a section heading
if ((trim($contentLine) == null) || ($contentLines[$contentLineIndex + 1][0] == '[')) {
$insideSection = null;
}
}
if (!preg_match('#' . $key . '\s?=.*#', $contentLine)) {
$newLines[] = $contentLine;
}
}
$this->_content = implode('', $newLines);
}
public function removeItem($item, $section = 'production')
{
$stringItems = array();
$stringValues = array();
$configKeyNames = array();
$rii = new RecursiveIteratorIterator(
new RecursiveArrayIterator($item),
RecursiveIteratorIterator::SELF_FIRST
);
$lastDepth = 0;
// loop through array structure recursively to create proper keys
foreach ($rii as $name => $value) {
$lastDepth = $rii->getDepth();
if (is_array($value)) {
array_push($configKeyNames, $name);
} else {
$stringItems[] = implode('.', $configKeyNames) . '.' . $name;
$stringValues[] = $value;
}
}
foreach ($stringItems as $stringItemIndex => $stringItem) {
$this->removeStringItem($stringItem, $section);
}
return $this;
}
protected function _getDefaultContents()
{
$contents =<<<EOS
[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
[staging : production]
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
EOS;
return $contents;
}
}
| gpl-3.0 |
Darkpeninsula/DarkCore-Old | src/server/scripts/Northrend/IcecrownCitadel/instance_icecrown_citadel.cpp | 36867 | /*
* Copyright (C) 2005-2012 MaNGOS <http://www.getmangos.com/>
* Copyright (C) 2008-2012 Trinity <http://www.trinitycore.org/>
* Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2011-2012 Darkpeninsula Project <http://www.darkpeninsula.eu/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "ObjectMgr.h"
#include "ScriptMgr.h"
#include "InstanceScript.h"
#include "ScriptedCreature.h"
#include "Map.h"
#include "PoolMgr.h"
#include "icecrown_citadel.h"
static const DoorData doorData[] =
{
{GO_LORD_MARROWGAR_S_ENTRANCE, DATA_LORD_MARROWGAR, DOOR_TYPE_ROOM, BOUNDARY_N },
{GO_ICEWALL, DATA_LORD_MARROWGAR, DOOR_TYPE_PASSAGE, BOUNDARY_NONE},
{GO_DOODAD_ICECROWN_ICEWALL02, DATA_LORD_MARROWGAR, DOOR_TYPE_PASSAGE, BOUNDARY_NONE},
{GO_ORATORY_OF_THE_DAMNED_ENTRANCE, DATA_LADY_DEATHWHISPER, DOOR_TYPE_ROOM, BOUNDARY_N },
{GO_SAURFANG_S_DOOR, DATA_DEATHBRINGER_SAURFANG, DOOR_TYPE_PASSAGE, BOUNDARY_NONE},
{GO_ORANGE_PLAGUE_MONSTER_ENTRANCE, DATA_FESTERGUT, DOOR_TYPE_ROOM, BOUNDARY_E },
{GO_GREEN_PLAGUE_MONSTER_ENTRANCE, DATA_ROTFACE, DOOR_TYPE_ROOM, BOUNDARY_E },
{GO_SCIENTIST_ENTRANCE, DATA_PROFESSOR_PUTRICIDE, DOOR_TYPE_ROOM, BOUNDARY_E },
{GO_CRIMSON_HALL_DOOR, DATA_BLOOD_PRINCE_COUNCIL, DOOR_TYPE_ROOM, BOUNDARY_S },
{GO_BLOOD_ELF_COUNCIL_DOOR, DATA_BLOOD_PRINCE_COUNCIL, DOOR_TYPE_PASSAGE, BOUNDARY_W },
{GO_BLOOD_ELF_COUNCIL_DOOR_RIGHT, DATA_BLOOD_PRINCE_COUNCIL, DOOR_TYPE_PASSAGE, BOUNDARY_E },
{GO_DOODAD_ICECROWN_BLOODPRINCE_DOOR_01, DATA_BLOOD_QUEEN_LANA_THEL, DOOR_TYPE_ROOM, BOUNDARY_S },
{GO_DOODAD_ICECROWN_GRATE_01, DATA_BLOOD_QUEEN_LANA_THEL, DOOR_TYPE_PASSAGE, BOUNDARY_NONE},
{GO_GREEN_DRAGON_BOSS_ENTRANCE, DATA_VALITHRIA_DREAMWALKER, DOOR_TYPE_ROOM, BOUNDARY_N },
{GO_GREEN_DRAGON_BOSS_EXIT, DATA_VALITHRIA_DREAMWALKER, DOOR_TYPE_PASSAGE, BOUNDARY_S },
{GO_SINDRAGOSA_ENTRANCE_DOOR, DATA_SINDRAGOSA, DOOR_TYPE_ROOM, BOUNDARY_S },
{GO_SINDRAGOSA_SHORTCUT_ENTRANCE_DOOR, DATA_SINDRAGOSA, DOOR_TYPE_PASSAGE, BOUNDARY_E },
{GO_SINDRAGOSA_SHORTCUT_EXIT_DOOR, DATA_SINDRAGOSA, DOOR_TYPE_PASSAGE, BOUNDARY_NONE},
{GO_ICE_WALL, DATA_SINDRAGOSA, DOOR_TYPE_ROOM, BOUNDARY_SE },
{GO_ICE_WALL, DATA_SINDRAGOSA, DOOR_TYPE_ROOM, BOUNDARY_SW },
{0, 0, DOOR_TYPE_ROOM, BOUNDARY_NONE} // END
};
static Position const SindragosaSpawnPos = {4818.700f, 2483.710f, 287.0650f, 3.089233f};
struct WeeklyQuest
{
uint32 npcStart;
uint32 questId[2]; // 10 and 25 man versions
} WeeklyQuestData[5] =
{
{NPC_INFILTRATOR_MINCHAR, {24869, 24875}}, // Deprogramming
{NPC_KOR_KRON_LIEUTENANT, {24870, 24877}}, // Securing the Ramparts
{NPC_ALCHEMIST_ADRIANNA, {24873, 24878}}, // Residue Rendezvous
{NPC_ALRIN_THE_AGILE, {24874, 24879}}, // Blood Quickening
{NPC_VALITHRIA_DREAMWALKER_QUEST, {24872, 24880}}, // Respite for a Tormented Soul
};
class instance_icecrown_citadel : public InstanceMapScript
{
public:
instance_icecrown_citadel() : InstanceMapScript(ICCScriptName, 631) { }
struct instance_icecrown_citadel_InstanceMapScript : public InstanceScript
{
instance_icecrown_citadel_InstanceMapScript(InstanceMap* map) : InstanceScript(map)
{
SetBossNumber(MAX_ENCOUNTER);
LoadDoorData(doorData);
teamInInstance = 0;
ladyDeathwisperElevator = 0;
deathbringerSaurfang = 0;
saurfangDoor = 0;
saurfangEventNPC = 0;
deathbringersCache = 0;
saurfangTeleport = 0;
memset(putricidePipes, 0, 2*sizeof(uint64));
memset(putricideGates, 0, 2*sizeof(uint64));
putricideCollision = 0;
festergut = 0;
rotface = 0;
professorPutricide = 0;
putricideTable = 0;
memset(bloodCouncil, 0, 3*sizeof(uint64));
bloodCouncilController = 0;
bloodQueenLanaThel = 0;
sindragosa = 0;
spinestalker = 0;
rimefang = 0;
frostwyrms = 0;
spinestalkerTrash = 0;
rimefangTrash = 0;
isBonedEligible = true;
isOozeDanceEligible = true;
isNauseaEligible = true;
isOrbWhispererEligible = true;
coldflameJetsState = NOT_STARTED;
}
void OnPlayerEnter(Player* player)
{
if (!teamInInstance)
teamInInstance = player->GetTeam();
}
void OnCreatureCreate(Creature* creature)
{
if (!teamInInstance)
{
Map::PlayerList const &players = instance->GetPlayers();
if (!players.isEmpty())
if (Player* player = players.begin()->getSource())
teamInInstance = player->GetTeam();
}
switch (creature->GetEntry())
{
case NPC_KOR_KRON_GENERAL:
if (teamInInstance == ALLIANCE)
creature->UpdateEntry(NPC_ALLIANCE_COMMANDER, ALLIANCE);
break;
case NPC_KOR_KRON_LIEUTENANT:
if (teamInInstance == ALLIANCE)
creature->UpdateEntry(NPC_SKYBREAKER_LIEUTENANT, ALLIANCE);
break;
case NPC_TORTUNOK:
if (teamInInstance == ALLIANCE)
creature->UpdateEntry(NPC_ALANA_MOONSTRIKE, ALLIANCE);
break;
case NPC_GERARDO_THE_SUAVE:
if (teamInInstance == ALLIANCE)
creature->UpdateEntry(NPC_TALAN_MOONSTRIKE, ALLIANCE);
break;
case NPC_UVLUS_BANEFIRE:
if (teamInInstance == ALLIANCE)
creature->UpdateEntry(NPC_MALFUS_GRIMFROST, ALLIANCE);
break;
case NPC_IKFIRUS_THE_VILE:
if (teamInInstance == ALLIANCE)
creature->UpdateEntry(NPC_YILI, ALLIANCE);
break;
case NPC_VOL_GUK:
if (teamInInstance == ALLIANCE)
creature->UpdateEntry(NPC_JEDEBIA, ALLIANCE);
break;
case NPC_HARAGG_THE_UNSEEN:
if (teamInInstance == ALLIANCE)
creature->UpdateEntry(NPC_NIBY_THE_ALMIGHTY, ALLIANCE);
break;
case NPC_GARROSH_HELLSCREAM:
if (teamInInstance == ALLIANCE)
creature->UpdateEntry(NPC_KING_VARIAN_WRYNN, ALLIANCE);
break;
case NPC_DEATHBRINGER_SAURFANG:
deathbringerSaurfang = creature->GetGUID();
break;
case NPC_SE_HIGH_OVERLORD_SAURFANG:
if (teamInInstance == ALLIANCE)
creature->UpdateEntry(NPC_SE_MURADIN_BRONZEBEARD, ALLIANCE);
case NPC_SE_MURADIN_BRONZEBEARD:
saurfangEventNPC = creature->GetGUID();
creature->LastUsedScriptID = creature->GetScriptId();
break;
case NPC_SE_KOR_KRON_REAVER:
if (teamInInstance == ALLIANCE)
creature->UpdateEntry(NPC_SE_SKYBREAKER_MARINE, ALLIANCE);
break;
case NPC_FROST_FREEZE_TRAP:
coldflameJets.insert(creature->GetGUID());
break;
case NPC_FESTERGUT:
festergut = creature->GetGUID();
break;
case NPC_ROTFACE:
rotface = creature->GetGUID();
break;
case NPC_PROFESSOR_PUTRICIDE:
professorPutricide = creature->GetGUID();
break;
case NPC_PRINCE_KELESETH:
bloodCouncil[0] = creature->GetGUID();
break;
case NPC_PRINCE_TALDARAM:
bloodCouncil[1] = creature->GetGUID();
break;
case NPC_PRINCE_VALANAR:
bloodCouncil[2] = creature->GetGUID();
break;
case NPC_BLOOD_ORB_CONTROLLER:
bloodCouncilController = creature->GetGUID();
break;
case NPC_BLOOD_QUEEN_LANA_THEL:
bloodQueenLanaThel = creature->GetGUID();
break;
case NPC_SINDRAGOSA:
sindragosa = creature->GetGUID();
break;
case NPC_SPINESTALKER:
spinestalker = creature->GetGUID();
if (!creature->isDead())
++frostwyrms;
break;
case NPC_RIMEFANG:
rimefang = creature->GetGUID();
if (!creature->isDead())
++frostwyrms;
break;
default:
break;
}
}
// Weekly quest spawn prevention
uint32 GetCreatureEntry(uint32 /*guidLow*/, CreatureData const* data)
{
uint32 entry = data->id;
switch (entry)
{
case NPC_INFILTRATOR_MINCHAR:
case NPC_KOR_KRON_LIEUTENANT:
case NPC_ALCHEMIST_ADRIANNA:
case NPC_ALRIN_THE_AGILE:
case NPC_VALITHRIA_DREAMWALKER_QUEST:
{
for (uint8 questIndex = 0; questIndex < 5; ++questIndex)
{
if (WeeklyQuestData[questIndex].npcStart == entry)
{
uint8 diffIndex = instance->GetSpawnMode() & 1;
if (!sPoolMgr->IsSpawnedObject<Quest>(WeeklyQuestData[questIndex].questId[diffIndex]))
entry = 0;
break;
}
}
break;
}
default:
break;
}
return entry;
}
void OnCreatureRemove(Creature* creature)
{
if (creature->GetEntry() == NPC_FROST_FREEZE_TRAP)
coldflameJets.erase(creature->GetGUID());
}
void OnGameObjectCreate(GameObject* go)
{
switch (go->GetEntry())
{
case GO_DOODAD_ICECROWN_ICEWALL02:
case GO_ICEWALL:
case GO_LORD_MARROWGAR_S_ENTRANCE:
case GO_ORATORY_OF_THE_DAMNED_ENTRANCE:
case GO_ORANGE_PLAGUE_MONSTER_ENTRANCE:
case GO_GREEN_PLAGUE_MONSTER_ENTRANCE:
case GO_SCIENTIST_ENTRANCE:
case GO_CRIMSON_HALL_DOOR:
case GO_BLOOD_ELF_COUNCIL_DOOR:
case GO_BLOOD_ELF_COUNCIL_DOOR_RIGHT:
case GO_DOODAD_ICECROWN_BLOODPRINCE_DOOR_01:
case GO_DOODAD_ICECROWN_GRATE_01:
case GO_GREEN_DRAGON_BOSS_ENTRANCE:
case GO_GREEN_DRAGON_BOSS_EXIT:
case GO_SINDRAGOSA_ENTRANCE_DOOR:
case GO_SINDRAGOSA_SHORTCUT_ENTRANCE_DOOR:
case GO_SINDRAGOSA_SHORTCUT_EXIT_DOOR:
case GO_ICE_WALL:
AddDoor(go, true);
break;
case GO_LADY_DEATHWHISPER_ELEVATOR:
ladyDeathwisperElevator = go->GetGUID();
if (GetBossState(DATA_LADY_DEATHWHISPER) == DONE)
{
go->SetUInt32Value(GAMEOBJECT_LEVEL, 0);
go->SetGoState(GO_STATE_READY);
}
break;
case GO_SAURFANG_S_DOOR:
saurfangDoor = go->GetGUID();
AddDoor(go, true);
break;
case GO_DEATHBRINGER_S_CACHE_10N:
case GO_DEATHBRINGER_S_CACHE_25N:
case GO_DEATHBRINGER_S_CACHE_10H:
case GO_DEATHBRINGER_S_CACHE_25H:
deathbringersCache = go->GetGUID();
break;
case GO_SCOURGE_TRANSPORTER_SAURFANG:
saurfangTeleport = go->GetGUID();
break;
case GO_SCIENTIST_AIRLOCK_DOOR_COLLISION:
putricideCollision = go->GetGUID();
if (GetBossState(DATA_FESTERGUT) == DONE && GetBossState(DATA_ROTFACE) == DONE)
HandleGameObject(putricideCollision, true, go);
break;
case GO_SCIENTIST_AIRLOCK_DOOR_ORANGE:
putricideGates[0] = go->GetGUID();
if (GetBossState(DATA_FESTERGUT) == DONE && GetBossState(DATA_ROTFACE) == DONE)
go->SetGoState(GO_STATE_ACTIVE_ALTERNATIVE);
else if (GetBossState(DATA_FESTERGUT) == DONE)
HandleGameObject(putricideGates[1], false, go);
break;
case GO_SCIENTIST_AIRLOCK_DOOR_GREEN:
putricideGates[1] = go->GetGUID();
if (GetBossState(DATA_ROTFACE) == DONE && GetBossState(DATA_FESTERGUT) == DONE)
go->SetGoState(GO_STATE_ACTIVE_ALTERNATIVE);
else if (GetBossState(DATA_ROTFACE) == DONE)
HandleGameObject(putricideGates[1], false, go);
break;
case GO_DOODAD_ICECROWN_ORANGETUBES02:
putricidePipes[0] = go->GetGUID();
if (GetBossState(DATA_FESTERGUT) == DONE)
HandleGameObject(putricidePipes[0], true, go);
break;
case GO_DOODAD_ICECROWN_GREENTUBES02:
putricidePipes[1] = go->GetGUID();
if (GetBossState(DATA_ROTFACE) == DONE)
HandleGameObject(putricidePipes[1], true, go);
break;
case GO_DRINK_ME:
putricideTable = go->GetGUID();
break;
default:
break;
}
}
void OnGameObjectRemove(GameObject* go)
{
switch (go->GetEntry())
{
case GO_DOODAD_ICECROWN_ICEWALL02:
case GO_ICEWALL:
case GO_LORD_MARROWGAR_S_ENTRANCE:
case GO_ORATORY_OF_THE_DAMNED_ENTRANCE:
case GO_SAURFANG_S_DOOR:
case GO_ORANGE_PLAGUE_MONSTER_ENTRANCE:
case GO_GREEN_PLAGUE_MONSTER_ENTRANCE:
case GO_SCIENTIST_ENTRANCE:
case GO_CRIMSON_HALL_DOOR:
case GO_BLOOD_ELF_COUNCIL_DOOR:
case GO_BLOOD_ELF_COUNCIL_DOOR_RIGHT:
case GO_DOODAD_ICECROWN_BLOODPRINCE_DOOR_01:
case GO_DOODAD_ICECROWN_GRATE_01:
case GO_GREEN_DRAGON_BOSS_ENTRANCE:
case GO_GREEN_DRAGON_BOSS_EXIT:
case GO_SINDRAGOSA_ENTRANCE_DOOR:
case GO_SINDRAGOSA_SHORTCUT_ENTRANCE_DOOR:
case GO_SINDRAGOSA_SHORTCUT_EXIT_DOOR:
case GO_ICE_WALL:
AddDoor(go, false);
break;
default:
break;
}
}
uint32 GetData(uint32 type)
{
switch (type)
{
case DATA_SINDRAGOSA_FROSTWYRMS:
return frostwyrms;
case DATA_SPINESTALKER:
return spinestalkerTrash;
case DATA_RIMEFANG:
return rimefangTrash;
case DATA_COLDFLAME_JETS:
return coldflameJetsState;
default:
break;
}
return 0;
}
uint64 GetData64(uint32 type)
{
switch (type)
{
case DATA_DEATHBRINGER_SAURFANG:
return deathbringerSaurfang;
case DATA_SAURFANG_EVENT_NPC:
return saurfangEventNPC;
case GO_SAURFANG_S_DOOR:
return saurfangDoor;
case GO_SCOURGE_TRANSPORTER_SAURFANG:
return saurfangTeleport;
case DATA_FESTERGUT:
return festergut;
case DATA_ROTFACE:
return rotface;
case DATA_PROFESSOR_PUTRICIDE:
return professorPutricide;
case DATA_PUTRICIDE_TABLE:
return putricideTable;
case DATA_PRINCE_KELESETH_GUID:
return bloodCouncil[0];
case DATA_PRINCE_TALDARAM_GUID:
return bloodCouncil[1];
case DATA_PRINCE_VALANAR_GUID:
return bloodCouncil[2];
case DATA_BLOOD_PRINCES_CONTROL:
return bloodCouncilController;
case DATA_BLOOD_QUEEN_LANA_THEL:
return bloodQueenLanaThel;
case DATA_SINDRAGOSA:
return sindragosa;
case DATA_SPINESTALKER:
return spinestalker;
case DATA_RIMEFANG:
return rimefang;
default:
break;
}
return 0;
}
bool SetBossState(uint32 type, EncounterState state)
{
if (!InstanceScript::SetBossState(type, state))
return false;
switch (type)
{
case DATA_LADY_DEATHWHISPER:
SetBossState(DATA_GUNSHIP_EVENT, state); // TEMP HACK UNTIL GUNSHIP SCRIPTED
if (state == DONE)
if (GameObject* elevator = instance->GetGameObject(ladyDeathwisperElevator))
{
elevator->SetUInt32Value(GAMEOBJECT_LEVEL, 0);
elevator->SetGoState(GO_STATE_READY);
}
break;
case DATA_DEATHBRINGER_SAURFANG:
switch (state)
{
case DONE:
DoRespawnGameObject(deathbringersCache, 7*DAY);
case NOT_STARTED:
if (GameObject* teleporter = instance->GetGameObject(saurfangTeleport))
{
HandleGameObject(saurfangTeleport, true, teleporter);
teleporter->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
}
break;
default:
break;
}
break;
case DATA_FESTERGUT:
if (state == DONE)
{
if (GetBossState(DATA_ROTFACE) == DONE)
{
HandleGameObject(putricideCollision, true);
if (GameObject* go = instance->GetGameObject(putricideGates[0]))
go->SetGoState(GO_STATE_ACTIVE_ALTERNATIVE);
if (GameObject* go = instance->GetGameObject(putricideGates[1]))
go->SetGoState(GO_STATE_ACTIVE_ALTERNATIVE);
}
else
HandleGameObject(putricideGates[0], false);
HandleGameObject(putricidePipes[0], true);
}
break;
case DATA_ROTFACE:
if (state == DONE)
{
if (GetBossState(DATA_FESTERGUT) == DONE)
{
HandleGameObject(putricideCollision, true);
if (GameObject* go = instance->GetGameObject(putricideGates[0]))
go->SetGoState(GO_STATE_ACTIVE_ALTERNATIVE);
if (GameObject* go = instance->GetGameObject(putricideGates[1]))
go->SetGoState(GO_STATE_ACTIVE_ALTERNATIVE);
}
else
HandleGameObject(putricideGates[1], false);
HandleGameObject(putricidePipes[1], true);
}
break;
case DATA_VALITHRIA_DREAMWALKER:
case DATA_SINDRAGOSA:
case DATA_THE_LICH_KING:
break;
default:
break;
}
return true;
}
void SetData(uint32 type, uint32 data)
{
switch (type)
{
case DATA_BONED_ACHIEVEMENT:
isBonedEligible = data ? true : false;
break;
case DATA_OOZE_DANCE_ACHIEVEMENT:
isOozeDanceEligible = data ? true : false;
break;
case DATA_NAUSEA_ACHIEVEMENT:
isNauseaEligible = data ? true : false;
break;
case DATA_ORB_WHISPERER_ACHIEVEMENT:
isOrbWhispererEligible = data ? true : false;
break;
case DATA_SINDRAGOSA_FROSTWYRMS:
if (data > 1)
frostwyrms = data;
else if (data == 1)
++frostwyrms;
else if (!data && !--frostwyrms && GetBossState(DATA_SINDRAGOSA) != DONE)
{
instance->LoadGrid(SindragosaSpawnPos.GetPositionX(), SindragosaSpawnPos.GetPositionY());
if (Creature* boss = instance->SummonCreature(NPC_SINDRAGOSA, SindragosaSpawnPos))
{
boss->setActive(true);
boss->AI()->DoAction(ACTION_START_FROSTWYRM);
}
}
break;
case DATA_SPINESTALKER:
if (data > 1)
spinestalkerTrash = data;
else if (data == 1)
++spinestalkerTrash;
else if (!data && !--spinestalkerTrash)
if (Creature* spinestalk = instance->GetCreature(spinestalker))
spinestalk->AI()->DoAction(ACTION_START_FROSTWYRM);
break;
case DATA_RIMEFANG:
if (data > 1)
rimefangTrash = data;
else if (data == 1)
++rimefangTrash;
else if (!data && !--rimefangTrash)
if (Creature* rime = instance->GetCreature(rimefang))
rime->AI()->DoAction(ACTION_START_FROSTWYRM);
break;
case DATA_COLDFLAME_JETS:
coldflameJetsState = data;
if (coldflameJetsState == DONE)
{
SaveToDB();
for (std::set<uint64>::iterator itr = coldflameJets.begin(); itr != coldflameJets.end(); ++itr)
if (Creature* trap = instance->GetCreature(*itr))
trap->AI()->DoAction(ACTION_STOP_TRAPS);
}
break;
default:
break;
}
}
bool CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* /*source*/, Unit const* /*target*/, uint32 /*miscvalue1*/)
{
switch (criteria_id)
{
case CRITERIA_BONED_10N:
case CRITERIA_BONED_25N:
case CRITERIA_BONED_10H:
case CRITERIA_BONED_25H:
return isBonedEligible;
case CRITERIA_DANCES_WITH_OOZES_10N:
case CRITERIA_DANCES_WITH_OOZES_25N:
case CRITERIA_DANCES_WITH_OOZES_10H:
case CRITERIA_DANCES_WITH_OOZES_25H:
return isOozeDanceEligible;
case CRITERIA_NAUSEA_10N:
case CRITERIA_NAUSEA_25N:
case CRITERIA_NAUSEA_10H:
case CRITERIA_NAUSEA_25H:
return isNauseaEligible;
case CRITERIA_ORB_WHISPERER_10N:
case CRITERIA_ORB_WHISPERER_25N:
case CRITERIA_ORB_WHISPERER_10H:
case CRITERIA_ORB_WHISPERER_25H:
return isOrbWhispererEligible;
// Only one criteria for both modes, need to do it like this
case CRITERIA_KILL_LANA_THEL_10M:
case CRITERIA_ONCE_BITTEN_TWICE_SHY_10N:
case CRITERIA_ONCE_BITTEN_TWICE_SHY_10V:
return CAST_INST(InstanceMap, instance)->GetMaxPlayers() == 10;
case CRITERIA_KILL_LANA_THEL_25M:
case CRITERIA_ONCE_BITTEN_TWICE_SHY_25N:
case CRITERIA_ONCE_BITTEN_TWICE_SHY_25V:
return CAST_INST(InstanceMap, instance)->GetMaxPlayers() == 25;
default:
break;
}
return false;
}
bool CheckRequiredBosses(uint32 bossId, Player const* player = NULL) const
{
if (player && player->isGameMaster())
return true;
switch (bossId)
{
case DATA_THE_LICH_KING:
if (!CheckPlagueworks(bossId))
return false;
if (!CheckCrimsonHalls(bossId))
return false;
if (!CheckFrostwingHalls(bossId))
return false;
break;
case DATA_SINDRAGOSA:
case DATA_VALITHRIA_DREAMWALKER:
if (!CheckFrostwingHalls(bossId))
return false;
break;
case DATA_BLOOD_QUEEN_LANA_THEL:
case DATA_BLOOD_PRINCE_COUNCIL:
if (!CheckCrimsonHalls(bossId))
return false;
break;
case DATA_FESTERGUT:
case DATA_ROTFACE:
case DATA_PROFESSOR_PUTRICIDE:
if (!CheckPlagueworks(bossId))
return false;
break;
default:
break;
}
if (!CheckLowerSpire(bossId))
return false;
return true;
}
bool CheckPlagueworks(uint32 bossId) const
{
switch (bossId)
{
case DATA_THE_LICH_KING:
if (GetBossState(DATA_PROFESSOR_PUTRICIDE) != DONE)
return false;
// no break
case DATA_PROFESSOR_PUTRICIDE:
if (GetBossState(DATA_FESTERGUT) != DONE || GetBossState(DATA_ROTFACE) != DONE)
return false;
break;
default:
break;
}
return true;
}
bool CheckCrimsonHalls(uint32 bossId) const
{
switch (bossId)
{
case DATA_THE_LICH_KING:
if (GetBossState(DATA_BLOOD_QUEEN_LANA_THEL) != DONE)
return false;
// no break
case DATA_BLOOD_QUEEN_LANA_THEL:
if (GetBossState(DATA_BLOOD_PRINCE_COUNCIL) != DONE)
return false;
break;
default:
break;
}
return true;
}
bool CheckFrostwingHalls(uint32 bossId) const
{
switch (bossId)
{
case DATA_THE_LICH_KING:
if (GetBossState(DATA_SINDRAGOSA) != DONE)
return false;
// no break
case DATA_SINDRAGOSA:
//if (GetBossState(DATA_VALITHRIA_DREAMWALKER) != DONE)
// return false;
break;
default:
break;
}
return true;
}
bool CheckLowerSpire(uint32 bossId) const
{
switch (bossId)
{
case DATA_THE_LICH_KING:
case DATA_SINDRAGOSA:
case DATA_BLOOD_QUEEN_LANA_THEL:
case DATA_PROFESSOR_PUTRICIDE:
case DATA_VALITHRIA_DREAMWALKER:
case DATA_BLOOD_PRINCE_COUNCIL:
case DATA_ROTFACE:
case DATA_FESTERGUT:
if (GetBossState(DATA_DEATHBRINGER_SAURFANG) != DONE)
return false;
// no break
case DATA_DEATHBRINGER_SAURFANG:
if (GetBossState(DATA_GUNSHIP_EVENT) != DONE)
return false;
// no break
case DATA_GUNSHIP_EVENT:
if (GetBossState(DATA_LADY_DEATHWHISPER) != DONE)
return false;
// no break
case DATA_LADY_DEATHWHISPER:
if (GetBossState(DATA_LORD_MARROWGAR) != DONE)
return false;
// no break
case DATA_LORD_MARROWGAR:
default:
break;
}
return true;
}
std::string GetSaveData()
{
OUT_SAVE_INST_DATA;
std::ostringstream saveStream;
saveStream << "I C " << GetBossSaveData() << uint32(coldflameJetsState);
OUT_SAVE_INST_DATA_COMPLETE;
return saveStream.str();
}
void Load(const char* str)
{
if (!str)
{
OUT_LOAD_INST_DATA_FAIL;
return;
}
OUT_LOAD_INST_DATA(str);
char dataHead1, dataHead2;
std::istringstream loadStream(str);
loadStream >> dataHead1 >> dataHead2;
if (dataHead1 == 'I' && dataHead2 == 'C')
{
for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)
{
uint32 tmpState;
loadStream >> tmpState;
if (tmpState == IN_PROGRESS || tmpState > SPECIAL)
tmpState = NOT_STARTED;
SetBossState(i, EncounterState(tmpState));
}
uint32 jets = 0;
loadStream >> jets;
coldflameJetsState = jets ? DONE : NOT_STARTED;
} else OUT_LOAD_INST_DATA_FAIL;
OUT_LOAD_INST_DATA_COMPLETE;
}
private:
uint64 ladyDeathwisperElevator;
uint64 deathbringerSaurfang;
uint64 saurfangDoor;
uint64 saurfangEventNPC; // Muradin Bronzebeard or High Overlord Saurfang
uint64 deathbringersCache;
uint64 saurfangTeleport;
uint64 putricidePipes[2];
uint64 putricideGates[2];
uint64 putricideCollision;
uint64 festergut;
uint64 rotface;
uint64 professorPutricide;
uint64 putricideTable;
uint64 bloodCouncil[3];
uint64 bloodCouncilController;
uint64 bloodQueenLanaThel;
uint64 sindragosa;
uint64 spinestalker;
uint64 rimefang;
std::set<uint64> coldflameJets;
uint32 teamInInstance;
uint8 coldflameJetsState;
uint8 frostwyrms;
uint8 spinestalkerTrash;
uint8 rimefangTrash;
bool isBonedEligible;
bool isOozeDanceEligible;
bool isNauseaEligible;
bool isOrbWhispererEligible;
};
InstanceScript* GetInstanceScript(InstanceMap* map) const
{
return new instance_icecrown_citadel_InstanceMapScript(map);
}
};
void AddSC_instance_icecrown_citadel()
{
new instance_icecrown_citadel();
} | gpl-3.0 |
saumiko/ProjectArchiveAnalyzer | Project300/src/main/java/com/great/cms/db/dao/GenericDao.java | 667 | package com.great.cms.db.dao;
import java.io.Serializable;
import java.util.List;
import com.great.cms.db.entity.DomainObject;
/**
* @author sknabil
* @version 1.0.0
*
*/
public interface GenericDao <T extends DomainObject, ID extends Serializable> {
public T findById(ID id) throws RuntimeException;
public List<T> findAll() throws RuntimeException;
public void save(T object) throws RuntimeException;
public void update(T object)throws RuntimeException;
public void updateNative ( String sql );
public void delete(T object) throws RuntimeException;
public void deleteById(ID id) throws RuntimeException;
}
| gpl-3.0 |
grimoirelab/sortinghat | sortinghat/exceptions.py | 3478 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2014-2018 Bitergia
#
# 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/>.
#
# Authors:
# Santiago Dueñas <sduenas@bitergia.com>
#
import logging
CODE_BASE_ERROR = 1
CODE_ALREADY_EXISTS_ERROR = 2
CODE_BAD_FILE_FORMAT_ERROR = 3
CODE_DATABASE_ERROR = 4
CODE_INVALID_DATE_ERROR = 5
CODE_INVALID_FORMAT_ERROR = 6
CODE_LOAD_ERROR = 7
CODE_MATCHER_NOT_SUPPORTED_ERROR = 8
CODE_NOT_FOUND_ERROR = 9
CODE_VALUE_ERROR = 10
CODE_DATABASE_EXISTS = 11
logger = logging.getLogger(__name__)
class BaseError(Exception):
"""Base class error.
Derived classes can overwrite error message declaring 'message' property.
"""
message = "Unknown error"
code = CODE_BASE_ERROR
def __init__(self, **kwargs):
super(BaseError, self).__init__(kwargs)
self.msg = self.message % kwargs
def __str__(self):
return self.msg
def __int__(self):
return self.code
class AlreadyExistsError(BaseError):
"""Exception raised when an entity already exists in the registry"""
message = "%(entity)s '%(eid)s' already exists in the registry"
code = CODE_ALREADY_EXISTS_ERROR
def __init__(self, **kwargs):
self.entity = kwargs['entity']
self.eid = kwargs['eid']
super(AlreadyExistsError, self).__init__(**kwargs)
class BadFileFormatError(BaseError):
"""Exception raised when an input file does not have the expected format"""
message = "%(cause)s"
code = CODE_BAD_FILE_FORMAT_ERROR
class DatabaseError(BaseError):
"""Exception raised when a database error occurs"""
message = "%(error)s (err: %(code)s)"
code = CODE_DATABASE_EXISTS
class DatabaseExists(BaseError):
"""Exception raised when trying to create a database and it already exists"""
message = "%(error)s (err: %(code)s)"
code = CODE_DATABASE_EXISTS
class InvalidDateError(BaseError):
"""Exception raised when a date is invalid"""
message = "%(date)s is not a valid date"
code = CODE_INVALID_DATE_ERROR
class InvalidFormatError(BaseError):
"""Exception raised when a format is invalid"""
message = "%(cause)s"
code = CODE_INVALID_FORMAT_ERROR
class LoadError(BaseError):
"""Exception raised when an error occurs loading data"""
message = "%(cause)s"
code = CODE_LOAD_ERROR
class MatcherNotSupportedError(BaseError):
"""Exception raised when an identity matcher is not supported"""
message = "%(matcher)s identity matcher is not supported"
code = CODE_MATCHER_NOT_SUPPORTED_ERROR
class NotFoundError(BaseError):
"""Exception raised when an entity is not found in the registry"""
message = "%(entity)s not found in the registry"
code = CODE_NOT_FOUND_ERROR
class InvalidValueError(ValueError):
"""Exception InvalidValueError is a normal ValueError with code support"""
code = CODE_VALUE_ERROR
| gpl-3.0 |
Marlinski/Rumble | app/src/main/java/org/disrupted/rumble/userinterface/fragments/FragmentContactList.java | 4552 | /*
* Copyright (C) 2014 Lucien Loiseau
* This file is part of Rumble.
* Rumble 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.
*
* Rumble 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 Rumble. If not, see <http://www.gnu.org/licenses/>.
*/
package org.disrupted.rumble.userinterface.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import org.disrupted.rumble.R;
import org.disrupted.rumble.database.ContactDatabase;
import org.disrupted.rumble.database.DatabaseExecutor;
import org.disrupted.rumble.database.DatabaseFactory;
import org.disrupted.rumble.database.events.ContactDeletedEvent;
import org.disrupted.rumble.database.events.ContactInsertedEvent;
import org.disrupted.rumble.database.objects.Contact;
import org.disrupted.rumble.userinterface.adapter.ContactRecyclerAdapter;
import java.util.ArrayList;
import de.greenrobot.event.EventBus;
/**
* @author Lucien Loiseau
*/
public class FragmentContactList extends Fragment {
public static final String TAG = "FragmentContactList";
private View mView;
private RecyclerView mRecyclerView;
private ContactRecyclerAdapter contactRecyclerAdapter;
private String filter_gid = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
Bundle args = getArguments();
if(args != null) {
this.filter_gid = args.getString("GroupID");
}
mView = inflater.inflate(R.layout.fragment_contact_list, container, false);
mRecyclerView = (RecyclerView) mView.findViewById(R.id.contact_list);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
contactRecyclerAdapter = new ContactRecyclerAdapter(getActivity());
mRecyclerView.setAdapter(contactRecyclerAdapter);
EventBus.getDefault().register(this);
getContactList();
return mView;
}
@Override
public void onDestroy() {
if(EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this);
super.onDestroy();
}
public void getContactList() {
ContactDatabase.ContactQueryOption options = new ContactDatabase.ContactQueryOption();
options.answerLimit = 20;
options.order_by = ContactDatabase.ContactQueryOption.ORDER_BY.LAST_TIME_MET;
if(filter_gid != null) {
options.filterFlags |= ContactDatabase.ContactQueryOption.FILTER_GROUP;
options.gid = filter_gid;
} else {
options.filterFlags |= ContactDatabase.ContactQueryOption.FILTER_LOCAL;
options.local = false;
}
DatabaseFactory.getContactDatabase(getActivity())
.getContacts(options, onContactsLoaded);
}
private DatabaseExecutor.ReadableQueryCallback onContactsLoaded = new DatabaseExecutor.ReadableQueryCallback() {
@Override
public void onReadableQueryFinished(final Object result) {
if(getActivity() == null)
return;
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayList<Contact> answer = (ArrayList<Contact>)(result);
contactRecyclerAdapter.swap(answer);
}
}
);
}
};
public void onEvent(ContactInsertedEvent event) {
getContactList();
}
public void onEvent(ContactDeletedEvent event) {
getContactList();
}
}
| gpl-3.0 |
Harkame/My_lib | src/TestJsoup.java | 1633 | import java.io.IOException;
import java.util.Scanner;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class TestJsoup
{
public static void main(String[] Args) throws IOException
{
System.out.print("Title : ");
Scanner keyboardScanner = new Scanner(System.in);
String title = keyboardScanner.nextLine();
System.out.println(title);
String animeVFSearch = "http://www.anime-vf.fr/index.php?route=product/search&search=";
String search = animeVFSearch + title;
Document doc = Jsoup.connect(search).get();
Elements links = doc.select("a[href]");
Elements media = doc.select("[src]");
Elements imports = doc.select("link[href]");
print("\nMedia: (%d)", media.size());
for(Element src : media)
{
if(src.tagName().equals("img"))
print(" * %s: <%s> %sx%s (%s)", src.tagName(), src.attr("abs:src"), src.attr("width"),
src.attr("height"), trim(src.attr("alt"), 20));
else
print(" * %s: <%s>", src.tagName(), src.attr("abs:src"));
}
print("\nImports: (%d)", imports.size());
for(Element link : imports)
{
print(" * %s <%s> (%s)", link.tagName(), link.attr("abs:href"), link.attr("rel"));
}
print("\nLinks: (%d)", links.size());
for(Element link : links)
{
print(" * a: <%s> (%s)", link.attr("abs:href"), trim(link.text(), 35));
}
}
private static void print(String msg, Object... args)
{
System.out.println(String.format(msg, args));
}
private static String trim(String s, int width)
{
if(s.length() > width)
return s.substring(0, width - 1) + ".";
else
return s;
}
}
| gpl-3.0 |
samszo/open-edition | plugins-dist/porte_plume/lang/barreoutils_it.php | 5665 | <?php
// This is a SPIP language file -- Ceci est un fichier langue de SPIP
// extrait automatiquement de http://trad.spip.net/tradlang_module/barreoutils?lang_cible=it
// ** ne pas modifier le fichier **
if (!defined('_ECRIRE_INC_VERSION')) {
return;
}
$GLOBALS[$GLOBALS['idx_lang']] = array(
// B
'barre_a_accent_grave' => 'Inserisci una A con accento grave maiuscolo',
'barre_adresse' => 'Indirizzo',
'barre_aide' => 'Utilizza le scorciatoie tipografiche per arrichhire la tua impaginazione',
'barre_alignerdroite' => '[/Allinea a destra/] il paragrafo',
'barre_ancres' => 'Gestione delle ancore',
'barre_barre' => 'Barra il testo',
'barre_bulle' => 'Tooltip',
'barre_c_cedille_maj' => 'Inserisci una C con cediglia maiuscola',
'barre_cadre' => 'Metti dentro una <cadre>zona di inserimento del testo</cadre>',
'barre_caracteres' => 'Caratteri speciali',
'barre_centrer' => '[|Centra|] il paragrafo',
'barre_chercher' => 'Cerca e sostituisci',
'barre_clean' => 'Elimina dal codice tutti i tag HTML',
'barre_code' => 'Impagina un <code>codice informatico</code>',
'barre_desindenter' => 'Elimina l’indentazione della linea',
'barre_e_accent_aigu' => 'Inserisci una E con accento acuto maiuscola',
'barre_e_accent_grave' => 'Inserisci una E maiuscola con accento grave',
'barre_ea' => 'Inserisci una E nella A',
'barre_ea_maj' => 'Inserisci una E nella A maiuscola',
'barre_encadrer' => '[(Riquadra)] il paragrafo',
'barre_eo' => 'Inserisci una E con legatura alla O minuscola',
'barre_eo_maj' => 'Inserisci una E con legatura alla O maiuscola',
'barre_euro' => 'Inserisci il simbolo €',
'barre_exposant' => 'Metti il testo in <sup>esponente</sup>',
'barre_formatages_speciaux' => 'Formattazioni speciali',
'barre_galerie' => 'Apri la galleria',
'barre_gestion_anc_bulle' => 'Tooltip ancora',
'barre_gestion_anc_caption' => 'Gestione delle ancore',
'barre_gestion_anc_cible' => 'Destinazione ancora',
'barre_gestion_anc_inserer' => 'Trasforma in ancora',
'barre_gestion_anc_nom' => 'Nome dell’ancora',
'barre_gestion_anc_pointer' => 'Punta verso un’ancora',
'barre_gestion_caption' => 'Didascalia e riassunto',
'barre_gestion_colonne' => 'Num colonne',
'barre_gestion_cr_casse' => 'Rispetta le maiuscole/minuscole',
'barre_gestion_cr_changercasse' => 'Cambia maiuscole/minuscole',
'barre_gestion_cr_changercassemajuscules' => 'Passa in maiuscole',
'barre_gestion_cr_changercasseminuscules' => 'Passa in minuscole',
'barre_gestion_cr_chercher' => 'Cerca',
'barre_gestion_cr_entier' => 'Parola intera',
'barre_gestion_cr_remplacer' => 'Sostituisci',
'barre_gestion_cr_tout' => 'Sostituisci tutto',
'barre_gestion_entete' => 'Intestazione',
'barre_gestion_ligne' => 'Num righe',
'barre_gestion_taille' => 'DImensione fissa',
'barre_glossaire' => 'Voce di [?glossario] (Wikipedia)',
'barre_gras' => 'Converti in {{grassetto}}',
'barre_guillemets' => 'Racchiudi tra « virgolette »',
'barre_guillemets_simples' => 'Racchiudi tra “virgolette di secondo livello”',
'barre_indenter' => 'Indenta la lista',
'barre_inserer_cadre' => 'Inserire un codice pre formattato (struttura)',
'barre_inserer_caracteres' => 'Inserisci dei caratteri speciali',
'barre_inserer_code' => 'Inserire del codice applicativo (code)',
'barre_intertitre' => 'Trasforma in {{{titolo}}}',
'barre_italic' => 'Converti in {corsivo}',
'barre_langue' => 'Acronimo lingua',
'barre_lien' => 'Trasforma in [link ipertestuale->http://...]',
'barre_lien_externe' => 'Link esterno',
'barre_lien_input' => 'Indica l’indirizzo del tuo link (puoi indicare un indirizzo internet sotto forma di http://www.miosito.com, un indirizzo di posta elettronica, o semplicemente indicare il numero di un articolo di questo sito).',
'barre_liste_ol' => 'Converti in lista numerata',
'barre_liste_ul' => 'Converti in lista',
'barre_lorem_ipsum' => 'Inserisci un paragrafo di prova (lorem ipsum)',
'barre_lorem_ipsum_3' => 'Inserisci 3 paragrafi di prova (lorem ipsum)',
'barre_miseenevidence' => 'Metti il testo in [*evidenza*]',
'barre_note' => 'Trasforma in [[nota a piè pagina]]',
'barre_paragraphe' => 'Crea un paragrafo',
'barre_petitescapitales' => 'metti il testo in <sc>maiuscoletto</sc>',
'barre_poesie' => 'Impagina come una <poesie>poesia</poesie>',
'barre_preview' => 'Modalità anteprima',
'barre_quote' => '<quote>Cita un messaggio</quote>',
'barre_stats' => 'Mostra le statistiche del testo',
'barre_tableau' => 'Inserisci/modifica una tabella (selezionarla prima)',
// C
'config_info_enregistree' => 'Configurazione salvata',
// E
'editer' => 'Modifica',
'explication_barre_outils_public' => 'Gli script CSS e Javascript delle barre di utilità
(estensione Porte Plume) vengono caricate nello spazio pubblico
e consentono di utilizzare queste barre sui moduli dei forum,
i pennarelli pubblici o per altri plugin, se le loro rispettive configurazioni
lo permettono.',
'explication_barre_outils_public_2' => 'Puoi scegliere di non caricare questi script al fine di alleggerire le pagine pubbliche.
In questo caso, qualunque sia la configurazione dei forum, pennarelli o plugin, nessuna barra di Porte Plume potrà essere inserita automaticamente nello spazio pubblico.',
// I
'info_barre_outils_public' => 'Barra ti testo pubblica',
'info_porte_plume_titre' => 'Configura le barre di testo',
// L
'label_barre_outils_public_non' => 'Non caricare gli script della barra di testo sullo spazio pubblico',
'label_barre_outils_public_oui' => 'Caricare gli script della barra di testo sullo spazio pubblico',
// V
'voir' => 'Vedi'
);
?>
| gpl-3.0 |
metalab25/OpenSID | donjo-app/controllers/Setting.php | 1361 | <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Setting extends CI_Controller {
public function __construct()
{
parent::__construct();
session_start();
$this->load->model('user_model');
$grup = $this->user_model->sesi_grup($_SESSION['sesi']);
if ($grup != 1)
{
if (empty($grup))
$_SESSION['request_uri'] = $_SERVER['REQUEST_URI'];
else
unset($_SESSION['request_uri']);
redirect('siteman');
}
$this->load->model('setting_model');
$this->load->model('header_model');
$this->load->model('theme_model');
$this->modul_ini = 11;
}
public function index()
{
$nav['act'] = 11;
$nav['act_sub'] = 43;
$header = $this->header_model->get_data();
$data['list_tema'] = $this->theme_model->list_all();
$this->setting_model->load_options();
$this->load->view('header', $header);
$this->load->view('nav', $nav);
$this->load->view('setting/setting_form', $data);
$this->load->view('footer');
}
public function update()
{
$this->setting_model->update($this->input->post());
redirect('setting');
}
public function info_sistem()
{
$nav['act'] = 11;
$nav['act_sub'] = 46;
$header = $this->header_model->get_data();
$this->load->view('header', $header);
$this->load->view('nav', $nav);
$this->load->view('setting/info_php');
$this->load->view('footer');
}
}
| gpl-3.0 |
indianopt/todb | test_mysql.php | 1215 | <HTML>
<HEAD>
<TITLE>Test wizard page 3: MySQL/PHP installation</TITLE>
</HEAD>
<BODY>
<h1>Testing MySQL/PHP installation:</h1>
<p>Note: TODB uses the PHP MySQL libraries, <i>not</i> the MySQLi libraries.</p>
<p>If your MySQL installation is working correctly with PHP, you should see current date and the decimal (floating point) value of PI displayed below:</p>
<?php
if (function_exists('mysql_query'))
{
// get DB connection apparatus:
global $dbread;
require('config/db.inc');
// connect:
open_db_read();
// test query:
$tq = 'select pi(), CURDATE();';
// run the query:
$res = mysql_query($tq, $dbread);
while ($row = mysql_fetch_array($res))
{
echo "<p>PI is $row[0] and the current date is $row[1].</p>";
}
mysql_free_result($res);
}
else
{
echo '<p>MySQL PHP module not installed! This is essential for TODB operation.</p>';
}
?>
<P><A href="test_html.html">Home</a> |Next: <A href="test_tables.php">Test database setup (tables).</a></p>
</BODY>
</HTML>
| gpl-3.0 |
geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtmultimedia/src/multimediawidgets/qgraphicsvideoitem.cpp | 11187 | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qgraphicsvideoitem.h"
#include "qpaintervideosurface_p.h"
#include <qmediaobject.h>
#include <qmediaservice.h>
#include <qvideorenderercontrol.h>
#include <qvideosurfaceformat.h>
#include <QtCore/qcoreevent.h>
#include <QtCore/qpointer.h>
#if QT_CONFIG(opengl)
#include <QtOpenGL/qgl.h>
#endif
QT_BEGIN_NAMESPACE
class QGraphicsVideoItemPrivate
{
public:
QGraphicsVideoItemPrivate()
: q_ptr(0)
, surface(0)
, mediaObject(0)
, service(0)
, rendererControl(0)
, aspectRatioMode(Qt::KeepAspectRatio)
, updatePaintDevice(true)
, rect(0.0, 0.0, 320, 240)
{
}
QGraphicsVideoItem *q_ptr;
QPainterVideoSurface *surface;
QPointer<QMediaObject> mediaObject;
QMediaService *service;
QVideoRendererControl *rendererControl;
Qt::AspectRatioMode aspectRatioMode;
bool updatePaintDevice;
QRectF rect;
QRectF boundingRect;
QRectF sourceRect;
QSizeF nativeSize;
void clearService();
void updateRects();
void _q_present();
void _q_formatChanged(const QVideoSurfaceFormat &format);
void _q_updateNativeSize();
void _q_serviceDestroyed();
};
void QGraphicsVideoItemPrivate::clearService()
{
if (rendererControl) {
surface->stop();
rendererControl->setSurface(0);
service->releaseControl(rendererControl);
rendererControl = 0;
}
if (service) {
QObject::disconnect(service, SIGNAL(destroyed()), q_ptr, SLOT(_q_serviceDestroyed()));
service = 0;
}
}
void QGraphicsVideoItemPrivate::updateRects()
{
q_ptr->prepareGeometryChange();
if (nativeSize.isEmpty()) {
//this is necessary for item to receive the
//first paint event and configure video surface.
boundingRect = rect;
} else if (aspectRatioMode == Qt::IgnoreAspectRatio) {
boundingRect = rect;
sourceRect = QRectF(0, 0, 1, 1);
} else if (aspectRatioMode == Qt::KeepAspectRatio) {
QSizeF size = nativeSize;
size.scale(rect.size(), Qt::KeepAspectRatio);
boundingRect = QRectF(0, 0, size.width(), size.height());
boundingRect.moveCenter(rect.center());
sourceRect = QRectF(0, 0, 1, 1);
} else if (aspectRatioMode == Qt::KeepAspectRatioByExpanding) {
boundingRect = rect;
QSizeF size = rect.size();
size.scale(nativeSize, Qt::KeepAspectRatio);
sourceRect = QRectF(
0, 0, size.width() / nativeSize.width(), size.height() / nativeSize.height());
sourceRect.moveCenter(QPointF(0.5, 0.5));
}
}
void QGraphicsVideoItemPrivate::_q_present()
{
if (q_ptr->isObscured()) {
q_ptr->update(boundingRect);
surface->setReady(true);
} else {
q_ptr->update(boundingRect);
}
}
void QGraphicsVideoItemPrivate::_q_updateNativeSize()
{
const QSize &size = surface->surfaceFormat().sizeHint();
if (nativeSize != size) {
nativeSize = size;
updateRects();
emit q_ptr->nativeSizeChanged(nativeSize);
}
}
void QGraphicsVideoItemPrivate::_q_serviceDestroyed()
{
rendererControl = 0;
service = 0;
surface->stop();
}
/*!
\class QGraphicsVideoItem
\brief The QGraphicsVideoItem class provides a graphics item which display video produced by a QMediaObject.
\inmodule QtMultimediaWidgets
\ingroup multimedia
Attaching a QGraphicsVideoItem to a QMediaObject allows it to display
the video or image output of that media object. A QGraphicsVideoItem
is attached to a media object by passing a pointer to the QMediaObject
to the setMediaObject() function.
\snippet multimedia-snippets/video.cpp Video graphics item
\b {Note}: Only a single display output can be attached to a media
object at one time.
\sa QMediaObject, QMediaPlayer, QVideoWidget
*/
/*!
Constructs a graphics item that displays video.
The \a parent is passed to QGraphicsItem.
*/
QGraphicsVideoItem::QGraphicsVideoItem(QGraphicsItem *parent)
: QGraphicsObject(parent)
, d_ptr(new QGraphicsVideoItemPrivate)
{
d_ptr->q_ptr = this;
d_ptr->surface = new QPainterVideoSurface;
qRegisterMetaType<QVideoSurfaceFormat>();
connect(d_ptr->surface, SIGNAL(frameChanged()), this, SLOT(_q_present()));
connect(d_ptr->surface, SIGNAL(surfaceFormatChanged(QVideoSurfaceFormat)),
this, SLOT(_q_updateNativeSize()), Qt::QueuedConnection);
}
/*!
Destroys a video graphics item.
*/
QGraphicsVideoItem::~QGraphicsVideoItem()
{
if (d_ptr->rendererControl) {
d_ptr->rendererControl->setSurface(0);
d_ptr->service->releaseControl(d_ptr->rendererControl);
}
delete d_ptr->surface;
delete d_ptr;
}
/*!
\property QGraphicsVideoItem::mediaObject
\brief the media object which provides the video displayed by a graphics
item.
*/
QMediaObject *QGraphicsVideoItem::mediaObject() const
{
return d_func()->mediaObject;
}
/*!
\internal
*/
bool QGraphicsVideoItem::setMediaObject(QMediaObject *object)
{
Q_D(QGraphicsVideoItem);
if (object == d->mediaObject)
return true;
d->clearService();
d->mediaObject = object;
if (d->mediaObject) {
d->service = d->mediaObject->service();
if (d->service) {
QMediaControl *control = d->service->requestControl(QVideoRendererControl_iid);
if (control) {
d->rendererControl = qobject_cast<QVideoRendererControl *>(control);
if (d->rendererControl) {
//don't set the surface untill the item is painted
//at least once and the surface is configured
if (!d->updatePaintDevice)
d->rendererControl->setSurface(d->surface);
else
update(boundingRect());
connect(d->service, SIGNAL(destroyed()), this, SLOT(_q_serviceDestroyed()));
return true;
}
if (control)
d->service->releaseControl(control);
}
}
}
d->mediaObject = 0;
return false;
}
/*!
\property QGraphicsVideoItem::aspectRatioMode
\brief how a video is scaled to fit the graphics item's size.
*/
Qt::AspectRatioMode QGraphicsVideoItem::aspectRatioMode() const
{
return d_func()->aspectRatioMode;
}
void QGraphicsVideoItem::setAspectRatioMode(Qt::AspectRatioMode mode)
{
Q_D(QGraphicsVideoItem);
d->aspectRatioMode = mode;
d->updateRects();
}
/*!
\property QGraphicsVideoItem::offset
\brief the video item's offset.
QGraphicsVideoItem will draw video using the offset for its top left
corner.
*/
QPointF QGraphicsVideoItem::offset() const
{
return d_func()->rect.topLeft();
}
void QGraphicsVideoItem::setOffset(const QPointF &offset)
{
Q_D(QGraphicsVideoItem);
d->rect.moveTo(offset);
d->updateRects();
}
/*!
\property QGraphicsVideoItem::size
\brief the video item's size.
QGraphicsVideoItem will draw video scaled to fit size according to its
fillMode.
*/
QSizeF QGraphicsVideoItem::size() const
{
return d_func()->rect.size();
}
void QGraphicsVideoItem::setSize(const QSizeF &size)
{
Q_D(QGraphicsVideoItem);
d->rect.setSize(size.isValid() ? size : QSizeF(0, 0));
d->updateRects();
}
/*!
\property QGraphicsVideoItem::nativeSize
\brief the native size of the video.
*/
QSizeF QGraphicsVideoItem::nativeSize() const
{
return d_func()->nativeSize;
}
/*!
\fn QGraphicsVideoItem::nativeSizeChanged(const QSizeF &size)
Signals that the native \a size of the video has changed.
*/
/*!
\reimp
*/
QRectF QGraphicsVideoItem::boundingRect() const
{
return d_func()->boundingRect;
}
/*!
\reimp
*/
void QGraphicsVideoItem::paint(
QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_D(QGraphicsVideoItem);
Q_UNUSED(option);
Q_UNUSED(widget);
if (d->surface && d->updatePaintDevice) {
d->updatePaintDevice = false;
#if QT_CONFIG(opengl)
if (widget)
connect(widget, SIGNAL(destroyed()), d->surface, SLOT(viewportDestroyed()));
d->surface->setGLContext(const_cast<QGLContext *>(QGLContext::currentContext()));
if (d->surface->supportedShaderTypes() & QPainterVideoSurface::GlslShader) {
d->surface->setShaderType(QPainterVideoSurface::GlslShader);
} else {
d->surface->setShaderType(QPainterVideoSurface::FragmentProgramShader);
}
#endif
if (d->rendererControl && d->rendererControl->surface() != d->surface)
d->rendererControl->setSurface(d->surface);
}
if (d->surface && d->surface->isActive()) {
d->surface->paint(painter, d->boundingRect, d->sourceRect);
d->surface->setReady(true);
}
}
/*!
\reimp
\internal
*/
QVariant QGraphicsVideoItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
return QGraphicsItem::itemChange(change, value);
}
/*!
\internal
*/
void QGraphicsVideoItem::timerEvent(QTimerEvent *event)
{
QGraphicsObject::timerEvent(event);
}
#include "moc_qgraphicsvideoitem.cpp"
QT_END_NAMESPACE
| gpl-3.0 |
krishardy/argentum-firmware | src/argentum/argentum.cpp | 1256 | /*
Argentum Firmware
Copyright (C) 2013 Isabella Stevens
Copyright (C) 2014 Michael Shiel
Copyright (C) 2015 Trent Waddington
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 "argentum.h"
// Should be x axis
Stepper a_motor(STEPPER_A_STEP_PIN, STEPPER_A_DIR_PIN, STEPPER_A_ENABLE_PIN);
// Should be y axis
Stepper b_motor(STEPPER_B_STEP_PIN, STEPPER_B_DIR_PIN, STEPPER_B_ENABLE_PIN);
Axis x_axis(Axis::X, &a_motor, &limit_x_positive, &limit_x_negative);
Axis y_axis(Axis::Y, &b_motor, &limit_y_positive, &limit_y_negative);
SerialCommand serial_command;
Rollers rollers;
SdFat sd;
long x_size = 0;
long y_size = 0;
| gpl-3.0 |
masneyb/flickrdownload | dev/src/java/org/gftp/FlickrDownload/IOUtils.java | 5116 | /*
FlickrDownload - Copyright(C) 2010 Brian Masney <masneyb@onstation.org>.
If you have any questions, comments, or suggestions about this program, please
feel free to email them to me. You can always find out the latest news about
FlickrDownload from my website at http://www.onstation.org/flickrdownload/
FlickrDownload comes with ABSOLUTELY NO WARRANTY; for details, see the COPYING
file. This is free software, and you are welcome to redistribute it under
certain conditions; for details, see the COPYING file.
*/
package org.gftp.FlickrDownload;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Collection;
import javax.xml.ws.http.HTTPException;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
public class IOUtils {
public static void copy(InputStream istr, OutputStream ostr) throws IOException {
byte[] buffer = new byte[4096];
int n;
while ((n = istr.read(buffer)) != -1) {
ostr.write(buffer, 0, n);
}
}
public static String md5Sum(File file) {
InputStream istr = null;
try {
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
istr = new FileInputStream(file);
byte[] buffer = new byte[4096];
int n;
while ((n = istr.read(buffer)) != -1) {
digest.update(buffer, 0, n);
}
istr.close();
return new BigInteger(1, digest.digest()).toString(16);
}
catch (Exception e) {
Logger.getLogger(IOUtils.class).error(String.format("Could not get md5sum of %s: %s", file, e.getMessage()), e);
return "";
}
}
public static void copyToFileAndCloseStreams(InputStream istr, File destFile) throws IOException {
OutputStream ostr = null;
try {
ostr = new FileOutputStream(destFile);
IOUtils.copy(istr, ostr);
}
finally {
if (ostr != null)
ostr.close();
if (istr != null)
istr.close();
}
}
public static void downloadUrl(String url, File destFile) throws IOException, HTTPException {
File tmpFile = new File(destFile.getAbsoluteFile() + ".tmp");
Logger.getLogger(IOUtils.class).debug(String.format("Downloading URL %s to %s", url, tmpFile));
tmpFile.getParentFile().mkdirs();
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(url);
get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
int code = client.executeMethod(get);
if (code >= 200 && code < 300) {
copyToFileAndCloseStreams(get.getResponseBodyAsStream(), tmpFile);
tmpFile.renameTo(destFile);
}
else
Logger.getLogger(IOUtils.class).fatal("Got HTTP response code " + code + " when trying to download " + url);
}
private static String getRemoteFilename(String url) throws IOException, HTTPException {
HttpClient client = new HttpClient();
HeadMethod get = new HeadMethod(url);
get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
int code = client.executeMethod(get);
if (code >= 200 && code < 400) {
Header disposition = get.getResponseHeader("Content-Disposition");
if (disposition != null)
return disposition.getValue().replace("attachment; filename=", "");
}
Logger.getLogger(IOUtils.class).fatal("Got HTTP response code " + code + " when trying to download " + url + ". Returning null.");
return null;
}
public static String getVideoExtension(String url) throws IOException, HTTPException {
String filename = getRemoteFilename(url);
if (filename == null || filename.endsWith("."))
return "mp4"; // FIXME
return filename.substring(filename.lastIndexOf(".") + 1);
}
public static void findFilesThatDoNotBelong(File setDir, Collection<String> expectedFiles, String addExtensionToUnknownFiles) {
for (String file : setDir.list()) {
if (expectedFiles.contains(file))
continue;
if (StringUtils.isNotBlank(addExtensionToUnknownFiles) && !file.endsWith(addExtensionToUnknownFiles)) {
File oldFile = new File(setDir, file);
File newFile = new File(setDir, file + "." + addExtensionToUnknownFiles);
Logger.getLogger(IOUtils.class).warn(String.format("Unexpected file %s, adding %s extension.", new File(setDir, file).getAbsoluteFile(), addExtensionToUnknownFiles));
try {
oldFile.renameTo(newFile);
}
catch (Exception e) {
Logger.getLogger(IOUtils.class).warn(String.format("Error renaming %s to %s: %s", oldFile.getAbsolutePath(), newFile.getAbsolutePath(), e.getMessage()));
}
}
else {
Logger.getLogger(IOUtils.class).warn(String.format("Unexpected file %s.", new File(setDir, file).getAbsoluteFile()));
}
}
}
}
| gpl-3.0 |
PandoraPFA/LArContent | larpandoracontent/LArThreeDReco/LArCosmicRay/TwoViewCosmicRayRemovalTool.cc | 24754 | /**
* @file larpandoracontent/LArThreeDReco/LArTransverseTrackMatching/TwoViewCosmicRayRemovalTool.cc
*
* @brief Implementation of the two view cosmic removal tool class.
*
* $Log: $
*/
#include "larpandoracontent/LArThreeDReco/LArCosmicRay/TwoViewCosmicRayRemovalTool.h"
#include "Pandora/AlgorithmHeaders.h"
#include "larpandoracontent/LArHelpers/LArClusterHelper.h"
#include "larpandoracontent/LArHelpers/LArGeometryHelper.h"
#include "larpandoracontent/LArHelpers/LArPfoHelper.h"
#include "larpandoracontent/LArObjects/LArTwoDSlidingFitResult.h"
using namespace pandora;
namespace lar_content
{
TwoViewCosmicRayRemovalTool::TwoViewCosmicRayRemovalTool() :
m_minSeparation(2.f),
m_slidingFitWindow(10000),
m_distanceToLine(0.5f),
m_minContaminationLength(3.f),
m_maxDistanceToHit(1.f),
m_minRemnantClusterSize(3),
m_maxDistanceToTrack(2.f)
{
}
//------------------------------------------------------------------------------------------------------------------------------------------
bool TwoViewCosmicRayRemovalTool::Run(TwoViewDeltaRayMatchingAlgorithm *const pAlgorithm, MatrixType &overlapMatrix)
{
m_pParentAlgorithm = pAlgorithm;
if (PandoraContentApi::GetSettings(*m_pParentAlgorithm)->ShouldDisplayAlgorithmInfo())
std::cout << "----> Running Algorithm Tool: " << this->GetInstanceName() << ", " << this->GetType() << std::endl;
bool changesMade(false);
ClusterVector sortedKeyClusters;
overlapMatrix.GetSortedKeyClusters(sortedKeyClusters);
ClusterSet usedKeyClusters;
for (const Cluster *const pKeyCluster : sortedKeyClusters)
{
if (usedKeyClusters.count(pKeyCluster))
continue;
MatrixType::ElementList elementList;
overlapMatrix.GetConnectedElements(pKeyCluster, true, elementList);
for (const MatrixType::Element &element : elementList)
usedKeyClusters.insert(element.GetCluster1());
const bool changesMadeInIteration = this->RemoveCosmicRayHits(elementList);
changesMade = (changesMade ? changesMade : changesMadeInIteration);
}
return changesMade;
}
//------------------------------------------------------------------------------------------------------------------------------------------
bool TwoViewCosmicRayRemovalTool::RemoveCosmicRayHits(const MatrixType::ElementList &elementList) const
{
ClusterSet modifiedClusters, checkedClusters;
for (const MatrixType::Element &element : elementList)
{
for (const HitType hitType : m_pParentAlgorithm->GetHitTypeVector())
{
const Cluster *const pDeltaRayCluster(m_pParentAlgorithm->GetCluster(element, hitType));
if (checkedClusters.count(pDeltaRayCluster))
continue;
// ATTN: The underlying matrix will update during this loop, do not proceed if element has been modified
if ((modifiedClusters.count(element.GetCluster1())) || (modifiedClusters.count(element.GetCluster2())))
continue;
if (!this->PassElementChecks(element, hitType))
continue;
if (!this->IsContaminated(element, hitType))
continue;
if (!this->IsBestElement(element, hitType, elementList))
continue;
checkedClusters.insert(pDeltaRayCluster);
// Attempt to pull delta ray hits out of cluster
CaloHitList deltaRayHits;
this->CreateSeed(element, hitType, deltaRayHits);
if (deltaRayHits.empty())
continue;
// ATTN: If seed cannot be grown, abort
CaloHitList deltaRayRemnantHits;
if (this->GrowSeed(element, hitType, deltaRayHits, deltaRayRemnantHits) != STATUS_CODE_SUCCESS)
continue;
if (deltaRayHits.size() == pDeltaRayCluster->GetNCaloHits())
continue;
modifiedClusters.insert(pDeltaRayCluster);
this->SplitDeltaRayCluster(element, hitType, deltaRayHits, deltaRayRemnantHits);
}
}
return !modifiedClusters.empty();
}
//------------------------------------------------------------------------------------------------------------------------------------------
bool TwoViewCosmicRayRemovalTool::PassElementChecks(const MatrixType::Element &element, const HitType hitType) const
{
// ATTN: Avoid endpoints, topological michel reconstruction is very ambiguous
if (this->IsMuonEndpoint(element, hitType))
return false;
const Cluster *pMuonCluster(nullptr), *const pDeltaRayCluster(m_pParentAlgorithm->GetCluster(element, hitType));
if (m_pParentAlgorithm->GetMuonCluster(element.GetOverlapResult().GetCommonMuonPfoList(), hitType, pMuonCluster) != STATUS_CODE_SUCCESS)
return false;
const float separation(LArClusterHelper::GetClosestDistance(pDeltaRayCluster, pMuonCluster));
return separation <= m_minSeparation;
}
//------------------------------------------------------------------------------------------------------------------------------------------
bool TwoViewCosmicRayRemovalTool::IsMuonEndpoint(const MatrixType::Element &element, const HitType hitType) const
{
for (const HitType &otherHitType : m_pParentAlgorithm->GetHitTypeVector())
{
if (otherHitType == hitType)
continue;
const Cluster *pMuonCluster(nullptr), *const pDeltaRayCluster(m_pParentAlgorithm->GetCluster(element, hitType));
if (m_pParentAlgorithm->GetMuonCluster(element.GetOverlapResult().GetCommonMuonPfoList(), hitType, pMuonCluster) != STATUS_CODE_SUCCESS)
return false;
float xMinDR(+std::numeric_limits<float>::max()), xMaxDR(-std::numeric_limits<float>::max());
pDeltaRayCluster->GetClusterSpanX(xMinDR, xMaxDR);
float xMinCR(-std::numeric_limits<float>::max()), xMaxCR(+std::numeric_limits<float>::max());
pMuonCluster->GetClusterSpanX(xMinCR, xMaxCR);
if ((xMinDR < xMinCR) || (xMaxDR > xMaxCR))
return false;
float zMinDR(+std::numeric_limits<float>::max()), zMaxDR(-std::numeric_limits<float>::max());
pDeltaRayCluster->GetClusterSpanZ(xMinDR, xMaxDR, zMinDR, zMaxDR);
float zMinCR(-std::numeric_limits<float>::max()), zMaxCR(+std::numeric_limits<float>::max());
pMuonCluster->GetClusterSpanZ(xMinCR, xMaxCR, zMinCR, zMaxCR);
if ((zMinDR < zMinCR) || (zMaxDR > zMaxCR))
return false;
}
return true;
}
//------------------------------------------------------------------------------------------------------------------------------------------
bool TwoViewCosmicRayRemovalTool::IsContaminated(const MatrixType::Element &element, const HitType hitType) const
{
const Cluster *pMuonCluster(nullptr), *const pDeltaRayCluster(m_pParentAlgorithm->GetCluster(element, hitType));
if (m_pParentAlgorithm->GetMuonCluster(element.GetOverlapResult().GetCommonMuonPfoList(), hitType, pMuonCluster) != STATUS_CODE_SUCCESS)
return false;
const float slidingFitPitch(LArGeometryHelper::GetWireZPitch(this->GetPandora()));
const TwoDSlidingFitResult slidingFitResult(pMuonCluster, m_slidingFitWindow, slidingFitPitch);
CartesianVector muonDirection(0.f, 0.f, 0.f);
slidingFitResult.GetGlobalDirection(slidingFitResult.GetLayerFitResultMap().begin()->second.GetGradient(), muonDirection);
CartesianVector deltaRayVertex(0.f, 0.f, 0.f), muonVertex(0.f, 0.f, 0.f);
LArClusterHelper::GetClosestPositions(pDeltaRayCluster, pMuonCluster, deltaRayVertex, muonVertex);
// Find furthest point in DR cluster that lies on the projected muon track
float furthestSeparation(0.f);
CartesianVector extendedPoint(0.f, 0.f, 0.f);
CaloHitList deltaRayHitList;
pDeltaRayCluster->GetOrderedCaloHitList().FillCaloHitList(deltaRayHitList);
for (const CaloHit *const pCaloHit : deltaRayHitList)
{
const CartesianVector &position(pCaloHit->GetPositionVector());
const float separation((position - muonVertex).GetMagnitude());
if (separation > furthestSeparation)
{
if (this->IsCloseToLine(position, muonVertex, muonVertex + muonDirection, m_distanceToLine))
{
furthestSeparation = separation;
extendedPoint = position;
}
}
}
// Check if delta ray has significant track contamination
if (furthestSeparation < m_minContaminationLength)
return false;
// ATTN: Avoid cases where opening angle is small - it is easy to make mistakes in these instances
CaloHitList muonHitList;
pMuonCluster->GetOrderedCaloHitList().FillCaloHitList(muonHitList);
for (const CaloHit *const pCaloHit : muonHitList)
{
if (this->IsInLineSegment(deltaRayVertex, extendedPoint, pCaloHit->GetPositionVector()))
return false;
}
return true;
}
//------------------------------------------------------------------------------------------------------------------------------------------
bool TwoViewCosmicRayRemovalTool::IsCloseToLine(
const CartesianVector &hitPosition, const CartesianVector &lineStart, const CartesianVector &lineEnd, const float distanceToLine) const
{
CartesianVector lineDirection(lineStart - lineEnd);
lineDirection = lineDirection.GetUnitVector();
const float transverseDistanceFromLine(lineDirection.GetCrossProduct(hitPosition - lineStart).GetMagnitude());
if (transverseDistanceFromLine > distanceToLine)
return false;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------------------
bool TwoViewCosmicRayRemovalTool::IsInLineSegment(
const CartesianVector &lowerBoundary, const CartesianVector &upperBoundary, const CartesianVector &point) const
{
const float segmentBoundaryGradient = (-1.f) * (upperBoundary.GetX() - lowerBoundary.GetX()) / (upperBoundary.GetZ() - lowerBoundary.GetZ());
const float xPointOnUpperLine((point.GetZ() - upperBoundary.GetZ()) / segmentBoundaryGradient + upperBoundary.GetX());
const float xPointOnLowerLine((point.GetZ() - lowerBoundary.GetZ()) / segmentBoundaryGradient + lowerBoundary.GetX());
if (std::fabs(xPointOnUpperLine - point.GetX()) < std::numeric_limits<float>::epsilon())
return true;
if (std::fabs(xPointOnLowerLine - point.GetX()) < std::numeric_limits<float>::epsilon())
return true;
if ((point.GetX() > xPointOnUpperLine) && (point.GetX() > xPointOnLowerLine))
return false;
if ((point.GetX() < xPointOnUpperLine) && (point.GetX() < xPointOnLowerLine))
return false;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------------------
bool TwoViewCosmicRayRemovalTool::IsBestElement(const MatrixType::Element &element, const HitType hitType, const MatrixType::ElementList &elementList) const
{
const float chiSquared(element.GetOverlapResult().GetReducedChiSquared());
const unsigned int hitSum(element.GetCluster1()->GetNCaloHits() + element.GetCluster2()->GetNCaloHits());
for (const MatrixType::Element &testElement : elementList)
{
if (m_pParentAlgorithm->GetCluster(testElement, hitType) != m_pParentAlgorithm->GetCluster(element, hitType))
continue;
if ((testElement.GetCluster1() == element.GetCluster1()) && (testElement.GetCluster2() == element.GetCluster2()))
continue;
const float testChiSquared(testElement.GetOverlapResult().GetReducedChiSquared());
const unsigned int testHitSum(testElement.GetCluster1()->GetNCaloHits() + testElement.GetCluster2()->GetNCaloHits());
if ((testHitSum < hitSum) || ((testHitSum == hitSum) && (testChiSquared > chiSquared)))
continue;
if (this->PassElementChecks(testElement, hitType))
return false;
}
return true;
}
//------------------------------------------------------------------------------------------------------------------------------------------
void TwoViewCosmicRayRemovalTool::CreateSeed(const MatrixType::Element &element, const HitType hitType, CaloHitList &collectedHits) const
{
// To avoid fluctuations, parameterise the muon track
CartesianVector positionOnMuon(0.f, 0.f, 0.f), muonDirection(0.f, 0.f, 0.f);
if (m_pParentAlgorithm->ParameteriseMuon(element.GetOverlapResult().GetCommonMuonPfoList().front(),
m_pParentAlgorithm->GetCluster(element, hitType), positionOnMuon, muonDirection) != STATUS_CODE_SUCCESS)
return;
CartesianPointVector deltaRayProjectedPositions;
if (this->ProjectDeltaRayPositions(element, hitType, deltaRayProjectedPositions) != STATUS_CODE_SUCCESS)
return;
CaloHitList deltaRayHitList;
m_pParentAlgorithm->GetCluster(element, hitType)->GetOrderedCaloHitList().FillCaloHitList(deltaRayHitList);
CaloHitVector deltaRayHitVector(deltaRayHitList.begin(), deltaRayHitList.end());
std::sort(deltaRayHitVector.begin(), deltaRayHitVector.end(), LArClusterHelper::SortHitsByPosition);
for (const CaloHit *const pCaloHit : deltaRayHitVector)
{
const CartesianVector &position(pCaloHit->GetPositionVector());
for (const CartesianVector &projectedPosition : deltaRayProjectedPositions)
{
const float distanceToProjectionSquared((position - projectedPosition).GetMagnitudeSquared());
if (distanceToProjectionSquared < m_maxDistanceToHit * m_maxDistanceToHit)
{
// To prevent gappy seeds
if ((!collectedHits.empty()) && (LArClusterHelper::GetClosestDistance(position, collectedHits) > m_maxDistanceToHit))
continue;
const float distanceToMuonHitsSquared(muonDirection.GetCrossProduct(position - positionOnMuon).GetMagnitudeSquared());
if (distanceToMuonHitsSquared < m_maxDistanceToHit * m_maxDistanceToHit)
continue;
collectedHits.push_back(pCaloHit);
break;
}
}
}
}
//------------------------------------------------------------------------------------------------------------------------------------------
StatusCode TwoViewCosmicRayRemovalTool::GrowSeed(
const MatrixType::Element &element, const HitType hitType, CaloHitList &deltaRayHits, CaloHitList &remnantHits) const
{
const Cluster *const pDeltaRayCluster(m_pParentAlgorithm->GetCluster(element, hitType)), *pMuonCluster(nullptr);
if (m_pParentAlgorithm->GetMuonCluster(element.GetOverlapResult().GetCommonMuonPfoList(), hitType, pMuonCluster) != STATUS_CODE_SUCCESS)
return STATUS_CODE_NOT_FOUND;
// To avoid fluctuatuions, parameterise the muon track
CartesianVector positionOnMuon(0.f, 0.f, 0.f), muonDirection(0.f, 0.f, 0.f);
if (m_pParentAlgorithm->ParameteriseMuon(element.GetOverlapResult().GetCommonMuonPfoList().front(), pDeltaRayCluster, positionOnMuon,
muonDirection) != STATUS_CODE_SUCCESS)
return STATUS_CODE_NOT_FOUND;
// Identify delta ray hits
this->CollectHitsFromDeltaRay(positionOnMuon, muonDirection, pDeltaRayCluster, m_maxDistanceToHit, true, deltaRayHits, deltaRayHits);
// Identify remnant hits
this->CollectHitsFromDeltaRay(positionOnMuon, muonDirection, pDeltaRayCluster, m_maxDistanceToHit, false, deltaRayHits, remnantHits);
return STATUS_CODE_SUCCESS;
}
//------------------------------------------------------------------------------------------------------------------------------------------
void TwoViewCosmicRayRemovalTool::CollectHitsFromDeltaRay(const CartesianVector &positionOnMuon, const CartesianVector &muonDirection,
const Cluster *const pDeltaRayCluster, const float &minDistanceFromMuon, const bool demandCloserToCollected,
const CaloHitList &protectedHits, CaloHitList &collectedHits) const
{
CaloHitList deltaRayHitList;
pDeltaRayCluster->GetOrderedCaloHitList().FillCaloHitList(deltaRayHitList);
bool hitsAdded(false);
do
{
hitsAdded = false;
for (const CaloHit *const pCaloHit : deltaRayHitList)
{
if (std::find(protectedHits.begin(), protectedHits.end(), pCaloHit) != protectedHits.end())
continue;
if (std::find(collectedHits.begin(), collectedHits.end(), pCaloHit) != collectedHits.end())
continue;
const float distanceToCollectedHits(collectedHits.empty()
? std::numeric_limits<float>::max()
: LArClusterHelper::GetClosestDistance(pCaloHit->GetPositionVector(), collectedHits));
const float distanceToMuonHits(muonDirection.GetCrossProduct(pCaloHit->GetPositionVector() - positionOnMuon).GetMagnitude());
if ((distanceToMuonHits < minDistanceFromMuon) || (demandCloserToCollected && (distanceToCollectedHits > distanceToMuonHits)))
continue;
collectedHits.push_back(pCaloHit);
hitsAdded = true;
}
} while (hitsAdded);
}
//------------------------------------------------------------------------------------------------------------------------------------------
void TwoViewCosmicRayRemovalTool::SplitDeltaRayCluster(
const MatrixType::Element &element, const HitType hitType, CaloHitList &collectedHits, CaloHitList &deltaRayRemnantHits) const
{
const Cluster *const pDeltaRayCluster(m_pParentAlgorithm->GetCluster(element, hitType)), *pMuonCluster(nullptr);
if (m_pParentAlgorithm->GetMuonCluster(element.GetOverlapResult().GetCommonMuonPfoList(), hitType, pMuonCluster) != STATUS_CODE_SUCCESS)
return;
m_pParentAlgorithm->UpdateUponDeletion(pMuonCluster);
m_pParentAlgorithm->UpdateUponDeletion(pDeltaRayCluster);
std::string originalListName, fragmentListName;
ClusterList originalClusterList(1, pDeltaRayCluster);
PANDORA_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
PandoraContentApi::ReplaceCurrentList<Cluster>(*m_pParentAlgorithm, m_pParentAlgorithm->GetClusterListName(hitType)));
PANDORA_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
PandoraContentApi::InitializeFragmentation(*m_pParentAlgorithm, originalClusterList, originalListName, fragmentListName));
CaloHitList deltaRayHitList;
pDeltaRayCluster->GetOrderedCaloHitList().FillCaloHitList(deltaRayHitList);
const Cluster *pDeltaRay(nullptr), *pDeltaRayRemnant(nullptr);
for (const CaloHit *const pCaloHit : deltaRayHitList)
{
const bool isDeltaRay(std::find(collectedHits.begin(), collectedHits.end(), pCaloHit) != collectedHits.end());
const bool isDeltaRayRemnant(
!isDeltaRay && (std::find(deltaRayRemnantHits.begin(), deltaRayRemnantHits.end(), pCaloHit) != deltaRayRemnantHits.end()));
const Cluster *&pCluster(isDeltaRay ? pDeltaRay : isDeltaRayRemnant ? pDeltaRayRemnant : pMuonCluster);
if (!pCluster)
{
PandoraContentApi::Cluster::Parameters parameters;
parameters.m_caloHitList.push_back(pCaloHit);
PANDORA_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, PandoraContentApi::Cluster::Create(*m_pParentAlgorithm, parameters, pCluster));
}
else
{
PANDORA_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, PandoraContentApi::AddToCluster(*m_pParentAlgorithm, pCluster, pCaloHit));
}
}
PANDORA_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, PandoraContentApi::EndFragmentation(*m_pParentAlgorithm, fragmentListName, originalListName));
ClusterVector clusterVector;
PfoVector pfoVector;
if (pDeltaRayRemnant)
this->ReclusterRemnant(hitType, pMuonCluster, pDeltaRayRemnant, clusterVector, pfoVector);
clusterVector.push_back(pMuonCluster);
pfoVector.push_back(element.GetOverlapResult().GetCommonMuonPfoList().front());
clusterVector.push_back(pDeltaRay);
pfoVector.push_back(nullptr);
m_pParentAlgorithm->UpdateForNewClusters(clusterVector, pfoVector);
}
//------------------------------------------------------------------------------------------------------------------------------------------
void TwoViewCosmicRayRemovalTool::ReclusterRemnant(const HitType hitType, const Cluster *const pMuonCluster,
const Cluster *const pDeltaRayRemnant, ClusterVector &clusterVector, PfoVector &pfoVector) const
{
std::string caloHitListName(hitType == TPC_VIEW_U ? "CaloHitListU" : hitType == TPC_VIEW_V ? "CaloHitListV" : "CaloHitListW");
PANDORA_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, PandoraContentApi::ReplaceCurrentList<CaloHit>(*m_pParentAlgorithm, caloHitListName));
PANDORA_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
PandoraContentApi::ReplaceCurrentList<Cluster>(*m_pParentAlgorithm, m_pParentAlgorithm->GetClusterListName(hitType)));
PANDORA_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, PandoraContentApi::Delete<Cluster>(*m_pParentAlgorithm, pDeltaRayRemnant));
const ClusterList *pClusterList(nullptr);
std::string newClusterListName;
PANDORA_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
PandoraContentApi::RunClusteringAlgorithm(*m_pParentAlgorithm, m_pParentAlgorithm->GetClusteringAlgName(), pClusterList, newClusterListName));
const ClusterList remnantClusters(pClusterList->begin(), pClusterList->end());
PANDORA_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
PandoraContentApi::SaveList<Cluster>(*m_pParentAlgorithm, newClusterListName, m_pParentAlgorithm->GetClusterListName(hitType)));
PANDORA_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
PandoraContentApi::ReplaceCurrentList<Cluster>(*m_pParentAlgorithm, m_pParentAlgorithm->GetClusterListName(hitType)));
for (const Cluster *const pRemnant : remnantClusters)
{
if (pRemnant->GetNCaloHits() < m_minRemnantClusterSize)
{
if (LArClusterHelper::GetClosestDistance(pRemnant, pMuonCluster) < m_maxDistanceToTrack)
{
PANDORA_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, PandoraContentApi::MergeAndDeleteClusters(*m_pParentAlgorithm, pMuonCluster, pRemnant));
continue;
}
}
clusterVector.push_back(pRemnant);
pfoVector.push_back(nullptr);
}
}
//------------------------------------------------------------------------------------------------------------------------------------------
StatusCode TwoViewCosmicRayRemovalTool::ProjectDeltaRayPositions(
const MatrixType::Element &element, const HitType hitType, CartesianPointVector &projectedPositions) const
{
HitTypeVector hitTypes({TPC_VIEW_U, TPC_VIEW_V, TPC_VIEW_W});
hitTypes.erase(std::find(hitTypes.begin(), hitTypes.end(), hitType));
const Cluster *const pCluster1(m_pParentAlgorithm->GetCluster(element, hitTypes[0]));
const Cluster *const pCluster2(m_pParentAlgorithm->GetCluster(element, hitTypes[1]));
if (!pCluster1 || !pCluster2)
return STATUS_CODE_NOT_FOUND;
return m_pParentAlgorithm->GetProjectedPositions(pCluster1, pCluster2, projectedPositions);
}
//------------------------------------------------------------------------------------------------------------------------------------------
StatusCode TwoViewCosmicRayRemovalTool::ReadSettings(const TiXmlHandle xmlHandle)
{
PANDORA_RETURN_RESULT_IF_AND_IF(STATUS_CODE_SUCCESS, STATUS_CODE_NOT_FOUND, !=, XmlHelper::ReadValue(xmlHandle, "MinSeparation", m_minSeparation));
PANDORA_RETURN_RESULT_IF_AND_IF(
STATUS_CODE_SUCCESS, STATUS_CODE_NOT_FOUND, !=, XmlHelper::ReadValue(xmlHandle, "SlidingFitWindow", m_slidingFitWindow));
PANDORA_RETURN_RESULT_IF_AND_IF(STATUS_CODE_SUCCESS, STATUS_CODE_NOT_FOUND, !=, XmlHelper::ReadValue(xmlHandle, "DistanceToLine", m_distanceToLine));
PANDORA_RETURN_RESULT_IF_AND_IF(
STATUS_CODE_SUCCESS, STATUS_CODE_NOT_FOUND, !=, XmlHelper::ReadValue(xmlHandle, "MinContaminationLength", m_minContaminationLength));
PANDORA_RETURN_RESULT_IF_AND_IF(
STATUS_CODE_SUCCESS, STATUS_CODE_NOT_FOUND, !=, XmlHelper::ReadValue(xmlHandle, "MaxDistanceToHit", m_maxDistanceToHit));
PANDORA_RETURN_RESULT_IF_AND_IF(
STATUS_CODE_SUCCESS, STATUS_CODE_NOT_FOUND, !=, XmlHelper::ReadValue(xmlHandle, "MinRemnantClusterSize", m_minRemnantClusterSize));
PANDORA_RETURN_RESULT_IF_AND_IF(
STATUS_CODE_SUCCESS, STATUS_CODE_NOT_FOUND, !=, XmlHelper::ReadValue(xmlHandle, "MaxDistanceToTrack", m_maxDistanceToTrack));
return STATUS_CODE_SUCCESS;
}
} // namespace lar_content
| gpl-3.0 |
avish/gitextensions | Plugins/GitUIPluginInterfaces/IGitPlugin.cs | 288 | namespace GitUIPluginInterfaces
{
public interface IGitPlugin
{
string Description { get; }
IGitPluginSettingsContainer Settings { get; set; }
void Register(IGitUICommands gitUiCommands);
void Execute(GitUIBaseEventArgs gitUiCommands);
}
} | gpl-3.0 |
murilotimo/moodle | calendar/managesubscriptions_form.php | 6732 | <?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/>.
/**
* Allows the user to manage calendar subscriptions.
*
* @copyright 2012 Jonathan Harker
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package calendar
*/
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
require_once($CFG->libdir.'/formslib.php');
/**
* Form for adding a subscription to a Moodle course calendar.
* @copyright 2012 Jonathan Harker
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class calendar_addsubscription_form extends moodleform {
/**
* Defines the form used to add calendar subscriptions.
*/
public function definition() {
$mform = $this->_form;
$courseid = optional_param('course', 0, PARAM_INT);
$mform->addElement('header', 'addsubscriptionform', get_string('importcalendarheading', 'calendar'));
// Name.
$mform->addElement('text', 'name', get_string('subscriptionname', 'calendar'), array('maxsize' => '255', 'size' => '40'));
$mform->addRule('name', get_string('required'), 'required');
$mform->setType('name', PARAM_TEXT);
// Import from (url | importfile).
$mform->addElement('html', get_string('importfrominstructions', 'calendar'));
$choices = array(CALENDAR_IMPORT_FROM_FILE => get_string('importfromfile', 'calendar'),
CALENDAR_IMPORT_FROM_URL => get_string('importfromurl', 'calendar'));
$mform->addElement('select', 'importfrom', get_string('importcalendarfrom', 'calendar'), $choices);
$mform->setDefault('importfrom', CALENDAR_IMPORT_FROM_URL);
// URL.
$mform->addElement('text', 'url', get_string('importfromurl', 'calendar'), array('maxsize' => '255', 'size' => '50'));
// Cannot set as PARAM_URL since we need to allow webcal:// protocol.
$mform->setType('url', PARAM_RAW);
// Poll interval
$choices = calendar_get_pollinterval_choices();
$mform->addElement('select', 'pollinterval', get_string('pollinterval', 'calendar'), $choices);
$mform->setDefault('pollinterval', 604800);
$mform->addHelpButton('pollinterval', 'pollinterval', 'calendar');
$mform->setType('pollinterval', PARAM_INT);
// Import file
$mform->addElement('filepicker', 'importfile', get_string('importfromfile', 'calendar'), null, array('accepted_types' => '.ics'));
// Disable appropriate elements depending on import from value.
$mform->disabledIf('pollinterval', 'importfrom', 'eq', CALENDAR_IMPORT_FROM_FILE);
$mform->disabledIf('url', 'importfrom', 'eq', CALENDAR_IMPORT_FROM_FILE);
$mform->disabledIf('importfile', 'importfrom', 'eq', CALENDAR_IMPORT_FROM_URL);
// Eventtype: 0 = user, 1 = global, anything else = course ID.
list($choices, $groups) = calendar_get_eventtype_choices($courseid);
$mform->addElement('select', 'eventtype', get_string('eventkind', 'calendar'), $choices);
$mform->addRule('eventtype', get_string('required'), 'required');
$mform->setType('eventtype', PARAM_ALPHA);
if (!empty($groups) and is_array($groups)) {
$groupoptions = array();
foreach ($groups as $group) {
$groupoptions[$group->id] = $group->name;
}
$mform->addElement('select', 'groupid', get_string('typegroup', 'calendar'), $groupoptions);
$mform->setType('groupid', PARAM_INT);
$mform->disabledIf('groupid', 'eventtype', 'noteq', 'group');
}
$mform->addElement('hidden', 'course');
$mform->setType('course', PARAM_INT);
$mform->addElement('submit', 'add', get_string('add'));
}
/**
* Validates the returned data.
*
* @param array $data
* @param array $files
* @return array
*/
public function validation($data, $files) {
global $USER;
$errors = parent::validation($data, $files);
if ($data['importfrom'] == CALENDAR_IMPORT_FROM_FILE) {
if (empty($data['importfile'])) {
$errors['importfile'] = get_string('errorrequiredurlorfile', 'calendar');
} else {
// Make sure the file area is not empty and contains only one file.
$draftitemid = $data['importfile'];
$fs = get_file_storage();
$usercontext = context_user::instance($USER->id);
$files = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id DESC', false);
if (count($files) !== 1) {
$errors['importfile'] = get_string('errorrequiredurlorfile', 'calendar');
}
}
} else if (($data['importfrom'] == CALENDAR_IMPORT_FROM_URL)) {
// Clean input calendar url.
$url = clean_param($data['url'], PARAM_URL);
if (empty($url) || ($url !== $data['url'])) {
$errors['url'] = get_string('invalidurl', 'error');
}
} else {
// Shouldn't happen.
$errors['url'] = get_string('errorrequiredurlorfile', 'calendar');
}
return $errors;
}
public function definition_after_data() {
$mform =& $this->_form;
$mform->applyFilter('url', 'calendar_addsubscription_form::strip_webcal');
$mform->applyFilter('url', 'trim');
}
/**
* Replace webcal:// urls with http:// as
* curl does not understand this protocol
*
* @param string @url url to examine
* @return string url with webcal:// replaced
*/
public static function strip_webcal($url) {
if (strpos($url, 'webcal://') === 0) {
$url = str_replace('webcal://', 'http://', $url);
}
return $url;
}
}
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Fort_Ghelsba/mobs/Orcish_Fodder.lua | 806 | -----------------------------------
-- Area: Fort Ghelsba (141)
-- Mob: Orcish_Fodder
-----------------------------------
-- require("scripts/zones/Fort_Ghelsba/MobIDs");
-----------------------------------
-- onMobInitialize
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
end;
| gpl-3.0 |
wdzhou/mantid | Framework/PythonInterface/mantid/api/src/Exports/Sample.cpp | 3589 | #include "MantidAPI/Sample.h"
#include "MantidGeometry/Crystal/OrientedLattice.h"
#include "MantidGeometry/Crystal/CrystalStructure.h"
#include "MantidKernel/Material.h"
#include "MantidPythonInterface/kernel/GetPointer.h"
#include <boost/python/class.hpp>
#include <boost/python/copy_const_reference.hpp>
#include <boost/python/register_ptr_to_python.hpp>
using Mantid::API::Sample;
using Mantid::Geometry::OrientedLattice;
using Mantid::Kernel::Material;
using namespace boost::python;
GET_POINTER_SPECIALIZATION(Material)
GET_POINTER_SPECIALIZATION(OrientedLattice)
GET_POINTER_SPECIALIZATION(Sample)
void export_Sample() {
register_ptr_to_python<Sample *>();
register_ptr_to_python<boost::shared_ptr<Sample>>();
class_<Sample, boost::noncopyable>("Sample", no_init)
.def("getName", &Sample::getName,
return_value_policy<copy_const_reference>(), arg("self"),
"Returns the string name of the sample")
.def("getOrientedLattice", (const OrientedLattice &(Sample::*)() const) &
Sample::getOrientedLattice,
arg("self"), return_value_policy<reference_existing_object>(),
"Get the oriented lattice for this sample")
.def("hasOrientedLattice", &Sample::hasOrientedLattice, arg("self"),
"Returns True if this sample has an oriented lattice, false "
"otherwise")
.def("getCrystalStructure", &Sample::getCrystalStructure, arg("self"),
return_value_policy<reference_existing_object>(),
"Get the crystal structure for this sample")
.def("hasCrystalStructure", &Sample::hasCrystalStructure, arg("self"),
"Returns True if this sample has a crystal structure, false "
"otherwise")
.def("setCrystalStructure", &Sample::setCrystalStructure,
(arg("self"), arg("newCrystalStructure")),
"Assign a crystal structure object to the sample.")
.def("clearCrystalStructure", &Sample::clearCrystalStructure, arg("self"),
"Removes the internally stored crystal structure.")
.def("size", &Sample::size, arg("self"),
"Return the number of samples contained within this sample")
// Required for ISIS SANS reduction until the full sample geometry is
// defined on loading
.def("getGeometryFlag", &Sample::getGeometryFlag, arg("self"),
"Return the geometry flag.")
.def("getThickness", &Sample::getThickness, arg("self"),
"Return the thickness in mm")
.def("getHeight", &Sample::getHeight, arg("self"),
"Return the height in mm")
.def("getWidth", &Sample::getWidth, arg("self"), "Return the width in mm")
.def("getMaterial", (&Sample::getMaterial), arg("self"),
"The material the sample is composed of")
.def("setGeometryFlag", &Sample::setGeometryFlag,
(arg("self"), arg("geom_id")), "Set the geometry flag.")
.def("setThickness", &Sample::setThickness, (arg("self"), arg("thick")),
"Set the thickness in mm.")
.def("setHeight", &Sample::setHeight, (arg("self"), arg("height")),
"Set the height in mm.")
.def("setWidth", &Sample::setWidth, (arg("self"), arg("width")),
"Set the width in mm.")
// -------------------------Operators
// -------------------------------------
.def("__len__", &Sample::size, arg("self"),
"Gets the number of samples in this collection")
.def("__getitem__", &Sample::operator[], (arg("self"), arg("index")),
return_internal_reference<>());
}
| gpl-3.0 |
thebykov/trufit | wp-content/plugins/codepress-admin-columns/classes/Column/Post/Shortcodes.php | 1171 | <?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Display used shortcodes
*
* @since 2.3.5
*/
class AC_Column_Post_Shortcodes extends AC_Column {
public function __construct() {
$this->set_type( 'column-shortcode' );
$this->set_label( __( 'Shortcodes', 'codepress-admin-columns' ) );
}
public function get_value( $post_id ) {
if ( ! ( $shortcodes = $this->get_raw_value( $post_id ) ) ) {
return false;
}
$display = array();
foreach ( $shortcodes as $sc => $count ) {
$string = '[' . $sc . ']';
if ( $count > 1 ) {
$string .= ac_helper()->html->rounded( $count );
}
$display[ $sc ] = '<span class="ac-spacing">' . $string . '</span>';
}
return implode( ' ', $display );
}
public function get_raw_value( $post_id ) {
global $shortcode_tags;
if ( ! $shortcode_tags ) {
return false;
}
$content = get_post_field( 'post_content', $post_id );
$shortcodes = array();
$_shortcodes = array_keys( $shortcode_tags );
asort( $_shortcodes );
foreach ( $_shortcodes as $sc ) {
if ( $count = substr_count( $content, '[' . $sc ) ) {
$shortcodes[ $sc ] = $count;
}
}
return $shortcodes;
}
}
| gpl-3.0 |
fabriciobizotto/webprogramming | EnemSpring/src/main/java/com/algaworks/pedidovenda/model/Cliente.java | 2360 | package com.algaworks.pedidovenda.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "cliente")
public class Cliente implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String nome;
private String email;
private String documentoReceitaFederal;
private TipoPessoa tipo;
private List<Endereco> enderecos = new ArrayList<>();
@Id
@GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(nullable = false, length = 100)
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
@Column(nullable = false, length = 255)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name = "doc_receita_federal", nullable = false, length = 14)
public String getDocumentoReceitaFederal() {
return documentoReceitaFederal;
}
public void setDocumentoReceitaFederal(String documentoReceitaFederal) {
this.documentoReceitaFederal = documentoReceitaFederal;
}
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 10)
public TipoPessoa getTipo() {
return tipo;
}
public void setTipo(TipoPessoa tipo) {
this.tipo = tipo;
}
@OneToMany(mappedBy = "cliente", cascade = CascadeType.ALL)
public List<Endereco> getEnderecos() {
return enderecos;
}
public void setEnderecos(List<Endereco> enderecos) {
this.enderecos = enderecos;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Cliente other = (Cliente) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
| gpl-3.0 |
sanger-pathogens/Artemis | src/main/java/uk/ac/sanger/artemis/io/SimpleEntryInformation.java | 14627 | /* SimpleEntryInformation.java
*
* created: Wed Feb 9 2000
*
* This file is part of Artemis
*
* Copyright (C) 2000 Genome Research Limited
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* $Header: //tmp/pathsoft/artemis/uk/ac/sanger/artemis/io/SimpleEntryInformation.java,v 1.5 2008-06-26 09:38:54 tjc Exp $
*/
package uk.ac.sanger.artemis.io;
import uk.ac.sanger.artemis.util.*;
/**
* A SimpleEntryInformation is an EntryInformation object allows any key or
* qualifier.
*
* @author Kim Rutherford
* @version $Id: SimpleEntryInformation.java,v 1.5 2008-06-26 09:38:54 tjc Exp $
**/
public class SimpleEntryInformation
implements EntryInformation {
/**
* Create a new SimpleEntryInformation object.
**/
public SimpleEntryInformation () {
}
/**
* Create a new SimpleEntryInformation object which is a copy of the given
* object.
**/
public SimpleEntryInformation (final EntryInformation new_info) {
if (new_info.getAllQualifierInfo () != null) {
qualifier_info_hash = new_info.getAllQualifierInfo ();
}
if (new_info.getValidKeys () != null) {
valid_keys = new_info.getValidKeys ();
}
if (new_info.getUserKeys () != null) {
user_keys = new_info.getUserKeys ().copy ();
}
use_embl_format = new_info.useEMBLFormat ();
}
/**
* Add a new feature key to the list of keys returned by getValidKeys()
* and getSortedValidKeys(). Any key added with this method can have any
* qualifier.
**/
public void addKey (final Key key) {
if (user_keys != null && user_keys.contains (key)) {
return;
}
if (user_keys == null) {
user_keys = new KeyVector ();
}
user_keys.add (key);
}
/**
* Add a QualifierInfo object to this EntryInformation object. This will
* change the return values of getSortedValidKeys() and
* getValidKeys() if the new QualifierInfo object refers to a new key.
* @exception QualifierInfoException Thrown if a QualifierInfo object with
* the same name, but conflicting types has already been added to this
* EntryInformation object.
**/
public void addQualifierInfo (final QualifierInfo qualifier_info)
throws QualifierInfoException {
if (qualifier_info_hash == null) {
qualifier_info_hash = new QualifierInfoHash ();
}
final QualifierInfo current_qualifier_info =
getQualifierInfo (qualifier_info.getName ());
if (current_qualifier_info != null) {
if (qualifier_info.getType () != qualifier_info.UNKNOWN &&
current_qualifier_info.getType () != qualifier_info.getType ()) {
final String message =
"qualifier " + qualifier_info.getName () + " used with " +
"conflicting types";
throw new QualifierInfoException (message);
}
if (qualifier_info.getValidKeys () == null ||
qualifier_info.getRequiredKeys () == null) {
qualifier_info_hash.put (qualifier_info);
}
} else {
qualifier_info_hash.put (qualifier_info);
}
final KeyVector qualifier_valid_keys = qualifier_info.getValidKeys ();
if (qualifier_valid_keys != null) {
for (int i = 0 ; i < qualifier_valid_keys.size () ; ++i) {
final Key this_key = (Key)qualifier_valid_keys.get(i);
if (valid_keys != null && valid_keys.contains (this_key)) {
continue;
}
if (valid_keys == null) {
valid_keys = new KeyVector ();
}
valid_keys.add (this_key);
}
}
}
/**
* Return a vector containing the valid feature keys. The returned
* Vector is a copy.
* @return null if and only if all keys are valid.
**/
public KeyVector getValidKeys () {
if (valid_keys == null) {
if (user_keys == null) {
return null;
} else {
return user_keys.copy ();
}
} else {
final KeyVector return_keys = valid_keys.copy ();
if (user_keys != null) {
for (int i = 0 ; i < user_keys.size () ; ++i) {
if (!return_keys.contains ((Key)user_keys.get (i))) {
return_keys.add ((Key)user_keys.get (i));
}
}
}
return return_keys;
}
}
/**
* Return a alphanumerically sorted vector of the valid keys.
* @return null if and only if all keys are valid.
**/
public KeyVector getSortedValidKeys () {
final KeyVector return_vector = getValidKeys ();
if (return_vector == null) {
return null;
}
return_vector.mysort ();
return return_vector;
}
/**
* Return the Key that should be used when a new (empty) feature is created.
**/
public Key getDefaultKey () {
Key misc_feature_key = new Key ("misc_feature");
if (isValidKey (misc_feature_key))
return misc_feature_key;
misc_feature_key = new Key ("region");
if (isValidKey (misc_feature_key))
return misc_feature_key;
return (Key)getValidKeys ().get (0);
}
/**
* Return a vector containing all valid feature qualifier names for
* features with the given key. The returned StringVector is a copy.
* @return null if and only if any Qualifier is legal.
**/
public StringVector getValidQualifierNames (final Key key) {
if (getQualifierInfoHash () == null) {
return null;
}
final StringVector all_names = getQualifierInfoHash ().names ();
final StringVector return_names = new StringVector ();
for (int i = 0 ; i < all_names.size () ; ++i) {
final QualifierInfo this_qualifier_info =
getQualifierInfoHash ().get ((String)all_names.elementAt (i));
if (this_qualifier_info.isValidFor (key)) {
return_names.add (this_qualifier_info.getName ());
}
}
if (return_names.size () == 0) {
return null;
} else {
return_names.sort ();
return return_names;
}
}
/**
* Return a vector containing the names of the required feature qualifiers
* for the given key.
* @return null if and only if no Qualifier is necessary.
**/
public StringVector getRequiredQualifiers (final Key key) {
if (getQualifierInfoHash () == null) {
return null;
}
final StringVector all_names = getQualifierInfoHash ().names ();
final StringVector return_names = new StringVector ();
for (int i = 0 ; i < all_names.size () ; ++i) {
final QualifierInfo this_qualifier_info =
getQualifierInfoHash ().get ((String)all_names.elementAt (i));
if (this_qualifier_info.isRequiredFor (key)) {
return_names.add (this_qualifier_info.getName ());
}
}
if (return_names.size () == 0) {
return null;
} else {
return_names.sort ();
return return_names;
}
}
/**
* Return true if and only if the given String contains a valid
* qualifier name.
**/
public boolean isValidQualifier (final String name) {
if (getQualifierInfoHash () == null) {
return true;
}
if (getQualifierInfoHash ().get (name) == null) {
return false;
} else {
return true;
}
}
/**
* Return true if and only if given qualifier_name is a legal qualifier
* name for the given key.
**/
public boolean isValidQualifier (final Key key,
final String qualifier_name) {
if (getUserKeys () != null && getUserKeys ().contains (key)) {
// any qualifier is valid for a user key
return true;
}
if (getQualifierInfoHash () == null) {
return true;
}
final QualifierInfo qualifier_info =
getQualifierInfoHash ().get (qualifier_name);
if (qualifier_info == null) {
return false;
} else {
return qualifier_info.isValidFor (key);
}
}
/**
* Return true if and only if given qualifier_name is a legal qualifier
* name for the given key and must be present in a feature with that key.
**/
public boolean isRequiredQualifier (final Key key,
final String qualifier_name) {
if (getUserKeys () != null && getUserKeys ().contains (key)) {
// there are no required qualifiers for a user key
return false;
}
if (getQualifierInfoHash () == null) {
return false;
}
final QualifierInfo qualifier_info =
getQualifierInfoHash ().get (qualifier_name);
if (qualifier_info == null) {
return false;
} else {
return qualifier_info.isRequiredFor (key);
}
}
/**
* Return true if and only if the given key is a valid in this
* EntryInformation.
**/
public boolean isValidKey (final Key key) {
if (valid_keys == null) {
return true;
} else {
if (valid_keys.contains (key)) {
return true;
} else {
if (getUserKeys () != null && getUserKeys ().contains (key)) {
return true;
} else {
return false;
}
}
}
}
/**
* Return the QualifierInfo object for the given qualifier name, or null if
* there are no qualifiers with the given name associated with this
* EntryInformation object.
**/
public QualifierInfo getQualifierInfo (final String qualifier_name) {
if (getQualifierInfoHash () == null) {
return null;
} else {
return getQualifierInfoHash ().get (qualifier_name);
}
}
/**
* Return a default EntryInformation object. It will allow any key or
* qualifier.
**/
public static EntryInformation getDefaultEntryInformation () {
return new SimpleEntryInformation ();
}
/**
* Returns true if strict EMBL format will be used when writing. If true
* qualifiers will always wrap at 80 columns.
* EMBL format locations have the complement (if any) inside the join. eg:
* join(complement(1..100),complement(200..300)).
* The default format has the complement on the outside, which is much more
* readable. eg: complement(join(1..100,200..300))
**/
public boolean useEMBLFormat () {
return use_embl_format;
}
/**
* Set the use_embl_format flag (see useEMBLFormat ()). true means the
* strict EMBL format should be used when writing.
**/
public void setEMBLFormat (final boolean use_embl_format) {
this.use_embl_format = use_embl_format;
}
/**
* Return a Vector contains all the QualifierInfo objects that this
* EntryInformation knows about.
* @return null if and only if there are no QualifierInfo objects in this
* object.
**/
public QualifierInfoHash getAllQualifierInfo () {
if (getQualifierInfoHash () == null) {
return null;
} else {
return getQualifierInfoHash ().copy ();
}
}
/**
* Fix this EntryInformation so that the given exception won't happen
* again.
**/
public void fixException (final EntryInformationException exception) {
if (exception instanceof InvalidKeyException) {
final InvalidKeyException key_exception =
(InvalidKeyException) exception;
addKey (key_exception.getKey ());
}
if (exception instanceof InvalidRelationException) {
final InvalidRelationException relation_exception =
(InvalidRelationException) exception;
if (relation_exception.getQualifier () == null) {
final Key key_to_add = relation_exception.getKey ();
addKey (key_to_add);
} else {
final Qualifier qualifier = relation_exception.getQualifier ();
// change the QualifierInfo object in the EntryInformation so that it
// can handle this key/qualifier combination
final QualifierInfo qualifier_info =
getQualifierInfo (qualifier.getName ());
final QualifierInfo new_qualifier_info;
if (qualifier_info == null) {
new_qualifier_info =
new QualifierInfo (qualifier.getName (),
QualifierInfo.QUOTED_TEXT, null, null, false);
} else {
new_qualifier_info =
new QualifierInfo (qualifier_info.getName (),
qualifier_info.getType (), null, null, false);
}
try {
addQualifierInfo (new_qualifier_info);
} catch (QualifierInfoException e) {
throw new Error ("internal error - unexpected exception: " + e);
}
}
}
if (exception instanceof InvalidQualifierException) {
final String exception_qualifier_name =
((InvalidQualifierException) exception).getQualifier ().getName ();
// add it again, but make it less restrictive
final QualifierInfo new_info =
new QualifierInfo (exception_qualifier_name, QualifierInfo.UNKNOWN,
null, null, false);
try {
addQualifierInfo (new_info);
} catch (QualifierInfoException e) {
throw new Error ("internal error - unexpected exception: " + e);
}
}
}
/**
* Returns the keys that where added with addKey ().
* @return null if and only if there are no user keys yet.
**/
public KeyVector getUserKeys () {
return user_keys;
}
/**
* Return qualifier_info_hash.
**/
private QualifierInfoHash getQualifierInfoHash () {
return qualifier_info_hash;
}
/**
* Returns valid_keys.
**/
private KeyVector getKeys () {
return valid_keys;
}
/**
* This is set by the constructor and addQualifierInfo(). null means
* any qualifier is valid
**/
private QualifierInfoHash qualifier_info_hash = null;
/**
* This is set by the constructor and addQualifierInfo(). null means any
* key is valid
**/
private KeyVector valid_keys = null;
/**
* This is set by the constructor and by addUserKey(). null means any
**/
private KeyVector user_keys = null;
/**
* true if the EMBL location format should be used when writing. (See
* useEMBLLocationFormat () ).
**/
private boolean use_embl_format = false;
}
| gpl-3.0 |
makzk/AnEpicSnake | src/Snake.cpp | 4781 | /*
* File: Snake.cpp
* Author: Jonathan Gutiérrez
*
* Created on 28 de junio de 2014, 08:59 PM
*
* AnEpicSnake v0.5-dev
*
* This file is part of AnEpicSnake, licensed under the GPLv3 license.
* See the NOTICE.txt file for more information.
*/
#include "stdafx.h"
#include "Snake.h"
Snake::Snake() {
reset();
}
Snake::~Snake() {
}
void Snake::move() {
// If the snake growment is not enabled, remove the last square on move
if(!grow) {
points.pop_back();
} else {
// If the snake have grown, stop it
grow = false;
}
SDL_Point n;
switch(direction) {
case UP:
case DOWN:
n.x = points[0].x;
n.y = points[0].y + (direction == DOWN ? 1 : -1);
break;
case LEFT:
case RIGHT:
n.x = points[0].x + (direction == RIGHT ? 1 : -1);
n.y = points[0].y;
}
// Reserve one more space for points vector
points.reserve(points.size()+1);
// Add the new position at the first place
points.insert(points.begin(), n);
// Move the tongue with the new first point position
moveTongue();
// The snake is now moved, this must be updated by direction changement
moved = true;
}
void Snake::draw(SDL_Renderer* renderer) {
// Draw each point of the square
for(Uint16 i = 0; i < points.size(); i++) {
p.x = points[i].x*size;
p.y = points[i].y*size;
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderFillRect(renderer, &p);
}
// Draw eyes
if(direction == UP || direction == LEFT) {
// Sets a square in the up-left first point corner
a.x = points[0].x * size + a.w;
a.y = points[0].y * size + a.h;
} else {
// Sets a square in the down-right first point corner
a.x = points[0].x * size + size - a.w * 2;
a.y = points[0].y * size + size - a.h * 2;
}
if(direction == UP || direction == RIGHT) {
// Sets a square in the up-right first point corner
b.x = points[0].x * size + size - b.w * 2;
b.y = points[0].y * size + b.h;
} else {
// Sets a quare in the down-left first point corner
b.x = points[0].x * size + b.w;
b.y = points[0].y * size + size - b.h * 2;
}
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
SDL_RenderFillRect(renderer, &a);
SDL_RenderFillRect(renderer, &b);
SDL_RenderFillRect(renderer, &tongue);
}
void Snake::moveTongue() {
if(direction == UP || direction == DOWN) {
tongue.w = size / 5;
tongue.h = size / 2;
tongue.x = points[0].x * size + (size / 2) - (tongue.w / 2);
} else {
tongue.w = size / 2;
tongue.h = size / 5;
tongue.y = points[0].y * size + (size / 2) - (tongue.h / 2);
}
switch(direction) {
case UP:
tongue.y = points[0].y * size - tongue.h;
break;
case DOWN:
tongue.y = points[0].y * size + size;
break;
case LEFT:
tongue.x = points[0].x * size - tongue.w;
break;
case RIGHT:
tongue.x = points[0].x * size + size;
break;
}
}
void Snake::reset() {
// Reset every aspect of the snake to its defaults
// TODO: receive parameters for speed, size and direction
direction = RIGHT;
speed = 10;
size = 10;
grow = false;
p.w = size;
p.h = size;
a.w = size / 5;
a.h = a.w;
b.w = a.w;
b.h = a.w;
points.resize(5);
points[0].x = 5; points[0].y = 5;
points[1].x = 4; points[1].y = 5;
points[2].x = 3; points[2].y = 5;
points[3].x = 2; points[3].y = 5;
points[4].x = 1; points[4].y = 5;
moveTongue();
}
void Snake::setSize(int size) {
this->size = size;
p.w = size;
p.h = size;
}
bool Snake::selfCrashed() {
// if the head is at the same place of some point of the snake, it have
// self crashed
for(Uint16 i = 1; i < points.size(); i++) {
if(points[0].x == points[i].x && points[0].y == points[i].y) {
return true;
}
}
return false;
}
int Snake::length() {
return (int) points.size();
}
bool Snake::collides(SDL_Rect* rect) {
// checks if some point is at the same place of some point of the snake
for(Uint16 i = 0; i < points.size(); i++) {
if(points[i].x*size == rect->x && points[i].y*size == rect->y) {
return true;
}
}
return false;
}
SDL_Point Snake::getFirstPoint() {
// gets the head of the snake
return points[0];
}
bool Snake::collidesWithHead(SDL_Rect* rect) {
return (points[0].x*size == rect->x && points[0].y*size == rect->y);
}
| gpl-3.0 |
halayudha/bearded-octo-bugfixes | BestPeerDevelop/sg/edu/nus/protocol/body/CAClientBody.java | 3438 | /*
* @(#) CAClientBody.java 1.0 2006-1-6
*
* Copyright 2006, National University of Singapore.
* All rights reserved.
*/
package sg.edu.nus.protocol.body;
import java.security.cert.Certificate;
/**
* Implement the message body used for communicating with peers which
* contains the user identifier, certificate, signature and other information.
*
* @author Wu Sai
* @author (Modified by) Xu Linhao
* @version 1.0 2006-1-6
*/
public class CAClientBody extends Body {
// private members
private static final long serialVersionUID = 344546576889955456L;
private String userID;
private String groupName; // group name
private String groupInfo; // group information
private String invitedUser; // invite this user to join our group
private String invitedGroup; // add users to this group
private String rawData; // raw data without encrption
private byte[] signaure; // signature
private Certificate certificate; // certificate
/**
* Construct a message body used for commnicating with peers.
*
* @param uid the user identifier
* @param groupName the group name
* @param data the raw data used for evaluating user's validness
* @param sign the signature
*/
public CAClientBody(String uid, String groupName, String data, byte[] sign) {
this.userID = uid;
this.rawData = data;
this.signaure = sign;
this.groupName = groupName;
this.groupInfo = new String();
this.invitedUser = new String();
this.invitedGroup = new String();
}
/**
* Get the user identifier.
*
* @return the user identifier
*/
public String getUserID() {
return userID;
}
/**
* Get the group name.
*
* @return the group name
*/
public String getGroupName() {
return groupName;
}
/**
* Get the group information.
*
* @return the group information
*/
public String getGroupInfo() {
return groupInfo;
}
/**
* Set the group information.
*
* @param s the group information
*/
public void setGroupInfo(String s) {
groupInfo = s;
}
/**
* Get the invited user name.
*
* @return the invited user name
*/
public String getInvitedUser() {
return invitedUser;
}
/**
* Set the invited user name.
*
* @param u the invited user name
*/
public void setInvitedUser(String u) {
invitedUser = u;
}
/**
* Get the invited group name.
*
* @return the invited group name
*/
public String getInvitedGroup() {
return invitedGroup;
}
/**
* Set the invited group name.
*
* @param g the invited group name
*/
public void setInvitedGroup(String g) {
invitedGroup = g;
}
/**
* Get the user's certificate.
*
* @return the user's certificate
*/
public Certificate getCertificate() {
return certificate;
}
/**
* Get the raw data used for evaluating user's validness.
*
* @return the raw data used for evaluating user's validness
*/
public String getData() {
return rawData;
}
/**
* Get the signature.
*
* @return the signature
*/
public byte[] getSignature() {
return signaure;
}
/**
* Set the user's certificate
*
* @param cert the user's certificate
*/
public void setCertificate(Certificate cert) {
this.certificate = cert;
}
@Override
public String toString() {
String delim = ":";
String result = "CAClientBody format:= userID:Certificate:data\r\n";
result = result + userID + delim + certificate.toString() + delim
+ rawData;
return result;
}
}
| gpl-3.0 |
Puzzlout/EasyMvc | Library/Core/HttpRequest.php | 4889 | <?php
namespace Library\Core;
if (!FrameworkConstants_ExecutionAccessRestriction) {
exit('No direct script access allowed');
}
class HttpRequest {
public $requestId;
public function __construct() {
$this->requestId = \Library\Utility\UUID::v4();
}
public function requestId() {
return $this->requestId;
}
public function setRequestId($requestId) {
$this->requestId = $requestId;
}
public function cookieData($key) {
$isKeyFound = $this->cookieExists($key);
if (!$isKeyFound) {
throw \Exception($key . ' is not present in the $_COOKIE', 0, null);
}
$result = filter_input(INPUT_COOKIE, $key);
return $result;
}
public function cookieExists($key) {
$result = filter_input(INPUT_COOKIE, $key);
if (is_null($result)) {
return false;
}
return isset($result);
}
public function getData($key) {
return $this->getExists($key) ? $_GET[$key] : null;
}
public function getExists($key) {
return isset($_GET[$key]);
}
public function method() {
return $_SERVER['REQUEST_METHOD'];
}
public function postData($key) {
return isset($_POST[$key]) ? $_POST[$key] : null;
}
public function postExists($key) {
return isset($_POST[$key]);
}
public function requestURI() {
$key = 'REQUEST_URI';
if (!array_key_exists($key, $_SERVER)) {
throw new Exception($key . ' is not set in $_SERVER. See dump above.' . var_dump($_SERVER), 0, NULL);
}
return strtok($_SERVER[$key], '?');
}
protected function requestType() {
$key = 'REQUEST_METHOD';
if (!array_key_exists($key, $_SERVER)) {
throw new Exception($key . ' is not set in $_SERVER. See dump above.' . var_dump($_SERVER), 0, NULL);
}
return $_SERVER[$key];
}
public function IsPost() {
if ($this->requestType() === "POST") {
return TRUE;
} else {
return FALSE;
}
}
public function initLanguage(Application $currentApp, $type) {
if ($type === "default") {
return $currentApp->config()->get(Enums\AppSettingKeys::DefaultLanguage);
}
if ($type === "browser") {
//Get the first culture
$culture = substr(strtok($_SERVER['HTTP_ACCEPT_LANGUAGE'], '?'), 0, 5);
//Check if the first culture is a short or long version, i.e. en ou en-US.
//If it is the short version, we update the culture to return.
if (!strpos($culture, "-"))
$culture = substr($culture, 0, 2);
return $culture;
}
}
/**
* Fetch the POST data from the php://input array which is compatible with
* modern post requests.
* We keep the old $_POST source for the time being, even if it will be
* depreaced.
*
* @access public
* @param bool
* @return array The POST data (associative array if necessary)
*/
public function retrievePostAjaxData($xss_clean = TRUE) {
$postData = $this->ParseDataFromPhpInput();
if (count($postData) > 0) {
return $postData;
}
$postData = $this->ParseDataFromGlobalVar();
return $postData;
}
/**
* Retrieve the POST data from php://input
* @return array The POST data (associative array if necessary)
*/
private function ParseDataFromPhpInput() {
if (file_get_contents('php://input') == "") {
return array();
}
$jsonDecodedData = json_decode(file_get_contents('php://input'));
if (is_null($jsonDecodedData)) {
return array();
}
$postData = get_object_vars($jsonDecodedData);
if (empty($postData)) {
return array();
}
return $postData;
}
/**
* Retrieve the POST data from $_POST super global
* @return array The POST data (associative array if necessary)
*/
private function ParseDataFromGlobalVar() {
$postData = filter_input_array(INPUT_POST);
if(is_null($postData)) {
return array();
}
$postDataCleaned = $this->FetchData($postData);
return $postDataCleaned;
}
private function FetchData($postDataRaw) {
foreach (array_keys($postDataRaw) as $key) {
$postDataCleaned[$key] = $this->ValidateData($postDataRaw, $key, TRUE);
}
return $postDataCleaned;
}
// --------------------------------------------------------------------
/**
* Fetch from array
*
* This is a helper function to retrieve values from global arrays
*
* @access private
* @param array
* @param string
* @param bool
* @return string
*/
private function ValidateData(&$array, $index = '', $xss_clean = FALSE) {
if (!isset($array[$index])) {
return FALSE;
}
if ($xss_clean === TRUE && !($array[$index] instanceof \stdClass)) {
$array[$index] = strip_tags($array[$index]);
$array[$index] = filter_var($array[$index]);
//$security = new BL\Security\Security();
//return $security->xss_clean($array[$index]);
}
return $array[$index];
}
}
| gpl-3.0 |
kplian/pxp | lib/ux/GMapPanel(2).js | 6665 | /*!
* Ext JS Library 3.3.0
* Copyright(c) 2006-2010 Ext JS, Inc.
* licensing@extjs.com
* http://www.extjs.com/license
*/
/**
* @class Ext.ux.GMapPanel
* @extends Ext.Panel
* @author Shea Frederick
*/
Ext.ux.GMapPanel = Ext.extend(Ext.Panel, {
initComponent : function(){
var defConfig = {
plain: true,
zoomLevel: 3,
yaw: 180,
pitch: 0,
zoom: 0,
gmapType: 'map',
border: false
};
Ext.applyIf(this,defConfig);
Ext.ux.GMapPanel.superclass.initComponent.call(this);
},
afterRender : function(){
var wh = this.ownerCt.getSize();
Ext.applyIf(this, wh);
Ext.ux.GMapPanel.superclass.afterRender.call(this);
if (this.gmapType === 'map'){
this.gmap = new GMap2(this.body.dom);
}
if (this.gmapType === 'panorama'){
this.gmap = new GStreetviewPanorama(this.body.dom);
}
if (typeof this.addControl == 'object' && this.gmapType === 'map') {
this.gmap.addControl(this.addControl);
}
if (typeof this.setCenter === 'object') {
if (typeof this.setCenter.geoCodeAddr === 'string'){
this.geoCodeLookup(this.setCenter.geoCodeAddr);
}else{
if (this.gmapType === 'map'){
var point = new GLatLng(this.setCenter.lat,this.setCenter.lng);
this.gmap.setCenter(point, this.zoomLevel);
}
if (typeof this.setCenter.marker === 'object' && typeof point === 'object'){
this.addMarker(point,this.setCenter.marker,this.setCenter.marker.clear);
}
}
if (this.gmapType === 'panorama'){
this.gmap.setLocationAndPOV(new GLatLng(this.setCenter.lat,this.setCenter.lng), {yaw: this.yaw, pitch: this.pitch, zoom: this.zoom});
}
}
GEvent.bind(this.gmap, '', this, function(){
this.onMapReady();
});
},
onMapReady : function(){
this.addMarkers(this.markers);
this.addMapControls();
this.addOptions();
},
onResize : function(w, h){
if (typeof this.getMap() == 'object') {
this.gmap.checkResize();
}
Ext.ux.GMapPanel.superclass.onResize.call(this, w, h);
},
setSize : function(width, height, animate){
if (typeof this.getMap() == 'object') {
this.gmap.checkResize();
}
Ext.ux.GMapPanel.superclass.setSize.call(this, width, height, animate);
},
getMap : function(){
return this.gmap;
},
getCenter : function(){
return this.getMap().getCenter();
},
getCenterLatLng : function(){
var ll = this.getCenter();
return {lat: ll.lat(), lng: ll.lng()};
},
addMarkers : function(markers) {
if (Ext.isArray(markers)){
for (var i = 0; i < markers.length; i++) {
var mkr_point = new GLatLng(markers[i].lat,markers[i].lng);
this.addMarker(mkr_point,markers[i].marker,false,markers[i].setCenter, markers[i].listeners);
}
}
},
addMarker : function(point, marker, clear, center, listeners){
Ext.applyIf(marker,G_DEFAULT_ICON);
if (clear === true){
this.getMap().clearOverlays();
}
if (center === true) {
this.getMap().setCenter(point, this.zoomLevel);
}
var mark = new GMarker(point,marker);
if (typeof listeners === 'object'){
for (evt in listeners) {
GEvent.bind(mark, evt, this, listeners[evt]);
}
}
this.getMap().addOverlay(mark);
},
addMapControls : function(){
if (this.gmapType === 'map') {
if (Ext.isArray(this.mapControls)) {
for(i=0;i<this.mapControls.length;i++){
this.addMapControl(this.mapControls[i]);
}
}else if(typeof this.mapControls === 'string'){
this.addMapControl(this.mapControls);
}else if(typeof this.mapControls === 'object'){
this.getMap().addControl(this.mapControls);
}
}
},
addMapControl : function(mc){
var mcf = window[mc];
if (typeof mcf === 'function') {
this.getMap().addControl(new mcf());
}
},
addOptions : function(){
if (Ext.isArray(this.mapConfOpts)) {
var mc;
for(i=0;i<this.mapConfOpts.length;i++){
this.addOption(this.mapConfOpts[i]);
}
}else if(typeof this.mapConfOpts === 'string'){
this.addOption(this.mapConfOpts);
}
},
addOption : function(mc){
var mcf = this.getMap()[mc];
if (typeof mcf === 'function') {
this.getMap()[mc]();
}
},
geoCodeLookup : function(addr) {
this.geocoder = new GClientGeocoder();
this.geocoder.getLocations(addr, this.addAddressToMap.createDelegate(this));
},
addAddressToMap : function(response) {
if (!response || response.Status.code != 200) {
Ext.MessageBox.alert('Error', 'Code '+response.Status.code+' Error Returned');
}else{
place = response.Placemark[0];
addressinfo = place.AddressDetails;
accuracy = addressinfo.Accuracy;
if (accuracy === 0) {
Ext.MessageBox.alert('Unable to Locate Address', 'Unable to Locate the Address you provided');
}else{
if (accuracy < 7) {
Ext.MessageBox.alert('Address Accuracy', 'The address provided has a low accuracy.<br><br>Level '+accuracy+' Accuracy (8 = Exact Match, 1 = Vague Match)');
}else{
point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
if (typeof this.setCenter.marker === 'object' && typeof point === 'object'){
this.addMarker(point,this.setCenter.marker,this.setCenter.marker.clear,true, this.setCenter.listeners);
}
}
}
}
}
});
Ext.reg('gmappanel', Ext.ux.GMapPanel); | gpl-3.0 |